Flutter Engine
json_message_codec.cc
Go to the documentation of this file.
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 "flutter/shell/platform/common/cpp/json_message_codec.h"
6 
7 #include <iostream>
8 #include <string>
9 
10 #include "rapidjson/error/en.h"
11 #include "rapidjson/stringbuffer.h"
12 #include "rapidjson/writer.h"
13 
14 namespace flutter {
15 
16 // static
18  static JsonMessageCodec sInstance;
19  return sInstance;
20 }
21 
22 std::unique_ptr<std::vector<uint8_t>> JsonMessageCodec::EncodeMessageInternal(
23  const rapidjson::Document& message) const {
24  // TODO: Look into alternate writers that would avoid the buffer copy.
25  rapidjson::StringBuffer buffer;
26  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
27  message.Accept(writer);
28  const char* buffer_start = buffer.GetString();
29  return std::make_unique<std::vector<uint8_t>>(
30  buffer_start, buffer_start + buffer.GetSize());
31 }
32 
33 std::unique_ptr<rapidjson::Document> JsonMessageCodec::DecodeMessageInternal(
34  const uint8_t* binary_message,
35  const size_t message_size) const {
36  auto raw_message = reinterpret_cast<const char*>(binary_message);
37  auto json_message = std::make_unique<rapidjson::Document>();
38  rapidjson::ParseResult result =
39  json_message->Parse(raw_message, message_size);
40  bool parsing_successful =
41  result == rapidjson::ParseErrorCode::kParseErrorNone;
42  if (!parsing_successful) {
43  std::cerr << "Unable to parse JSON message:" << std::endl
44  << rapidjson::GetParseError_En(result.Code()) << std::endl;
45  return nullptr;
46  }
47  return json_message;
48 }
49 
50 } // namespace flutter
std::unique_ptr< std::vector< uint8_t > > EncodeMessageInternal(const rapidjson::Document &message) const override
std::unique_ptr< rapidjson::Document > DecodeMessageInternal(const uint8_t *binary_message, const size_t message_size) const override
static const JsonMessageCodec & GetInstance()