作者:sunhuan | 来源:互联网 | 2023-05-18 11:41
我正在使用Java中的google protobuf.我看到可以将protobuf消息序列化为String,byte [],ByteString等:(来源:https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLite)
我不知道ByteString是什么.我从protobuf API文档中获得了以下定义(来源:https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/ByteString):"不可变的字节序列.子串与String一样,通过共享对不可变底层字节的引用来支持."
我不清楚ByteString如何与String或byte []不同.有人可以解释一下吗?谢谢.
1> Matt Ball..:
您可以将其ByteString
视为不可变的字节数组.这就是它.这是byte[]
你可以在protobuf中使用的.Protobuf不允许您使用Java数组,因为它们是可变的.
ByteString
因为String
不适合表示任意字节序列而存在.String
专门用于字符数据.
protobuf MessageLite接口提供toByteArray()和toByteString()方法.如果ByteString是一个不可变的byte [],那么ByteString和byte []表示的消息的字节表示是否相同?
有点.如果你给你打电话,toByteArray()
你会得到与你打电话相同的价值toByteString().toByteArray()
.比较两种方法的实现,在AbstractMessageLite
:
public ByteString toByteString() {
try {
final ByteString.CodedBuilder out =
ByteString.newCodedBuilder(getSerializedSize());
writeTo(out.getCodedOutput());
return out.build();
} catch (IOException e) {
throw new RuntimeException(
"Serializing to a ByteString threw an IOException (should " +
"never happen).", e);
}
}
public byte[] toByteArray() {
try {
final byte[] result = new byte[getSerializedSize()];
final CodedOutputStream output = CodedOutputStream.newInstance(result);
writeTo(output);
output.checkNoSpaceLeft();
return result;
} catch (IOException e) {
throw new RuntimeException(
"Serializing to a byte array threw an IOException " +
"(should never happen).", e);
}
}
2> Chris Thomps..:
A ByteString
使您能够对基础数据执行更多操作,而不必将数据复制到新结构中。例如,如果您想提供bytes
in 的子集byte[]
给另一种方法,则需要为其提供一个开始索引和一个结束索引。您也可以串联ByteStrings
而不必创建新的数据结构并手动复制数据。
但是,使用a ByteString
可以为该方法提供该数据的子集,而无需使方法知道有关底层存储的任何信息。就像普通String的子字符串一样。
字符串用于表示文本,不是存储二进制数据的好方法(因为并非所有二进制数据都具有文本等效项,除非您以某种方式对其进行编码:例如,十六进制或Base64)。