json.cc 1.58 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/torque/ls/json.h"

#include <iostream>
#include <sstream>
#include "src/torque/utils.h"

namespace v8 {
namespace internal {
namespace torque {
namespace ls {

namespace {

void SerializeToString(std::stringstream& str, const JsonValue& value) {
  switch (value.tag) {
    case JsonValue::NUMBER:
21
      str << value.ToNumber();
22 23
      break;
    case JsonValue::STRING:
24
      str << StringLiteralQuote(value.ToString());
25 26
      break;
    case JsonValue::IS_NULL:
27
      str << "null";
28 29
      break;
    case JsonValue::BOOL:
30
      str << (value.ToBool() ? "true" : "false");
31 32 33 34
      break;
    case JsonValue::OBJECT: {
      str << "{";
      size_t i = 0;
35
      for (const auto& pair : value.ToObject()) {
36 37
        str << "\"" << pair.first << "\":";
        SerializeToString(str, pair.second);
38
        if (++i < value.ToObject().size()) str << ",";
39 40 41 42 43 44 45
      }
      str << "}";
      break;
    }
    case JsonValue::ARRAY: {
      str << "[";
      size_t i = 0;
46
      for (const auto& element : value.ToArray()) {
47
        SerializeToString(str, element);
48
        if (++i < value.ToArray().size()) str << ",";
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
      }
      str << "]";
      break;
    }
    default:
      break;
  }
}

}  // namespace

std::string SerializeToString(const JsonValue& value) {
  std::stringstream result;
  SerializeToString(result, value);
  return result.str();
}

}  // namespace ls
}  // namespace torque
}  // namespace internal
}  // namespace v8