serializer.cpp 13.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
/* This file is part of qjson
  *
  * Copyright (C) 2009 Till Adam <adam@kde.org>
  * Copyright (C) 2009 Flavio Castelli <flavio@castelli.name>
  * Copyright (C) 2016 Anton Kudryavtsev <a.kudryavtsev@netris.ru>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License version 2.1, as published by the Free Software Foundation.
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public License
  * along with this library; see the file COPYING.LIB.  If not, write to
  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  * Boston, MA 02110-1301, USA.
  */

#include "serializer.h"

#include <QtCore/QDataStream>
#include <QtCore/QStringList>
#include <QtCore/QVariant>

// cmath does #undef for isnan and isinf macroses what can be defined in math.h
#if defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID) || defined(Q_OS_BLACKBERRY) || defined(Q_OS_SOLARIS)
# include <math.h>
#else
# include <cmath>
#endif

#ifdef Q_OS_SOLARIS
# ifndef isinf
#  include <ieeefp.h>
#  define isinf(x) (!finite((x)) && (x)==(x))
# endif
#endif

#ifdef _MSC_VER  // using MSVC compiler
#include <float.h>
#endif

using namespace QJson;

class Serializer::SerializerPrivate {
  public:
    SerializerPrivate() :
      specialNumbersAllowed(false),
      indentMode(QJson::IndentNone),
      doublePrecision(6) {
        errorMessage.clear();
    }
    QString errorMessage;
    bool specialNumbersAllowed;
    IndentMode indentMode;
    int doublePrecision;

    QByteArray serialize( const QVariant &v, bool *ok, int indentLevel = 0);

    static QByteArray buildIndent(int spaces);
    static QByteArray escapeString( const QString& str );
    static QByteArray join( const QList<QByteArray>& list, const QByteArray& sep );
    static QByteArray join( const QList<QByteArray>& list, char sep );
};

QByteArray Serializer::SerializerPrivate::join( const QList<QByteArray>& list, const QByteArray& sep ) {
  QByteArray res;
  Q_FOREACH( const QByteArray& i, list ) {
    if ( !res.isEmpty() )
      res += sep;
    res += i;
  }
  return res;
}

QByteArray Serializer::SerializerPrivate::join( const QList<QByteArray>& list, char sep ) {
  QByteArray res;
  Q_FOREACH( const QByteArray& i, list ) {
    if ( !res.isEmpty() )
      res += sep;
    res += i;
  }
  return res;
}

QByteArray Serializer::SerializerPrivate::serialize( const QVariant &v, bool *ok, int indentLevel)
{
  QByteArray str;
  const QVariant::Type type = v.type();

  if ( ! v.isValid() ) { // invalid or null?
    str = "null";
  } else if (( type == QVariant::List ) || ( type == QVariant::StringList )) { // an array or a stringlist?
    const QVariantList list = v.toList();
    QList<QByteArray> values;
    Q_FOREACH( const QVariant& var, list )
    {
      QByteArray serializedValue;

      serializedValue = serialize( var, ok, indentLevel+1);

      if ( !*ok ) {
        break;
      }
      switch(indentMode) {
        case QJson::IndentFull :
        case QJson::IndentMedium :
        case QJson::IndentMinimum :
          values << serializedValue;
          break;
        case QJson::IndentCompact :
        case QJson::IndentNone :
        default:
          values << serializedValue.trimmed();
          break;
      }
    }

    if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull ) {
      QByteArray indent = buildIndent(indentLevel);
      str = indent + "[\n" + join( values, ",\n" ) + '\n' + indent + ']';
    }
    else if (indentMode == QJson::IndentMinimum) {
      QByteArray indent = buildIndent(indentLevel);
      str = indent + "[\n" + join( values, ",\n" ) + '\n' + indent + ']';
    }
    else if (indentMode == QJson::IndentCompact) {
      str = '[' + join( values, "," ) + ']';
    }
    else {
      str = "[ " + join( values, ", " ) + " ]";
    }

  } else if ( type == QVariant::Map ) { // variant is a map?
    const QVariantMap vmap = v.toMap();

    if (indentMode == QJson::IndentMinimum) {
      QByteArray indent = buildIndent(indentLevel);
      str = indent + "{ ";
    }
    else if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {
      QByteArray indent = buildIndent(indentLevel);
      QByteArray nextindent = buildIndent(indentLevel + 1);
      str = indent + "{\n" + nextindent;
    }
    else if (indentMode == QJson::IndentCompact) {
      str = "{";
    }
    else {
      str = "{ ";
    }

    QList<QByteArray> pairs;
    for (QVariantMap::const_iterator it = vmap.begin(), end = vmap.end(); it != end; ++it) {
      indentLevel++;
      QByteArray serializedValue = serialize( it.value(), ok, indentLevel);
      indentLevel--;
      if ( !*ok ) {
        break;
      }
      QByteArray key   = escapeString( it.key() );
      QByteArray value = serializedValue.trimmed();
      if (indentMode == QJson::IndentCompact) {
        pairs << key + ':' + value;
      } else {
        pairs << key + " : " + value;
      }
    }

    if (indentMode == QJson::IndentFull) {
      QByteArray indent = buildIndent(indentLevel + 1);
      str += join( pairs, ",\n" + indent);
    }
    else if (indentMode == QJson::IndentCompact) {
      str += join( pairs, ',' );
    }
    else {
      str += join( pairs, ", " );
    }

    if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {
      QByteArray indent = buildIndent(indentLevel);
      str += '\n' + indent + '}';
    }
    else if (indentMode == QJson::IndentCompact) {
      str += '}';
    }
    else {
      str += " }";
    }

  } else if ( type == QVariant::Hash ) { // variant is a hash?
    const QVariantHash vhash = v.toHash();

    if (indentMode == QJson::IndentMinimum) {
      QByteArray indent = buildIndent(indentLevel);
      str = indent + "{ ";
    }
    else if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {
      QByteArray indent = buildIndent(indentLevel);
      QByteArray nextindent = buildIndent(indentLevel + 1);
      str = indent + "{\n" + nextindent;
    }
    else if (indentMode == QJson::IndentCompact) {
      str = "{";
    }
    else {
      str = "{ ";
    }

    QList<QByteArray> pairs;
    for (QVariantHash::const_iterator it = vhash.begin(), end = vhash.end(); it != end; ++it) {
      QByteArray serializedValue = serialize( it.value(), ok, indentLevel + 1);

      if ( !*ok ) {
        break;
      }
      QByteArray key   = escapeString( it.key() );
      QByteArray value = serializedValue.trimmed();
      if (indentMode == QJson::IndentCompact) {
        pairs << key + ':' + value;
      } else {
        pairs << key + " : " + value;
      }
    }

    if (indentMode == QJson::IndentFull) {
      QByteArray indent = buildIndent(indentLevel + 1);
      str += join( pairs, ",\n" + indent);
    }
    else if (indentMode == QJson::IndentCompact) {
      str += join( pairs, ',' );
    }
    else {
      str += join( pairs, ", " );
    }

    if (indentMode == QJson::IndentMedium || indentMode == QJson::IndentFull) {
      QByteArray indent = buildIndent(indentLevel);
      str += '\n' + indent + '}';
    }
    else if (indentMode == QJson::IndentCompact) {
      str += '}';
    }
    else {
      str += " }";
    }

  } else {
    // Add indent, we may need to remove it later for some layouts
    switch(indentMode) {
      case QJson::IndentFull :
      case QJson::IndentMedium :
      case QJson::IndentMinimum :
        str += buildIndent(indentLevel);
        break;
      case QJson::IndentCompact :
      case QJson::IndentNone :
      default:
        break;
    }

    if (( type == QVariant::String ) ||  ( type == QVariant::ByteArray )) { // a string or a byte array?
      str += escapeString( v.toString() );
    } else if (( type == QVariant::Double) || ((QMetaType::Type)type == QMetaType::Float)) { // a double or a float?
      const double value = v.toDouble();
  #if defined _WIN32 && !defined(Q_OS_SYMBIAN)
      const bool special = _isnan(value) || !_finite(value);
  #elif defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID) || defined(Q_OS_BLACKBERRY) || defined(Q_OS_SOLARIS)
      const bool special = isnan(value) || isinf(value);
  #else
      const bool special = std::isnan(value) || std::isinf(value);
  #endif
      if (special) {
        if (specialNumbersAllowed) {
  #if defined _WIN32 && !defined(Q_OS_SYMBIAN)
          if (_isnan(value)) {
  #elif defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID) || defined(Q_OS_BLACKBERRY) || defined(Q_OS_SOLARIS)
          if (isnan(value)) {
  #else
          if (std::isnan(value)) {
  #endif
            str += "NaN";
          } else {
            if (value<0) {
              str += '-';
            }
            str += "Infinity";
          }
        } else {
          errorMessage += QLatin1String("Attempt to write NaN or infinity, which is not supported by json\n");
          *ok = false;
      }
      } else {
        str = QByteArray::number( value , 'g', doublePrecision);
        if( !str.contains( '.' ) && !str.contains( 'e' ) ) {
          str += ".0";
        }
      }
    } else if ( type == QVariant::Bool ) { // boolean value?
      str += ( v.toBool() ? "true" : "false" );
    } else if ( type == QVariant::ULongLong ) { // large unsigned number?
      str += QByteArray::number( v.value<qulonglong>() );
    } else if ( type == QVariant::UInt ) { // unsigned int number?
      str += QByteArray::number( v.value<quint32>() );
    } else if ( v.canConvert<qlonglong>() ) { // any signed number?
      str += QByteArray::number( v.value<qlonglong>() );
    } else if ( v.canConvert<int>() ) { // unsigned short number?
      str += QByteArray::number( v.value<int>() );
    } else if ( v.canConvert<QString>() ){ // can value be converted to string?
      // this will catch QDate, QDateTime, QUrl, ...
      str += escapeString( v.toString() );
      //TODO: catch other values like QImage, QRect, ...
    } else {
      *ok = false;
      errorMessage += QLatin1String("Cannot serialize ");
      errorMessage += v.toString();
      errorMessage += QLatin1String(" because type ");
      errorMessage += QLatin1String(v.typeName());
      errorMessage += QLatin1String(" is not supported by QJson\n");
    }
  }
  if ( *ok )
  {
    return str;
  }
  else
    return QByteArray();
}

QByteArray Serializer::SerializerPrivate::buildIndent(int spaces)
{
   QByteArray indent;
   if (spaces < 0) {
     spaces = 0;
   }
   for (int i = 0; i < spaces; i++ ) {
     indent += ' ';
   }
   return indent;
}

QByteArray Serializer::SerializerPrivate::escapeString( const QString& str )
{
  QByteArray result;
  result.reserve(str.size() + 2);
  result.append('\"');
  for (QString::const_iterator it = str.begin(), end = str.end(); it != end; ++it) {
    ushort unicode = it->unicode();
    switch ( unicode ) {
      case '\"':
        result.append("\\\"");
        break;
      case '\\':
        result.append("\\\\");
        break;
      case '\b':
        result.append("\\b");
        break;
      case '\f':
        result.append("\\f");
        break;
      case '\n':
        result.append("\\n");
        break;
      case '\r':
        result.append("\\r");
        break;
      case '\t':
        result.append("\\t");
        break;
      default:
        if ( unicode > 0x1F && unicode < 128 ) {
          result.append(static_cast<char>(unicode));
        } else {
          char escaped[7];
          qsnprintf(escaped, sizeof(escaped)/sizeof(char), "\\u%04x", unicode);
          result.append(escaped);
        }
    }
  }
  result.append('\"');
  return result;
}

Serializer::Serializer()
  : d( new SerializerPrivate )
{
}

Serializer::~Serializer() {
  delete d;
}

void Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok)
{
  Q_ASSERT( io );
  *ok = true;

  if (!io->isOpen()) {
    if (!io->open(QIODevice::WriteOnly)) {
      d->errorMessage = QLatin1String("Error opening device");
      *ok = false;
      return;
    }
  }

  if (!io->isWritable()) {
    d->errorMessage = QLatin1String("Device is not readable");
    io->close();
    *ok = false;
    return;
  }

  const QByteArray str = serialize( v, ok);
  if (*ok && (io->write(str) != str.count())) {
    *ok = false;
    d->errorMessage = QLatin1String("Something went wrong while writing to IO device");
  }
}

QByteArray Serializer::serialize( const QVariant &v)
{
  bool ok;

  return serialize(v, &ok);
}

QByteArray Serializer::serialize( const QVariant &v, bool *ok)
{
  bool _ok = true;
  d->errorMessage.clear();

  if (ok) {
    *ok = true;
  } else {
    ok = &_ok;
  }

  return d->serialize(v, ok);
}

void QJson::Serializer::allowSpecialNumbers(bool allow) {
  d->specialNumbersAllowed = allow;
}

bool QJson::Serializer::specialNumbersAllowed() const {
  return d->specialNumbersAllowed;
}

void QJson::Serializer::setIndentMode(IndentMode mode) {
  d->indentMode = mode;
}

void QJson::Serializer::setDoublePrecision(int precision) {
  d->doublePrecision = precision;
}

IndentMode QJson::Serializer::indentMode() const {
  return d->indentMode;
}

QString QJson::Serializer::errorMessage() const {
  return d->errorMessage;
}