Make EncodableValue a thin std::variant wrapper (flutter/engine#19983)

Instead of a hand-rolled discriminated union (originally used to avoid a C++17
dependency, which is no longer an issue), implement EncodableValue as a
std::variant. Rather than simply changing the internals, this makes EncodableValue
a minimal std::variant subclass with only a handful of added methodS, replacing
the old IsFoo/FooValue APIs with the standard std::holds_alternative/std::get,
so that plugin code will use a standard-based API rather than a Flutter-specific
API for wrapped values.

This is a breaking change for Windows and GLFW plugins. In the short
term USE_LEGACY_ENCODABLE_VALUE can be set in builds to use the old
version, to separate rolling from updating.

Fixes https://github.com/flutter/flutter/issues/61970
This commit is contained in:
stuartmorgan
2020-08-04 08:53:07 -07:00
committed by GitHub
parent 9f9e335a7c
commit d6fccfd566
11 changed files with 333 additions and 265 deletions

View File

@@ -48,8 +48,6 @@ executable("client_wrapper_unittests") {
"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

@@ -2,11 +2,10 @@
// 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/basic_message_channel.h"
#include <memory>
#include <string>
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/basic_message_channel.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/binary_messenger.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/standard_message_codec.h"
#include "gtest/gtest.h"
@@ -56,7 +55,7 @@ TEST(BasicMessageChannelTest, Registration) {
callback_called = true;
// Ensure that the wrapper recieved a correctly decoded message and a
// reply.
EXPECT_EQ(message.StringValue(), message_value);
EXPECT_EQ(std::get<std::string>(message), message_value);
EXPECT_NE(reply, nullptr);
});
EXPECT_EQ(messenger.last_message_handler_channel(), channel_name);

View File

@@ -3,96 +3,82 @@
// found in the LICENSE file.
// FLUTTER_NOLINT
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/encodable_value.h"
#include <limits>
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/encodable_value.h"
#include "gtest/gtest.h"
namespace flutter {
// Verifies that value.type() is |type|, and that of all the Is* methods, only
// the one that matches the type is true.
void VerifyType(EncodableValue& value,
EncodableValue::EncodableValue::Type type) {
EXPECT_EQ(value.type(), type);
EXPECT_EQ(value.IsNull(), type == EncodableValue::Type::kNull);
EXPECT_EQ(value.IsBool(), type == EncodableValue::Type::kBool);
EXPECT_EQ(value.IsInt(), type == EncodableValue::Type::kInt);
EXPECT_EQ(value.IsLong(), type == EncodableValue::Type::kLong);
EXPECT_EQ(value.IsDouble(), type == EncodableValue::Type::kDouble);
EXPECT_EQ(value.IsString(), type == EncodableValue::Type::kString);
EXPECT_EQ(value.IsByteList(), type == EncodableValue::Type::kByteList);
EXPECT_EQ(value.IsIntList(), type == EncodableValue::Type::kIntList);
EXPECT_EQ(value.IsLongList(), type == EncodableValue::Type::kLongList);
EXPECT_EQ(value.IsDoubleList(), type == EncodableValue::Type::kDoubleList);
EXPECT_EQ(value.IsList(), type == EncodableValue::Type::kList);
EXPECT_EQ(value.IsMap(), type == EncodableValue::Type::kMap);
}
TEST(EncodableValueTest, Null) {
EncodableValue value;
VerifyType(value, EncodableValue::Type::kNull);
value.IsNull();
}
TEST(EncodableValueTest, Bool) {
EncodableValue value(false);
VerifyType(value, EncodableValue::Type::kBool);
EXPECT_FALSE(value.BoolValue());
EXPECT_FALSE(std::get<bool>(value));
value = true;
EXPECT_TRUE(value.BoolValue());
EXPECT_TRUE(std::get<bool>(value));
}
TEST(EncodableValueTest, Int) {
EncodableValue value(42);
VerifyType(value, EncodableValue::Type::kInt);
EXPECT_EQ(value.IntValue(), 42);
EXPECT_EQ(std::get<int32_t>(value), 42);
value = std::numeric_limits<int32_t>::max();
EXPECT_EQ(value.IntValue(), std::numeric_limits<int32_t>::max());
EXPECT_EQ(std::get<int32_t>(value), std::numeric_limits<int32_t>::max());
}
TEST(EncodableValueTest, LongValueFromInt) {
// Test the int/long convenience wrapper.
TEST(EncodableValueTest, LongValue) {
EncodableValue value(std::numeric_limits<int32_t>::max());
EXPECT_EQ(value.LongValue(), std::numeric_limits<int32_t>::max());
}
TEST(EncodableValueTest, Long) {
EncodableValue value(INT64_C(42));
VerifyType(value, EncodableValue::Type::kLong);
EXPECT_EQ(value.LongValue(), 42);
value = std::numeric_limits<int64_t>::max();
EXPECT_EQ(value.LongValue(), std::numeric_limits<int64_t>::max());
}
TEST(EncodableValueTest, Long) {
EncodableValue value(INT64_C(42));
EXPECT_EQ(std::get<int64_t>(value), 42);
value = std::numeric_limits<int64_t>::max();
EXPECT_EQ(std::get<int64_t>(value), std::numeric_limits<int64_t>::max());
}
TEST(EncodableValueTest, Double) {
EncodableValue value(3.14);
VerifyType(value, EncodableValue::Type::kDouble);
EXPECT_EQ(value.DoubleValue(), 3.14);
EXPECT_EQ(std::get<double>(value), 3.14);
value = std::numeric_limits<double>::max();
EXPECT_EQ(value.DoubleValue(), std::numeric_limits<double>::max());
EXPECT_EQ(std::get<double>(value), std::numeric_limits<double>::max());
}
TEST(EncodableValueTest, String) {
std::string hello("Hello, world!");
EncodableValue value(hello);
VerifyType(value, EncodableValue::Type::kString);
EXPECT_EQ(value.StringValue(), hello);
EXPECT_EQ(std::get<std::string>(value), hello);
value = std::string("Goodbye");
EXPECT_EQ(std::get<std::string>(value), "Goodbye");
}
// Explicitly verify that the overrides to prevent char*->bool conversions work.
TEST(EncodableValueTest, CString) {
const char* hello = "Hello, world!";
EncodableValue value(hello);
EXPECT_EQ(std::get<std::string>(value), hello);
value = "Goodbye";
EXPECT_EQ(value.StringValue(), "Goodbye");
EXPECT_EQ(std::get<std::string>(value), "Goodbye");
}
TEST(EncodableValueTest, UInt8List) {
std::vector<uint8_t> data = {0, 2};
EncodableValue value(data);
VerifyType(value, EncodableValue::Type::kByteList);
std::vector<uint8_t>& list_value = value.ByteListValue();
auto& list_value = std::get<std::vector<uint8_t>>(value);
list_value.push_back(std::numeric_limits<uint8_t>::max());
EXPECT_EQ(list_value[0], 0);
EXPECT_EQ(list_value[1], 2);
@@ -105,9 +91,8 @@ TEST(EncodableValueTest, UInt8List) {
TEST(EncodableValueTest, Int32List) {
std::vector<int32_t> data = {-10, 2};
EncodableValue value(data);
VerifyType(value, EncodableValue::Type::kIntList);
std::vector<int32_t>& list_value = value.IntListValue();
auto& list_value = std::get<std::vector<int32_t>>(value);
list_value.push_back(std::numeric_limits<int32_t>::max());
EXPECT_EQ(list_value[0], -10);
EXPECT_EQ(list_value[1], 2);
@@ -120,9 +105,8 @@ TEST(EncodableValueTest, Int32List) {
TEST(EncodableValueTest, Int64List) {
std::vector<int64_t> data = {-10, 2};
EncodableValue value(data);
VerifyType(value, EncodableValue::Type::kLongList);
std::vector<int64_t>& list_value = value.LongListValue();
auto& list_value = std::get<std::vector<int64_t>>(value);
list_value.push_back(std::numeric_limits<int64_t>::max());
EXPECT_EQ(list_value[0], -10);
EXPECT_EQ(list_value[1], 2);
@@ -135,9 +119,8 @@ TEST(EncodableValueTest, Int64List) {
TEST(EncodableValueTest, DoubleList) {
std::vector<double> data = {-10.0, 2.0};
EncodableValue value(data);
VerifyType(value, EncodableValue::Type::kDoubleList);
std::vector<double>& list_value = value.DoubleListValue();
auto& list_value = std::get<std::vector<double>>(value);
list_value.push_back(std::numeric_limits<double>::max());
EXPECT_EQ(list_value[0], -10.0);
EXPECT_EQ(list_value[1], 2.0);
@@ -154,18 +137,17 @@ TEST(EncodableValueTest, List) {
EncodableValue("Three"),
};
EncodableValue value(encodables);
VerifyType(value, EncodableValue::Type::kList);
EncodableList& list_value = value.ListValue();
EXPECT_EQ(list_value[0].IntValue(), 1);
EXPECT_EQ(list_value[1].DoubleValue(), 2.0);
EXPECT_EQ(list_value[2].StringValue(), "Three");
auto& list_value = std::get<EncodableList>(value);
EXPECT_EQ(std::get<int32_t>(list_value[0]), 1);
EXPECT_EQ(std::get<double>(list_value[1]), 2.0);
EXPECT_EQ(std::get<std::string>(list_value[2]), "Three");
// Ensure that it's a modifiable copy of the original array.
list_value.push_back(EncodableValue(true));
ASSERT_EQ(list_value.size(), 4u);
EXPECT_EQ(encodables.size(), 3u);
EXPECT_EQ(value.ListValue()[3].BoolValue(), true);
EXPECT_EQ(std::get<bool>(std::get<EncodableList>(value)[3]), true);
}
TEST(EncodableValueTest, Map) {
@@ -175,43 +157,19 @@ TEST(EncodableValueTest, Map) {
{EncodableValue("two"), EncodableValue(7)},
};
EncodableValue value(encodables);
VerifyType(value, EncodableValue::Type::kMap);
EncodableMap& map_value = value.MapValue();
EXPECT_EQ(map_value[EncodableValue()].IsIntList(), true);
EXPECT_EQ(map_value[EncodableValue(1)].LongValue(), INT64_C(10000));
EXPECT_EQ(map_value[EncodableValue("two")].IntValue(), 7);
auto& map_value = std::get<EncodableMap>(value);
EXPECT_EQ(
std::holds_alternative<std::vector<int32_t>>(map_value[EncodableValue()]),
true);
EXPECT_EQ(std::get<int64_t>(map_value[EncodableValue(1)]), INT64_C(10000));
EXPECT_EQ(std::get<int32_t>(map_value[EncodableValue("two")]), 7);
// Ensure that it's a modifiable copy of the original map.
map_value[EncodableValue(true)] = EncodableValue(false);
ASSERT_EQ(map_value.size(), 4u);
EXPECT_EQ(encodables.size(), 3u);
EXPECT_EQ(map_value[EncodableValue(true)].BoolValue(), false);
}
TEST(EncodableValueTest, EmptyTypeConstructor) {
EXPECT_TRUE(EncodableValue(EncodableValue::Type::kNull).IsNull());
EXPECT_EQ(EncodableValue(EncodableValue::Type::kBool).BoolValue(), false);
EXPECT_EQ(EncodableValue(EncodableValue::Type::kInt).IntValue(), 0);
EXPECT_EQ(EncodableValue(EncodableValue::Type::kLong).LongValue(),
INT64_C(0));
EXPECT_EQ(EncodableValue(EncodableValue::Type::kDouble).DoubleValue(), 0.0);
EXPECT_EQ(EncodableValue(EncodableValue::Type::kString).StringValue().size(),
0u);
EXPECT_EQ(
EncodableValue(EncodableValue::Type::kByteList).ByteListValue().size(),
0u);
EXPECT_EQ(
EncodableValue(EncodableValue::Type::kIntList).IntListValue().size(), 0u);
EXPECT_EQ(
EncodableValue(EncodableValue::Type::kLongList).LongListValue().size(),
0u);
EXPECT_EQ(EncodableValue(EncodableValue::Type::kDoubleList)
.DoubleListValue()
.size(),
0u);
EXPECT_EQ(EncodableValue(EncodableValue::Type::kList).ListValue().size(), 0u);
EXPECT_EQ(EncodableValue(EncodableValue::Type::kMap).MapValue().size(), 0u);
EXPECT_EQ(std::get<bool>(map_value[EncodableValue(true)]), false);
}
// Tests that the < operator meets the requirements of using EncodableValue as
@@ -248,8 +206,8 @@ TEST(EncodableValueTest, Comparison) {
EncodableValue(std::vector<int64_t>{0, INT64_C(1)}),
EncodableValue(std::vector<int64_t>{0, INT64_C(100)}),
// DoubleList
EncodableValue(std::vector<int64_t>{0, INT64_C(1)}),
EncodableValue(std::vector<int64_t>{0, INT64_C(100)}),
EncodableValue(std::vector<double>{0, INT64_C(1)}),
EncodableValue(std::vector<double>{0, INT64_C(100)}),
// List
EncodableValue(EncodableList{EncodableValue(), EncodableValue(true)}),
EncodableValue(EncodableList{EncodableValue(), EncodableValue(1.0)}),
@@ -272,23 +230,19 @@ TEST(EncodableValueTest, Comparison) {
} else {
// All other comparisons should be consistent, but the direction doesn't
// matter.
EXPECT_NE(a < b, b < a);
EXPECT_NE(a < b, b < a) << "Indexes: " << i << ", " << j;
}
}
// Different non-collection objects with the same value should be equal;
// different collections should always be unequal regardless of contents.
bool is_collection = a.IsByteList() || a.IsIntList() || a.IsLongList() ||
a.IsDoubleList() || a.IsList() || a.IsMap();
// Copies should always be equal.
EncodableValue copy(a);
bool is_equal = !(a < copy || copy < a);
EXPECT_EQ(is_equal, !is_collection);
EXPECT_FALSE(a < copy || copy < a);
}
}
// Tests that structures are deep-copied.
TEST(EncodableValueTest, DeepCopy) {
EncodableList encodables = {
EncodableList original = {
EncodableValue(EncodableMap{
{EncodableValue(), EncodableValue(std::vector<int32_t>{1, 2, 3})},
{EncodableValue(1), EncodableValue(INT64_C(0000))},
@@ -302,30 +256,28 @@ TEST(EncodableValueTest, DeepCopy) {
}),
};
EncodableValue value(encodables);
ASSERT_TRUE(value.IsList());
EncodableValue copy(original);
ASSERT_TRUE(std::holds_alternative<EncodableList>(copy));
// Spot-check innermost collection values.
EXPECT_EQ(value.ListValue()[0].MapValue()[EncodableValue("two")].IntValue(),
7);
EXPECT_EQ(value.ListValue()[1]
.ListValue()[2]
.MapValue()[EncodableValue("a")]
.StringValue(),
"b");
auto& root_list = std::get<EncodableList>(copy);
auto& first_child = std::get<EncodableMap>(root_list[0]);
EXPECT_EQ(std::get<int32_t>(first_child[EncodableValue("two")]), 7);
auto& second_child = std::get<EncodableList>(root_list[1]);
auto& innermost_map = std::get<EncodableMap>(second_child[2]);
EXPECT_EQ(std::get<std::string>(innermost_map[EncodableValue("a")]), "b");
// Modify those values in the original structure.
encodables[0].MapValue()[EncodableValue("two")] = EncodableValue();
encodables[1].ListValue()[2].MapValue()[EncodableValue("a")] = 99;
first_child[EncodableValue("two")] = EncodableValue();
innermost_map[EncodableValue("a")] = 99;
// Re-check innermost collection values to ensure that they haven't changed.
EXPECT_EQ(value.ListValue()[0].MapValue()[EncodableValue("two")].IntValue(),
7);
EXPECT_EQ(value.ListValue()[1]
.ListValue()[2]
.MapValue()[EncodableValue("a")]
.StringValue(),
"b");
// Re-check innermost collection values of the original to ensure that they
// haven't changed.
first_child = std::get<EncodableMap>(original[0]);
EXPECT_EQ(std::get<int32_t>(first_child[EncodableValue("two")]), 7);
second_child = std::get<EncodableList>(original[1]);
innermost_map = std::get<EncodableMap>(second_child[2]);
EXPECT_EQ(std::get<std::string>(innermost_map[EncodableValue("a")]), "b");
}
} // namespace flutter

View File

@@ -6,16 +6,130 @@
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENCODABLE_VALUE_H_
#include <assert.h>
#include <cstdint>
#include <map>
#include <string>
#include <utility>
#include <variant>
#include <vector>
namespace flutter {
static_assert(sizeof(double) == 8, "EncodableValue requires a 64-bit double");
// Defining USE_LEGACY_ENCODABLE_VALUE will use the original EncodableValue
// implementation. This is a temporary measure to minimize the impact of the
// breaking change; it will be removed in the future. If you set this, you
// should update your code as soon as possible to use the new std::variant
// version, or it will break when the legacy version is removed.
#ifndef USE_LEGACY_ENCODABLE_VALUE
class EncodableValue;
// Convenience type aliases.
using EncodableList = std::vector<EncodableValue>;
using EncodableMap = std::map<EncodableValue, EncodableValue>;
namespace internal {
// The base class for EncodableValue. Do not use this directly; it exists only
// for EncodableValue to inherit from.
//
// Do not change the order or indexes of the items here; see the comment on
// EncodableValue
using EncodableValueVariant = std::variant<std::monostate,
bool,
int32_t,
int64_t,
double,
std::string,
std::vector<uint8_t>,
std::vector<int32_t>,
std::vector<int64_t>,
std::vector<double>,
EncodableList,
EncodableMap>;
} // namespace internal
// An object that can contain any value or collection type supported by
// Flutter's standard method codec.
//
// For details, see:
// https://api.flutter.dev/flutter/services/StandardMessageCodec-class.html
//
// As an example, the following Dart structure:
// {
// 'flag': true,
// 'name': 'Thing',
// 'values': [1, 2.0, 4],
// }
// would correspond to:
// EncodableValue(EncodableMap{
// {EncodableValue("flag"), EncodableValue(true)},
// {EncodableValue("name"), EncodableValue("Thing")},
// {EncodableValue("values"), EncodableValue(EncodableList{
// EncodableValue(1),
// EncodableValue(2.0),
// EncodableValue(4),
// })},
// })
//
// The primary API surface for this object is std::variant. For instance,
// getting a string value from an EncodableValue, with type checking:
// if (std::get<std::string>(value)) {
// std::string some_string = std::get<std::string>(value);
// }
//
// The order/indexes of the variant types is part of the API surface, and is
// guaranteed not to change.
class EncodableValue : public internal::EncodableValueVariant {
public:
// Rely on std::variant for most of the constructors/operators.
using super = internal::EncodableValueVariant;
using super::super;
using super::operator=;
explicit EncodableValue() = default;
// Avoid the C++17 pitfall of conversion from char* to bool. Should not be
// needed for C++20.
explicit EncodableValue(const char* string) : super(std::string(string)) {}
EncodableValue& operator=(const char* other) {
*this = std::string(other);
return *this;
}
// Override the conversion constructors from std::variant to make them
// explicit, to avoid implicit conversion.
//
// While implicit conversion can be convenient in some cases, it can have very
// surprising effects. E.g., calling a function that takes an EncodableValue
// but accidentally passing an EncodableValue* would, instead of failing to
// compile, go through a pointer->bool->EncodableValue(bool) chain and
// silently call the function with a temp-constructed EncodableValue(true).
template <class T>
constexpr explicit EncodableValue(T&& t) noexcept : super(t) {}
// Returns true if the value is null. Convenience wrapper since unlike the
// other types, std::monostate uses aren't self-documenting.
bool IsNull() const { return std::holds_alternative<std::monostate>(*this); }
// Convience method to simplify handling objects received from Flutter where
// the values may be larger than 32-bit, since they have the same type on the
// Dart side, but will be either 32-bit or 64-bit here depending on the value.
//
// Calling this method if the value doesn't contain either an int32_t or an
// int64_t will throw an exception.
int64_t LongValue() {
if (std::holds_alternative<int32_t>(*this)) {
return std::get<int32_t>(*this);
}
return std::get<int64_t>(*this);
}
};
#else
class EncodableValue;
// Convenience type aliases for list and map EncodableValue types.
using EncodableList = std::vector<EncodableValue>;
@@ -564,6 +678,8 @@ class EncodableValue {
Type type_ = Type::kNull;
};
#endif
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENCODABLE_VALUE_H_

View File

@@ -2,12 +2,11 @@
// 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/method_channel.h"
#include <memory>
#include <string>
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/binary_messenger.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/method_channel.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/method_result_functions.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/standard_method_codec.h"
#include "gtest/gtest.h"
@@ -119,7 +118,7 @@ TEST(MethodChannelTest, InvokeWithResponse) {
auto result_handler = std::make_unique<MethodResultFunctions<EncodableValue>>(
[&received_reply, reply](const EncodableValue* success_value) {
received_reply = true;
EXPECT_EQ(success_value->StringValue(), reply);
EXPECT_EQ(std::get<std::string>(*success_value), reply);
},
nullptr, nullptr);

View File

@@ -8,17 +8,18 @@
// 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>
#include "include/flutter/standard_message_codec.h"
#include "include/flutter/standard_method_codec.h"
#include "standard_codec_serializer.h"
namespace flutter {
// ===== standard_codec_serializer.h =====
@@ -45,6 +46,7 @@ enum class EncodedType {
// Returns the encoded type that should be written when serializing |value|.
EncodedType EncodedTypeForValue(const EncodableValue& value) {
#ifdef USE_LEGACY_ENCODABLE_VALUE
switch (value.type()) {
case EncodableValue::Type::kNull:
return EncodedType::kNull;
@@ -71,6 +73,34 @@ EncodedType EncodedTypeForValue(const EncodableValue& value) {
case EncodableValue::Type::kMap:
return EncodedType::kMap;
}
#else
switch (value.index()) {
case 0:
return EncodedType::kNull;
case 1:
return std::get<bool>(value) ? EncodedType::kTrue : EncodedType::kFalse;
case 2:
return EncodedType::kInt32;
case 3:
return EncodedType::kInt64;
case 4:
return EncodedType::kFloat64;
case 5:
return EncodedType::kString;
case 6:
return EncodedType::kUInt8List;
case 7:
return EncodedType::kInt32List;
case 8:
return EncodedType::kInt64List;
case 9:
return EncodedType::kFloat64List;
case 10:
return EncodedType::kList;
case 11:
return EncodedType::kMap;
}
#endif
assert(false);
return EncodedType::kNull;
}
@@ -151,6 +181,7 @@ EncodableValue StandardCodecSerializer::ReadValue(
void StandardCodecSerializer::WriteValue(const EncodableValue& value,
ByteBufferStreamWriter* stream) const {
stream->WriteByte(static_cast<uint8_t>(EncodedTypeForValue(value)));
#ifdef USE_LEGACY_ENCODABLE_VALUE
switch (value.type()) {
case EncodableValue::Type::kNull:
case EncodableValue::Type::kBool:
@@ -208,6 +239,70 @@ void StandardCodecSerializer::WriteValue(const EncodableValue& value,
}
break;
}
#else
// TODO: Consider replacing this this with a std::visitor.
switch (value.index()) {
case 0:
case 1:
// Null and bool are encoded directly in the type.
break;
case 2: {
int32_t int_value = std::get<int32_t>(value);
stream->WriteBytes(reinterpret_cast<const uint8_t*>(&int_value), 4);
break;
}
case 3: {
int64_t long_value = std::get<int64_t>(value);
stream->WriteBytes(reinterpret_cast<const uint8_t*>(&long_value), 8);
break;
}
case 4: {
stream->WriteAlignment(8);
double double_value = std::get<double>(value);
stream->WriteBytes(reinterpret_cast<const uint8_t*>(&double_value), 8);
break;
}
case 5: {
const auto& string_value = std::get<std::string>(value);
size_t size = string_value.size();
WriteSize(size, stream);
if (size > 0) {
stream->WriteBytes(
reinterpret_cast<const uint8_t*>(string_value.data()), size);
}
break;
}
case 6:
WriteVector(std::get<std::vector<uint8_t>>(value), stream);
break;
case 7:
WriteVector(std::get<std::vector<int32_t>>(value), stream);
break;
case 8:
WriteVector(std::get<std::vector<int64_t>>(value), stream);
break;
case 9:
WriteVector(std::get<std::vector<double>>(value), stream);
break;
case 10: {
const auto& list = std::get<EncodableList>(value);
WriteSize(list.size(), stream);
for (const auto& item : list) {
WriteValue(item, stream);
}
break;
}
case 11: {
const auto& map = std::get<EncodableMap>(value);
WriteSize(map.size(), stream);
for (const auto& pair : map) {
WriteValue(pair.first, stream);
WriteValue(pair.second, stream);
}
break;
}
}
#endif
}
size_t StandardCodecSerializer::ReadSize(ByteBufferStreamReader* stream) const {
@@ -315,6 +410,7 @@ StandardMethodCodec::DecodeMethodCallInternal(const uint8_t* message,
size_t message_size) const {
StandardCodecSerializer serializer;
ByteBufferStreamReader stream(message, message_size);
#ifdef USE_LEGACY_ENCODABLE_VALUE
EncodableValue method_name = serializer.ReadValue(&stream);
if (!method_name.IsString()) {
std::cerr << "Invalid method call; method name is not a string."
@@ -325,6 +421,19 @@ StandardMethodCodec::DecodeMethodCallInternal(const uint8_t* message,
std::make_unique<EncodableValue>(serializer.ReadValue(&stream));
return std::make_unique<MethodCall<EncodableValue>>(method_name.StringValue(),
std::move(arguments));
#else
EncodableValue method_name_value = serializer.ReadValue(&stream);
const auto* method_name = std::get_if<std::string>(&method_name_value);
if (!method_name) {
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,
std::move(arguments));
#endif
}
std::unique_ptr<std::vector<uint8_t>>
@@ -397,9 +506,15 @@ bool StandardMethodCodec::DecodeAndProcessResponseEnvelopeInternal(
EncodableValue code = serializer.ReadValue(&stream);
EncodableValue message = serializer.ReadValue(&stream);
EncodableValue details = serializer.ReadValue(&stream);
#ifdef USE_LEGACY_ENCODABLE_VALUE
result->Error(code.StringValue(),
message.IsNull() ? "" : message.StringValue(),
details.IsNull() ? nullptr : &details);
#else
result->Error(std::get<std::string>(code),
message.IsNull() ? "" : std::get<std::string>(message),
details.IsNull() ? nullptr : &details);
#endif
return true;
}
default:

View File

@@ -2,12 +2,10 @@
// 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 "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/standard_message_codec.h"
#include "gtest/gtest.h"
namespace flutter {
@@ -22,7 +20,7 @@ static void CheckEncodeDecode(const EncodableValue& value,
EXPECT_EQ(*encoded, expected_encoding);
auto decoded = codec.DecodeMessage(*encoded);
EXPECT_TRUE(testing::EncodableValuesAreEqual(value, *decoded));
EXPECT_EQ(value, *decoded);
}
// Validates round-trip encoding and decoding of |value|, and checks that the
@@ -34,7 +32,7 @@ static void CheckEncodeDecodeWithEncodePrefix(
const EncodableValue& value,
const std::vector<uint8_t>& expected_encoding_prefix,
size_t expected_encoding_length) {
EXPECT_TRUE(value.IsMap());
EXPECT_TRUE(std::holds_alternative<EncodableMap>(value));
const StandardMessageCodec& codec = StandardMessageCodec::GetInstance();
auto encoded = codec.EncodeMessage(value);
ASSERT_TRUE(encoded);
@@ -46,7 +44,7 @@ static void CheckEncodeDecodeWithEncodePrefix(
expected_encoding_prefix.begin(), expected_encoding_prefix.end()));
auto decoded = codec.DecodeMessage(*encoded);
EXPECT_TRUE(testing::EncodableValuesAreEqual(value, *decoded));
EXPECT_EQ(value, *decoded);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeNull) {

View File

@@ -2,10 +2,8 @@
// 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/include/flutter/method_result_functions.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/testing/encodable_value_utils.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/standard_method_codec.h"
#include "gtest/gtest.h"
namespace flutter {
@@ -24,7 +22,11 @@ bool MethodCallsAreEqual(const MethodCall<EncodableValue>& a,
(!b.arguments() || b.arguments()->IsNull())) {
return true;
}
return testing::EncodableValuesAreEqual(*a.arguments(), *b.arguments());
// If only one is nullptr, fail early rather than throw below.
if (!a.arguments() || !b.arguments()) {
return false;
}
return *a.arguments() == *b.arguments();
}
} // namespace
@@ -86,7 +88,7 @@ TEST(StandardMethodCodec, HandlesSuccessEnvelopesWithResult) {
MethodResultFunctions<EncodableValue> result_handler(
[&decoded_successfully](const EncodableValue* result) {
decoded_successfully = true;
EXPECT_EQ(result->IntValue(), 42);
EXPECT_EQ(std::get<int32_t>(*result), 42);
},
nullptr, nullptr);
codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(),
@@ -145,9 +147,10 @@ TEST(StandardMethodCodec, HandlesErrorEnvelopesWithDetails) {
decoded_successfully = true;
EXPECT_EQ(code, "errorCode");
EXPECT_EQ(message, "something failed");
EXPECT_TRUE(details->IsList());
EXPECT_EQ(details->ListValue()[0].StringValue(), "a");
EXPECT_EQ(details->ListValue()[1].IntValue(), 42);
const auto* details_list = std::get_if<EncodableList>(details);
ASSERT_NE(details_list, nullptr);
EXPECT_EQ(std::get<std::string>((*details_list)[0]), "a");
EXPECT_EQ(std::get<int32_t>((*details_list)[1]), 42);
},
nullptr);
codec.DecodeAndProcessResponseEnvelope(encoded->data(), encoded->size(),

View File

@@ -1,89 +0,0 @@
// 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 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

@@ -1,22 +0,0 @@
// 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_

View File

@@ -16,33 +16,32 @@ static constexpr char kKindKey[] = "kind";
namespace flutter {
CursorHandler::CursorHandler(flutter::BinaryMessenger* messenger,
CursorHandler::CursorHandler(BinaryMessenger* messenger,
WindowBindingHandler* delegate)
: channel_(std::make_unique<flutter::MethodChannel<EncodableValue>>(
: channel_(std::make_unique<MethodChannel<EncodableValue>>(
messenger,
kChannelName,
&flutter::StandardMethodCodec::GetInstance())),
&StandardMethodCodec::GetInstance())),
delegate_(delegate) {
channel_->SetMethodCallHandler(
[this](const flutter::MethodCall<EncodableValue>& call,
std::unique_ptr<flutter::MethodResult<EncodableValue>> result) {
[this](const MethodCall<EncodableValue>& call,
std::unique_ptr<MethodResult<EncodableValue>> result) {
HandleMethodCall(call, std::move(result));
});
}
void CursorHandler::HandleMethodCall(
const flutter::MethodCall<EncodableValue>& method_call,
std::unique_ptr<flutter::MethodResult<EncodableValue>> result) {
const MethodCall<EncodableValue>& method_call,
std::unique_ptr<MethodResult<EncodableValue>> result) {
const std::string& method = method_call.method_name();
if (method.compare(kActivateSystemCursorMethod) == 0) {
const flutter::EncodableMap& arguments =
method_call.arguments()->MapValue();
auto kind_iter = arguments.find(EncodableValue(kKindKey));
const auto& arguments = std::get<EncodableMap>(*method_call.arguments());
auto kind_iter = arguments.find(EncodableValue(std::string(kKindKey)));
if (kind_iter == arguments.end()) {
result->Error("Argument error",
"Missing argument while trying to activate system cursor");
}
const std::string& kind = kind_iter->second.StringValue();
const auto& kind = std::get<std::string>(kind_iter->second);
delegate_->UpdateFlutterCursor(kind);
result->Success();
} else {