Implement StandardMethodCodec for C++ shells (flutter/engine#8598)

Adds StandardMethodCodec support to the C++ client wrapper. This makes it
substantially easier to add Windows and Linux support for existing plugins, as
StandardMethodCodec is the default plugin protocol.

Fixes flutter/flutter#30670

Does not include extensibility for the codec, which will be added later.
This commit is contained in:
stuartmorgan
2019-04-16 19:49:09 -07:00
committed by GitHub
parent 4525e1eef2
commit 922d6df36f
15 changed files with 1046 additions and 8 deletions

View File

@@ -560,6 +560,7 @@ FILE: ../../../flutter/shell/platform/android/platform_view_android_jni.cc
FILE: ../../../flutter/shell/platform/android/platform_view_android_jni.h
FILE: ../../../flutter/shell/platform/android/vsync_waiter_android.cc
FILE: ../../../flutter/shell/platform/android/vsync_waiter_android.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/byte_stream_wrappers.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/encodable_value_unittests.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/engine_method_result.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/basic_message_channel.h
@@ -575,11 +576,17 @@ FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/method_codec.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/method_result.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/plugin_registrar.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/standard_message_codec.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/standard_method_codec.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/json_message_codec.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/json_method_codec.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/method_call_unittests.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/plugin_registrar.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/plugin_registrar_unittests.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/standard_codec.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/standard_codec_serializer.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/standard_message_codec_unittests.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/standard_method_codec_unittests.cc
FILE: ../../../flutter/shell/platform/common/cpp/incoming_message_dispatcher.cc
FILE: ../../../flutter/shell/platform/common/cpp/incoming_message_dispatcher.h
FILE: ../../../flutter/shell/platform/common/cpp/public/flutter_export.h

View File

@@ -18,16 +18,21 @@ _wrapper_includes = [
"include/flutter/method_codec.h",
"include/flutter/method_result.h",
"include/flutter/plugin_registrar.h",
"include/flutter/standard_message_codec.h",
"include/flutter/standard_method_codec.h",
]
# TODO: Once the wrapper API is more stable, consolidate to as few files as is
# reasonable (without forcing different kinds of clients to take unnecessary
# code) to simplify use.
_wrapper_sources = [
"byte_stream_wrappers.h",
"engine_method_result.cc",
"json_message_codec.cc",
"json_method_codec.cc",
"json_message_codec.cc", # TODO combine into a single json_codec.cc.
"json_method_codec.cc", # TODO combine into a single json_codec.cc.
"plugin_registrar.cc",
"standard_codec_serializer.h",
"standard_codec.cc",
]
# Client library build for internal use by the shell implementation.
@@ -76,6 +81,10 @@ executable("client_wrapper_unittests") {
"encodable_value_unittests.cc",
"method_call_unittests.cc",
"plugin_registrar_unittests.cc",
"standard_message_codec_unittests.cc",
"standard_method_codec_unittests.cc",
"testing/encodable_value_utils.cc",
"testing/encodable_value_utils.h",
]
deps = [

View File

@@ -0,0 +1,105 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_BYTE_STREAM_WRAPPERS_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_BYTE_STREAM_WRAPPERS_H_
// Utility classes for interacting with a buffer of bytes as a stream, for use
// in message channel codecs.
#include <cstdint>
#include <cstring>
#include <iostream>
#include <vector>
namespace flutter {
// Wraps an array of bytes with utility methods for treating it as a readable
// stream.
class ByteBufferStreamReader {
public:
// Createa a reader reading from |bytes|, which must have a length of |size|.
// |bytes| must remain valid for the lifetime of this object.
explicit ByteBufferStreamReader(const uint8_t* bytes, size_t size)
: bytes_(bytes), size_(size) {}
// Reads and returns the next byte from the stream.
uint8_t ReadByte() {
if (location_ >= size_) {
std::cerr << "Invalid read in StandardCodecByteStreamReader" << std::endl;
return 0;
}
return bytes_[location_++];
}
// Reads the next |length| bytes from the stream into |buffer|. The caller
// is responsible for ensuring that |buffer| is large enough.
void ReadBytes(uint8_t* buffer, size_t length) {
if (location_ + length > size_) {
std::cerr << "Invalid read in StandardCodecByteStreamReader" << std::endl;
return;
}
std::memcpy(buffer, &bytes_[location_], length);
location_ += length;
}
// Advances the read cursor to the next multiple of |alignment| relative to
// the start of the wrapped byte buffer, unless it is already aligned.
void ReadAlignment(uint8_t alignment) {
uint8_t mod = location_ % alignment;
if (mod) {
location_ += alignment - mod;
}
}
private:
// The buffer to read from.
const uint8_t* bytes_;
// The total size of the buffer.
size_t size_;
// The current read location.
size_t location_ = 0;
};
// Wraps an array of bytes with utility methods for treating it as a writable
// stream.
class ByteBufferStreamWriter {
public:
// Createa a writter that writes into |buffer|.
// |buffer| must remain valid for the lifetime of this object.
explicit ByteBufferStreamWriter(std::vector<uint8_t>* buffer)
: bytes_(buffer) {
assert(buffer);
}
// Writes |byte| to the wrapped buffer.
void WriteByte(uint8_t byte) { bytes_->push_back(byte); }
// Writes the next |length| bytes from |bytes| into the wrapped buffer.
// The caller is responsible for ensuring that |buffer| is large enough.
void WriteBytes(const uint8_t* bytes, size_t length) {
assert(length > 0);
bytes_->insert(bytes_->end(), bytes, bytes + length);
}
// Writes 0s until the next multiple of |alignment| relative to
// the start of the wrapped byte buffer, unless the write positition is
// already aligned.
void WriteAlignment(uint8_t alignment) {
uint8_t mod = bytes_->size() % alignment;
if (mod) {
for (int i = 0; i < alignment - mod; ++i) {
WriteByte(0);
}
}
}
private:
// The buffer to write to.
std::vector<uint8_t>* bytes_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_BYTE_STREAM_WRAPPERS_H_

View File

@@ -34,8 +34,6 @@ class BasicMessageChannel {
public:
// Creates an instance that sends and receives method calls on the channel
// named |name|, encoded with |codec| and dispatched via |messenger|.
//
// TODO: Make codec optional once the standard codec is supported (Issue #67).
BasicMessageChannel(BinaryMessenger* messenger,
const std::string& name,
const MessageCodec<T>* codec)

View File

@@ -26,12 +26,20 @@ class MessageCodec {
// Returns the message encoded in |binary_message|, or nullptr if it cannot be
// decoded by this codec.
// TODO: Consider adding absl as a dependency and using absl::Span.
std::unique_ptr<T> DecodeMessage(const uint8_t* binary_message,
const size_t message_size) const {
return std::move(DecodeMessageInternal(binary_message, message_size));
}
// Returns the message encoded in |binary_message|, or nullptr if it cannot be
// decoded by this codec.
std::unique_ptr<T> DecodeMessage(
const std::vector<uint8_t>& binary_message) const {
size_t size = binary_message.size();
const uint8_t* data = size > 0 ? &binary_message[0] : nullptr;
return std::move(DecodeMessageInternal(data, size));
}
// Returns a binary encoding of the given |message|, or nullptr if the
// message cannot be serialized by this codec.
std::unique_ptr<std::vector<uint8_t>> EncodeMessage(const T& message) const {

View File

@@ -32,8 +32,6 @@ class MethodChannel {
public:
// Creates an instance that sends and receives method calls on the channel
// named |name|, encoded with |codec| and dispatched via |messenger|.
//
// TODO: Make codec optional once the standard codec is supported (Issue #67).
MethodChannel(BinaryMessenger* messenger,
const std::string& name,
const MethodCodec<T>* codec)

View File

@@ -28,13 +28,21 @@ class MethodCodec {
// Returns the MethodCall encoded in |message|, or nullptr if it cannot be
// decoded.
// TODO: Consider adding absl as a dependency and using absl::Span.
std::unique_ptr<MethodCall<T>> DecodeMethodCall(
const uint8_t* message,
const size_t message_size) const {
return std::move(DecodeMethodCallInternal(message, message_size));
}
// Returns the MethodCall encoded in |message|, or nullptr if it cannot be
// decoded.
std::unique_ptr<MethodCall<T>> DecodeMethodCall(
const std::vector<uint8_t>& message) const {
size_t size = message.size();
const uint8_t* data = size > 0 ? &message[0] : nullptr;
return std::move(DecodeMethodCallInternal(data, size));
}
// Returns a binary encoding of the given |method_call|, or nullptr if the
// method call cannot be serialized by this codec.
std::unique_ptr<std::vector<uint8_t>> EncodeMethodCall(

View File

@@ -0,0 +1,42 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_MESSAGE_CODEC_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_MESSAGE_CODEC_H_
#include "encodable_value.h"
#include "message_codec.h"
namespace flutter {
// A binary message encoding/decoding mechanism for communications to/from the
// Flutter engine via message channels.
class StandardMessageCodec : public MessageCodec<EncodableValue> {
public:
// Returns the shared instance of the codec.
static const StandardMessageCodec& GetInstance();
~StandardMessageCodec();
// Prevent copying.
StandardMessageCodec(StandardMessageCodec const&) = delete;
StandardMessageCodec& operator=(StandardMessageCodec const&) = delete;
protected:
// Instances should be obtained via GetInstance.
StandardMessageCodec();
// |flutter::MessageCodec|
std::unique_ptr<EncodableValue> DecodeMessageInternal(
const uint8_t* binary_message,
const size_t message_size) const override;
// |flutter::MessageCodec|
std::unique_ptr<std::vector<uint8_t>> EncodeMessageInternal(
const EncodableValue& message) const override;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_MESSAGE_CODEC_H_

View File

@@ -0,0 +1,52 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_METHOD_CODEC_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_METHOD_CODEC_H_
#include "encodable_value.h"
#include "method_call.h"
#include "method_codec.h"
namespace flutter {
// An implementation of MethodCodec that uses a binary serialization.
class StandardMethodCodec : public MethodCodec<EncodableValue> {
public:
// Returns the shared instance of the codec.
static const StandardMethodCodec& GetInstance();
~StandardMethodCodec() = default;
// Prevent copying.
StandardMethodCodec(StandardMethodCodec const&) = delete;
StandardMethodCodec& operator=(StandardMethodCodec const&) = delete;
protected:
// Instances should be obtained via GetInstance.
StandardMethodCodec() = default;
// |flutter::MethodCodec|
std::unique_ptr<MethodCall<EncodableValue>> DecodeMethodCallInternal(
const uint8_t* message,
const size_t message_size) const override;
// |flutter::MethodCodec|
std::unique_ptr<std::vector<uint8_t>> EncodeMethodCallInternal(
const MethodCall<EncodableValue>& method_call) const override;
// |flutter::MethodCodec|
std::unique_ptr<std::vector<uint8_t>> EncodeSuccessEnvelopeInternal(
const EncodableValue* result) const override;
// |flutter::MethodCodec|
std::unique_ptr<std::vector<uint8_t>> EncodeErrorEnvelopeInternal(
const std::string& error_code,
const std::string& error_message,
const EncodableValue* error_details) const override;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_STANDARD_METHOD_CODEC_H_

View File

@@ -0,0 +1,378 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains what would normally be standard_codec_serializer.cc,
// standard_message_codec.cc, and standard_method_codec.cc. They are grouped
// together to simplify use of the client wrapper, since the common case is
// that any client that needs one of these files needs all three.
#include "include/flutter/standard_message_codec.h"
#include "include/flutter/standard_method_codec.h"
#include "standard_codec_serializer.h"
#include <assert.h>
#include <cstring>
#include <iostream>
#include <map>
#include <string>
#include <vector>
namespace flutter {
// ===== standard_codec_serializer.h =====
namespace {
// The order/values here must match the constants in message_codecs.dart.
enum class EncodedType {
kNull = 0,
kTrue,
kFalse,
kInt32,
kInt64,
kLargeInt, // No longer used. If encountered, treat as kString.
kFloat64,
kString,
kUInt8List,
kInt32List,
kInt64List,
kFloat64List,
kList,
kMap,
};
// Returns the encoded type that should be written when serializing |value|.
EncodedType EncodedTypeForValue(const EncodableValue& value) {
switch (value.type()) {
case EncodableValue::Type::kNull:
return EncodedType::kNull;
case EncodableValue::Type::kBool:
return value.BoolValue() ? EncodedType::kTrue : EncodedType::kFalse;
case EncodableValue::Type::kInt:
return EncodedType::kInt32;
case EncodableValue::Type::kLong:
return EncodedType::kInt64;
case EncodableValue::Type::kDouble:
return EncodedType::kFloat64;
case EncodableValue::Type::kString:
return EncodedType::kString;
case EncodableValue::Type::kByteList:
return EncodedType::kUInt8List;
case EncodableValue::Type::kIntList:
return EncodedType::kInt32List;
case EncodableValue::Type::kLongList:
return EncodedType::kInt64List;
case EncodableValue::Type::kDoubleList:
return EncodedType::kFloat64List;
case EncodableValue::Type::kList:
return EncodedType::kList;
case EncodableValue::Type::kMap:
return EncodedType::kMap;
}
assert(false);
return EncodedType::kNull;
}
} // namespace
StandardCodecSerializer::StandardCodecSerializer() = default;
StandardCodecSerializer::~StandardCodecSerializer() = default;
EncodableValue StandardCodecSerializer::ReadValue(
ByteBufferStreamReader* stream) const {
EncodedType type = static_cast<EncodedType>(stream->ReadByte());
;
switch (type) {
case EncodedType::kNull:
return EncodableValue();
case EncodedType::kTrue:
return EncodableValue(true);
case EncodedType::kFalse:
return EncodableValue(false);
case EncodedType::kInt32: {
int32_t int_value = 0;
stream->ReadBytes(reinterpret_cast<uint8_t*>(&int_value), 4);
return EncodableValue(int_value);
}
case EncodedType::kInt64: {
int64_t long_value = 0;
stream->ReadBytes(reinterpret_cast<uint8_t*>(&long_value), 8);
return EncodableValue(long_value);
}
case EncodedType::kFloat64: {
double double_value = 0;
stream->ReadAlignment(8);
stream->ReadBytes(reinterpret_cast<uint8_t*>(&double_value), 8);
return EncodableValue(double_value);
}
case EncodedType::kLargeInt:
case EncodedType::kString: {
int32_t size = ReadSize(stream);
std::string string_value;
string_value.resize(size);
stream->ReadBytes(reinterpret_cast<uint8_t*>(&string_value[0]), size);
return EncodableValue(string_value);
}
case EncodedType::kUInt8List:
return ReadVector<uint8_t>(stream);
case EncodedType::kInt32List:
return ReadVector<int32_t>(stream);
case EncodedType::kInt64List:
return ReadVector<int64_t>(stream);
case EncodedType::kFloat64List:
return ReadVector<double>(stream);
case EncodedType::kList: {
int32_t length = ReadSize(stream);
EncodableList list_value;
list_value.reserve(length);
for (int32_t i = 0; i < length; ++i) {
list_value.push_back(ReadValue(stream));
}
return EncodableValue(list_value);
}
case EncodedType::kMap: {
int32_t length = ReadSize(stream);
EncodableMap map_value;
for (int32_t i = 0; i < length; ++i) {
EncodableValue key = ReadValue(stream);
EncodableValue value = ReadValue(stream);
map_value.emplace(std::move(key), std::move(value));
}
return EncodableValue(map_value);
}
}
std::cerr << "Unknown type in StandardCodecSerializer::ReadValue: "
<< static_cast<int>(type) << std::endl;
return EncodableValue();
}
void StandardCodecSerializer::WriteValue(const EncodableValue& value,
ByteBufferStreamWriter* stream) const {
stream->WriteByte(static_cast<uint8_t>(EncodedTypeForValue(value)));
switch (value.type()) {
case EncodableValue::Type::kNull:
case EncodableValue::Type::kBool:
// Null and bool are encoded directly in the type.
break;
case EncodableValue::Type::kInt: {
int32_t int_value = value.IntValue();
stream->WriteBytes(reinterpret_cast<const uint8_t*>(&int_value), 4);
break;
}
case EncodableValue::Type::kLong: {
int64_t long_value = value.LongValue();
stream->WriteBytes(reinterpret_cast<const uint8_t*>(&long_value), 8);
break;
}
case EncodableValue::Type::kDouble: {
stream->WriteAlignment(8);
double double_value = value.DoubleValue();
stream->WriteBytes(reinterpret_cast<const uint8_t*>(&double_value), 8);
break;
}
case EncodableValue::Type::kString: {
const auto& string_value = value.StringValue();
size_t size = string_value.size();
WriteSize(size, stream);
stream->WriteBytes(reinterpret_cast<const uint8_t*>(string_value.data()),
size);
break;
}
case EncodableValue::Type::kByteList:
WriteVector(value.ByteListValue(), stream);
break;
case EncodableValue::Type::kIntList:
WriteVector(value.IntListValue(), stream);
break;
case EncodableValue::Type::kLongList:
WriteVector(value.LongListValue(), stream);
break;
case EncodableValue::Type::kDoubleList:
WriteVector(value.DoubleListValue(), stream);
break;
case EncodableValue::Type::kList:
WriteSize(value.ListValue().size(), stream);
for (const auto& item : value.ListValue()) {
WriteValue(item, stream);
}
break;
case EncodableValue::Type::kMap:
WriteSize(value.MapValue().size(), stream);
for (const auto& pair : value.MapValue()) {
WriteValue(pair.first, stream);
WriteValue(pair.second, stream);
}
break;
}
}
uint32_t StandardCodecSerializer::ReadSize(
ByteBufferStreamReader* stream) const {
uint8_t byte = stream->ReadByte();
if (byte < 254) {
return byte;
} else if (byte == 254) {
uint16_t value;
stream->ReadBytes(reinterpret_cast<uint8_t*>(&value), 2);
return value;
} else {
uint32_t value;
stream->ReadBytes(reinterpret_cast<uint8_t*>(&value), 4);
return value;
}
}
void StandardCodecSerializer::WriteSize(uint32_t size,
ByteBufferStreamWriter* stream) const {
if (size < 254) {
stream->WriteByte(static_cast<uint8_t>(size));
} else if (size <= 0xffff) {
stream->WriteByte(254);
uint16_t value = static_cast<uint16_t>(size);
stream->WriteBytes(reinterpret_cast<uint8_t*>(&value), 2);
} else {
stream->WriteByte(255);
stream->WriteBytes(reinterpret_cast<uint8_t*>(&size), 4);
}
}
template <typename T>
EncodableValue StandardCodecSerializer::ReadVector(
ByteBufferStreamReader* stream) const {
int32_t count = ReadSize(stream);
std::vector<T> vector;
vector.resize(count);
size_t type_size = sizeof(T);
if (type_size > 1) {
stream->ReadAlignment(type_size);
}
stream->ReadBytes(reinterpret_cast<uint8_t*>(vector.data()),
count * type_size);
return EncodableValue(vector);
}
template <typename T>
void StandardCodecSerializer::WriteVector(
const std::vector<T> vector,
ByteBufferStreamWriter* stream) const {
size_t count = vector.size();
WriteSize(count, stream);
size_t type_size = sizeof(T);
if (type_size > 1) {
stream->WriteAlignment(type_size);
}
stream->WriteBytes(reinterpret_cast<const uint8_t*>(vector.data()),
count * type_size);
}
// ===== standard_message_codec.h =====
// static
const StandardMessageCodec& StandardMessageCodec::GetInstance() {
static StandardMessageCodec sInstance;
return sInstance;
}
StandardMessageCodec::StandardMessageCodec() = default;
StandardMessageCodec::~StandardMessageCodec() = default;
std::unique_ptr<EncodableValue> StandardMessageCodec::DecodeMessageInternal(
const uint8_t* binary_message,
const size_t message_size) const {
StandardCodecSerializer serializer;
ByteBufferStreamReader stream(binary_message, message_size);
return std::make_unique<EncodableValue>(serializer.ReadValue(&stream));
}
std::unique_ptr<std::vector<uint8_t>>
StandardMessageCodec::EncodeMessageInternal(
const EncodableValue& message) const {
StandardCodecSerializer serializer;
auto encoded = std::make_unique<std::vector<uint8_t>>();
ByteBufferStreamWriter stream(encoded.get());
serializer.WriteValue(message, &stream);
return encoded;
}
// ===== standard_method_codec.h =====
// static
const StandardMethodCodec& StandardMethodCodec::GetInstance() {
static StandardMethodCodec sInstance;
return sInstance;
}
std::unique_ptr<MethodCall<EncodableValue>>
StandardMethodCodec::DecodeMethodCallInternal(const uint8_t* message,
const size_t message_size) const {
StandardCodecSerializer serializer;
ByteBufferStreamReader stream(message, message_size);
EncodableValue method_name = serializer.ReadValue(&stream);
if (!method_name.IsString()) {
std::cerr << "Invalid method call; method name is not a string."
<< std::endl;
return nullptr;
}
auto arguments =
std::make_unique<EncodableValue>(serializer.ReadValue(&stream));
return std::make_unique<MethodCall<EncodableValue>>(method_name.StringValue(),
std::move(arguments));
}
std::unique_ptr<std::vector<uint8_t>>
StandardMethodCodec::EncodeMethodCallInternal(
const MethodCall<EncodableValue>& method_call) const {
StandardCodecSerializer serializer;
auto encoded = std::make_unique<std::vector<uint8_t>>();
ByteBufferStreamWriter stream(encoded.get());
serializer.WriteValue(EncodableValue(method_call.method_name()), &stream);
if (method_call.arguments()) {
serializer.WriteValue(*method_call.arguments(), &stream);
} else {
serializer.WriteValue(EncodableValue(), &stream);
}
return encoded;
}
std::unique_ptr<std::vector<uint8_t>>
StandardMethodCodec::EncodeSuccessEnvelopeInternal(
const EncodableValue* result) const {
StandardCodecSerializer serializer;
auto encoded = std::make_unique<std::vector<uint8_t>>();
ByteBufferStreamWriter stream(encoded.get());
stream.WriteByte(0);
if (result) {
serializer.WriteValue(*result, &stream);
} else {
serializer.WriteValue(EncodableValue(), &stream);
}
return encoded;
}
std::unique_ptr<std::vector<uint8_t>>
StandardMethodCodec::EncodeErrorEnvelopeInternal(
const std::string& error_code,
const std::string& error_message,
const EncodableValue* error_details) const {
StandardCodecSerializer serializer;
auto encoded = std::make_unique<std::vector<uint8_t>>();
ByteBufferStreamWriter stream(encoded.get());
stream.WriteByte(1);
serializer.WriteValue(EncodableValue(error_code), &stream);
if (error_message.empty()) {
serializer.WriteValue(EncodableValue(), &stream);
} else {
serializer.WriteValue(EncodableValue(error_message), &stream);
}
if (error_details) {
serializer.WriteValue(*error_details, &stream);
} else {
serializer.WriteValue(EncodableValue(), &stream);
}
return encoded;
}
} // namespace flutter

View File

@@ -0,0 +1,54 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_ENCODABLE_VALUE_SERIALIZER_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_ENCODABLE_VALUE_SERIALIZER_H_
#include "byte_stream_wrappers.h"
#include "include/flutter/encodable_value.h"
namespace flutter {
// Encapsulates the logic for encoding/decoding EncodableValues to/from the
// standard codec binary representation.
class StandardCodecSerializer {
public:
StandardCodecSerializer();
~StandardCodecSerializer();
// Prevent copying.
StandardCodecSerializer(StandardCodecSerializer const&) = delete;
StandardCodecSerializer& operator=(StandardCodecSerializer const&) = delete;
// Reads and returns the next value from |stream|.
EncodableValue ReadValue(ByteBufferStreamReader* stream) const;
// Writes the encoding of |value| to |stream|.
void WriteValue(const EncodableValue& value,
ByteBufferStreamWriter* stream) const;
protected:
// Reads the variable-length size from the current position in |stream|.
uint32_t ReadSize(ByteBufferStreamReader* stream) const;
// Writes the variable-length size encoding to |stream|.
void WriteSize(uint32_t size, ByteBufferStreamWriter* stream) const;
// Reads a fixed-type list whose values are of type T from the current
// position in |stream|, and returns it as the corresponding EncodableValue.
// |T| must correspond to one of the support list value types of
// EncodableValue.
template <typename T>
EncodableValue ReadVector(ByteBufferStreamReader* stream) const;
// Writes |vector| to |stream| as a fixed-type list. |T| must correspond to
// one of the support list value types of EncodableValue.
template <typename T>
void WriteVector(const std::vector<T> vector,
ByteBufferStreamWriter* stream) const;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_ENCODABLE_VALUE_SERIALIZER_H_

View File

@@ -0,0 +1,163 @@
// Copyright 2013 The Flutter 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 "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/standard_message_codec.h"
#include <map>
#include <vector>
#include "flutter/shell/platform/common/cpp/client_wrapper/testing/encodable_value_utils.h"
#include "gtest/gtest.h"
namespace flutter {
// Validates round-trip encoding and decoding of |value|, and checks that the
// encoded value matches |expected_encoding|.
static void CheckEncodeDecode(const EncodableValue& value,
const std::vector<uint8_t>& expected_encoding) {
const StandardMessageCodec& codec = StandardMessageCodec::GetInstance();
auto encoded = codec.EncodeMessage(value);
ASSERT_TRUE(encoded);
EXPECT_EQ(*encoded, expected_encoding);
auto decoded = codec.DecodeMessage(*encoded);
EXPECT_TRUE(testing::EncodableValuesAreEqual(value, *decoded));
}
// Validates round-trip encoding and decoding of |value|, and checks that the
// encoded value has the given prefix and length.
//
// This should be used only for Map, where asserting the order of the elements
// in a test is undesirable.
static void CheckEncodeDecodeWithEncodePrefix(
const EncodableValue& value,
const std::vector<uint8_t>& expected_encoding_prefix,
size_t expected_encoding_length) {
EXPECT_TRUE(value.IsMap());
const StandardMessageCodec& codec = StandardMessageCodec::GetInstance();
auto encoded = codec.EncodeMessage(value);
ASSERT_TRUE(encoded);
EXPECT_EQ(encoded->size(), expected_encoding_length);
ASSERT_GT(encoded->size(), expected_encoding_prefix.size());
EXPECT_TRUE(std::equal(
encoded->begin(), encoded->begin() + expected_encoding_prefix.size(),
expected_encoding_prefix.begin(), expected_encoding_prefix.end()));
auto decoded = codec.DecodeMessage(*encoded);
EXPECT_TRUE(testing::EncodableValuesAreEqual(value, *decoded));
}
TEST(StandardMessageCodec, CanEncodeAndDecodeNull) {
std::vector<uint8_t> bytes = {0x00};
CheckEncodeDecode(EncodableValue(), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeTrue) {
std::vector<uint8_t> bytes = {0x01};
CheckEncodeDecode(EncodableValue(true), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeFalse) {
std::vector<uint8_t> bytes = {0x02};
CheckEncodeDecode(EncodableValue(false), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeInt32) {
std::vector<uint8_t> bytes = {0x03, 0x78, 0x56, 0x34, 0x12};
CheckEncodeDecode(EncodableValue(0x12345678), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeInt64) {
std::vector<uint8_t> bytes = {0x04, 0xef, 0xcd, 0xab, 0x90,
0x78, 0x56, 0x34, 0x12};
CheckEncodeDecode(EncodableValue(0x1234567890abcdef), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeDouble) {
std::vector<uint8_t> bytes = {0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40};
CheckEncodeDecode(EncodableValue(3.14159265358979311599796346854), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeString) {
std::vector<uint8_t> bytes = {0x07, 0x0b, 0x68, 0x65, 0x6c, 0x6c, 0x6f,
0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64};
CheckEncodeDecode(EncodableValue(u8"hello world"), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeStringWithNonAsciiCodePoint) {
std::vector<uint8_t> bytes = {0x07, 0x05, 0x68, 0xe2, 0x98, 0xba, 0x77};
CheckEncodeDecode(EncodableValue(u8"h\u263Aw"), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeStringWithNonBMPCodePoint) {
std::vector<uint8_t> bytes = {0x07, 0x06, 0x68, 0xf0, 0x9f, 0x98, 0x82, 0x77};
CheckEncodeDecode(EncodableValue(u8"h\U0001F602w"), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeList) {
std::vector<uint8_t> bytes = {
0x0c, 0x05, 0x00, 0x07, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x85, 0xeb, 0x51, 0xb8, 0x1e,
0x09, 0x40, 0x03, 0x2f, 0x00, 0x00, 0x00, 0x0c, 0x02, 0x03, 0x2a,
0x00, 0x00, 0x00, 0x07, 0x06, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64,
};
EncodableValue value(EncodableList{
EncodableValue(),
EncodableValue("hello"),
EncodableValue(3.14),
EncodableValue(47),
EncodableValue(EncodableList{
EncodableValue(42),
EncodableValue("nested"),
}),
});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeMap) {
std::vector<uint8_t> bytes_prefix = {0x0d, 0x04};
EncodableValue value(EncodableMap{
{EncodableValue("a"), EncodableValue(3.14)},
{EncodableValue("b"), EncodableValue(47)},
{EncodableValue(), EncodableValue()},
{EncodableValue(3.14), EncodableValue(EncodableList{
EncodableValue("nested"),
})},
});
CheckEncodeDecodeWithEncodePrefix(value, bytes_prefix, 48);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeByteArray) {
std::vector<uint8_t> bytes = {0x08, 0x04, 0xba, 0x5e, 0xba, 0x11};
EncodableValue value(std::vector<uint8_t>{0xba, 0x5e, 0xba, 0x11});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeInt32Array) {
std::vector<uint8_t> bytes = {0x09, 0x03, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12,
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00};
EncodableValue value(std::vector<int32_t>{0x12345678, -1, 0});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeInt64Array) {
std::vector<uint8_t> bytes = {0x0a, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xef, 0xcd, 0xab, 0x90, 0x78, 0x56, 0x34, 0x12,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
EncodableValue value(std::vector<int64_t>{0x1234567890abcdef, -1});
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeFloat64Array) {
std::vector<uint8_t> bytes = {0x0b, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40,
0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x8f, 0x40};
EncodableValue value(
std::vector<double>{3.14159265358979311599796346854, 1000.0});
CheckEncodeDecode(value, bytes);
}
} // namespace flutter

View File

@@ -0,0 +1,105 @@
// Copyright 2013 The Flutter 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 "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/standard_method_codec.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/testing/encodable_value_utils.h"
#include "gtest/gtest.h"
namespace flutter {
namespace {
// Returns true if the given method calls have the same method name, and their
// arguments have equivalent values.
bool MethodCallsAreEqual(const MethodCall<EncodableValue>& a,
const MethodCall<EncodableValue>& b) {
if (a.method_name() != b.method_name()) {
return false;
}
// Treat nullptr and Null as equivalent.
if ((!a.arguments() || a.arguments()->IsNull()) &&
(!b.arguments() || b.arguments()->IsNull())) {
return true;
}
return testing::EncodableValuesAreEqual(*a.arguments(), *b.arguments());
}
} // namespace
TEST(StandardMethodCodec, HandlesMethodCallsWithNullArguments) {
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
MethodCall<EncodableValue> call("hello", nullptr);
auto encoded = codec.EncodeMethodCall(call);
ASSERT_NE(encoded.get(), nullptr);
std::unique_ptr<MethodCall<EncodableValue>> decoded =
codec.DecodeMethodCall(*encoded);
ASSERT_NE(decoded.get(), nullptr);
EXPECT_TRUE(MethodCallsAreEqual(call, *decoded));
}
TEST(StandardMethodCodec, HandlesMethodCallsWithArgument) {
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
MethodCall<EncodableValue> call(
"hello", std::make_unique<EncodableValue>(EncodableList{
EncodableValue(42),
EncodableValue("world"),
}));
auto encoded = codec.EncodeMethodCall(call);
ASSERT_NE(encoded.get(), nullptr);
std::unique_ptr<MethodCall<EncodableValue>> decoded =
codec.DecodeMethodCall(*encoded);
ASSERT_NE(decoded.get(), nullptr);
EXPECT_TRUE(MethodCallsAreEqual(call, *decoded));
}
TEST(StandardMethodCodec, HandlesSuccessEnvelopesWithNullResult) {
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
auto encoded = codec.EncodeSuccessEnvelope();
ASSERT_NE(encoded.get(), nullptr);
std::vector<uint8_t> bytes = {0x00, 0x00};
EXPECT_EQ(*encoded, bytes);
// TODO: Add round-trip check once decoding replies is implemented.
}
TEST(StandardMethodCodec, HandlesSuccessEnvelopesWithResult) {
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
EncodableValue result(42);
auto encoded = codec.EncodeSuccessEnvelope(&result);
ASSERT_NE(encoded.get(), nullptr);
std::vector<uint8_t> bytes = {0x00, 0x03, 0x2a, 0x00, 0x00, 0x00};
EXPECT_EQ(*encoded, bytes);
// TODO: Add round-trip check once decoding replies is implemented.
}
TEST(StandardMethodCodec, HandlesErrorEnvelopesWithNulls) {
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
auto encoded = codec.EncodeErrorEnvelope("errorCode");
ASSERT_NE(encoded.get(), nullptr);
std::vector<uint8_t> bytes = {0x01, 0x07, 0x09, 0x65, 0x72, 0x72, 0x6f,
0x72, 0x43, 0x6f, 0x64, 0x65, 0x00, 0x00};
EXPECT_EQ(*encoded, bytes);
// TODO: Add round-trip check once decoding replies is implemented.
}
TEST(StandardMethodCodec, HandlesErrorEnvelopesWithDetails) {
const StandardMethodCodec& codec = StandardMethodCodec::GetInstance();
EncodableValue details(EncodableList{
EncodableValue("a"),
EncodableValue(42),
});
auto encoded =
codec.EncodeErrorEnvelope("errorCode", "something failed", &details);
ASSERT_NE(encoded.get(), nullptr);
std::vector<uint8_t> bytes = {
0x01, 0x07, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f,
0x64, 0x65, 0x07, 0x10, 0x73, 0x6f, 0x6d, 0x65, 0x74, 0x68,
0x69, 0x6e, 0x67, 0x20, 0x66, 0x61, 0x69, 0x6c, 0x65, 0x64,
0x0c, 0x02, 0x07, 0x01, 0x61, 0x03, 0x2a, 0x00, 0x00, 0x00,
};
EXPECT_EQ(*encoded, bytes);
// TODO: Add round-trip check once decoding replies is implemented.
}
} // namespace flutter

View File

@@ -0,0 +1,89 @@
// Copyright 2013 The Flutter 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 "flutter/shell/platform/common/cpp/client_wrapper/testing/encodable_value_utils.h"
#include <cmath>
namespace flutter {
namespace testing {
bool EncodableValuesAreEqual(const EncodableValue& a, const EncodableValue& b) {
if (a.type() != b.type()) {
return false;
}
switch (a.type()) {
case EncodableValue::Type::kNull:
return true;
case EncodableValue::Type::kBool:
return a.BoolValue() == b.BoolValue();
case EncodableValue::Type::kInt:
return a.IntValue() == b.IntValue();
case EncodableValue::Type::kLong:
return a.LongValue() == b.LongValue();
case EncodableValue::Type::kDouble:
// This is a crude epsilon, but fine for the values in the the unit tests.
return std::abs(a.DoubleValue() - b.DoubleValue()) < 0.0001l;
case EncodableValue::Type::kString:
return a.StringValue() == b.StringValue();
case EncodableValue::Type::kByteList:
return a.ByteListValue() == b.ByteListValue();
case EncodableValue::Type::kIntList:
return a.IntListValue() == b.IntListValue();
case EncodableValue::Type::kLongList:
return a.LongListValue() == b.LongListValue();
case EncodableValue::Type::kDoubleList:
return a.DoubleListValue() == b.DoubleListValue();
case EncodableValue::Type::kList: {
const auto& a_list = a.ListValue();
const auto& b_list = b.ListValue();
if (a_list.size() != b_list.size()) {
return false;
}
for (size_t i = 0; i < a_list.size(); ++i) {
if (!EncodableValuesAreEqual(a_list[0], b_list[0])) {
return false;
}
}
return true;
}
case EncodableValue::Type::kMap: {
const auto& a_map = a.MapValue();
const auto& b_map = b.MapValue();
if (a_map.size() != b_map.size()) {
return false;
}
// Store references to all the keys in |b|.
std::vector<const EncodableValue*> unmatched_b_keys;
for (auto& pair : b_map) {
unmatched_b_keys.push_back(&pair.first);
}
// For each key,value in |a|, see if any of the not-yet-matched key,value
// pairs in |b| match by value; if so, remove that match and continue.
for (const auto& pair : a_map) {
bool found_match = false;
for (size_t i = 0; i < unmatched_b_keys.size(); ++i) {
const EncodableValue& b_key = *unmatched_b_keys[i];
if (EncodableValuesAreEqual(pair.first, b_key) &&
EncodableValuesAreEqual(pair.second, b_map.at(b_key))) {
found_match = true;
unmatched_b_keys.erase(unmatched_b_keys.begin() + i);
break;
}
}
if (!found_match) {
return false;
}
}
// If all entries had matches, consider the maps equal.
return true;
}
}
assert(false);
return false;
}
} // namespace testing
} // namespace flutter

View File

@@ -0,0 +1,22 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_TESTING_ENCODABLE_VALUE_UTILS_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_TESTING_ENCODABLE_VALUE_UTILS_H_
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/encodable_value.h"
namespace flutter {
namespace testing {
// Returns true if |a| and |b| have equivalent values, recursively comparing
// the contents of collections (unlike the < operator defined on EncodableValue,
// which doesn't consider different collections with the same contents to be
// the same).
bool EncodableValuesAreEqual(const EncodableValue& a, const EncodableValue& b);
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_TESTING_ENCODABLE_VALUE_UTILS_H_