• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "include/flutter/json_message_codec.h"
6 
7 #include <iostream>
8 #include <string>
9 
10 #ifdef USE_RAPID_JSON
11 #include "rapidjson/error/en.h"
12 #include "rapidjson/stringbuffer.h"
13 #include "rapidjson/writer.h"
14 #endif
15 
16 namespace flutter {
17 
18 // static
GetInstance()19 const JsonMessageCodec& JsonMessageCodec::GetInstance() {
20   static JsonMessageCodec sInstance;
21   return sInstance;
22 }
23 
EncodeMessageInternal(const JsonValueType & message) const24 std::unique_ptr<std::vector<uint8_t>> JsonMessageCodec::EncodeMessageInternal(
25     const JsonValueType& message) const {
26 #ifdef USE_RAPID_JSON
27   // TODO: Look into alternate writers that would avoid the buffer copy.
28   rapidjson::StringBuffer buffer;
29   rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
30   message.Accept(writer);
31   const char* buffer_start = buffer.GetString();
32   return std::make_unique<std::vector<uint8_t>>(
33       buffer_start, buffer_start + buffer.GetSize());
34 #else
35   Json::StreamWriterBuilder writer_builder;
36   std::string serialization = Json::writeString(writer_builder, message);
37   return std::make_unique<std::vector<uint8_t>>(serialization.begin(),
38                                                 serialization.end());
39 #endif
40 }
41 
DecodeMessageInternal(const uint8_t * binary_message,const size_t message_size) const42 std::unique_ptr<JsonValueType> JsonMessageCodec::DecodeMessageInternal(
43     const uint8_t* binary_message,
44     const size_t message_size) const {
45   auto raw_message = reinterpret_cast<const char*>(binary_message);
46   auto json_message = std::make_unique<JsonValueType>();
47   std::string parse_errors;
48   bool parsing_successful = false;
49 #ifdef USE_RAPID_JSON
50   rapidjson::ParseResult result =
51       json_message->Parse(raw_message, message_size);
52   parsing_successful = result == rapidjson::ParseErrorCode::kParseErrorNone;
53   if (!parsing_successful) {
54     parse_errors = rapidjson::GetParseError_En(result.Code());
55   }
56 #else
57   Json::CharReaderBuilder reader_builder;
58   std::unique_ptr<Json::CharReader> parser(reader_builder.newCharReader());
59   parsing_successful = parser->parse(raw_message, raw_message + message_size,
60                                      json_message.get(), &parse_errors);
61 #endif
62   if (!parsing_successful) {
63     std::cerr << "Unable to parse JSON message:" << std::endl
64               << parse_errors << std::endl;
65     return nullptr;
66   }
67   return json_message;
68 }
69 
70 }  // namespace flutter
71