Support empty strings and vectors in standard codec (flutter/engine#12974)

* Support empty strings and vectors in standard codec

Fixes #41993

Currently an empty string or vector will call through to WriteBytes
which asserts that the number of bytes it is being asked to write is
strictly positive. Instead we should not call WriteBytes if the length
is zero.

Similarly, when we read, we don't need to call out if the length is
zero.

* fix typo in test name

* remove unnecessary length check in ReadValue for List

* we also don't need this check before calling read as memcpy can handle size 0
This commit is contained in:
Andy Weiss
2019-10-15 08:35:50 -07:00
committed by Francisco Magdaleno
parent 1393c7fc54
commit 9b9dd7d20d
2 changed files with 17 additions and 2 deletions

View File

@@ -176,8 +176,10 @@ void StandardCodecSerializer::WriteValue(const EncodableValue& value,
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);
if (size > 0) {
stream->WriteBytes(
reinterpret_cast<const uint8_t*>(string_value.data()), size);
}
break;
}
case EncodableValue::Type::kByteList:
@@ -259,6 +261,9 @@ void StandardCodecSerializer::WriteVector(
ByteBufferStreamWriter* stream) const {
size_t count = vector.size();
WriteSize(count, stream);
if (count == 0) {
return;
}
uint8_t type_size = static_cast<uint8_t>(sizeof(T));
if (type_size > 1) {
stream->WriteAlignment(type_size);

View File

@@ -97,6 +97,11 @@ TEST(StandardMessageCodec, CanEncodeAndDecodeStringWithNonBMPCodePoint) {
CheckEncodeDecode(EncodableValue(u8"h\U0001F602w"), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeEmptyString) {
std::vector<uint8_t> bytes = {0x07, 0x00};
CheckEncodeDecode(EncodableValue(u8""), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeList) {
std::vector<uint8_t> bytes = {
0x0c, 0x05, 0x00, 0x07, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x06,
@@ -117,6 +122,11 @@ TEST(StandardMessageCodec, CanEncodeAndDecodeList) {
CheckEncodeDecode(value, bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeEmptyList) {
std::vector<uint8_t> bytes = {0x0c, 0x00};
CheckEncodeDecode(EncodableValue(EncodableList{}), bytes);
}
TEST(StandardMessageCodec, CanEncodeAndDecodeMap) {
std::vector<uint8_t> bytes_prefix = {0x0d, 0x04};
EncodableValue value(EncodableMap{