All Articles

Protobuf中的Options功能

1. 前言

之前的工作中使用Protobuf基本上都只用到了最简单的部分,最近做的基于gRPC的框架SASDN虽然重度使用了Protobuf,但其实还只是基础功能的使用。

直到最近的一个Issue之前,我都没关注过Protobuf的Options功能。后面简单了解了下这个功能,这里做下笔记。本文仅粗浅介绍该功能,并不会有很深入的探讨。

2. 释义

官方文档上,关于Options的介绍如下:

Individual declarations in a .proto file can be annotated with a number of options. Options do not change the overall meaning of a declaration, but may affect the way it is handled in a particular context. The complete list of available options is defined in google/protobuf/descriptor.proto.

简单来说,这个Options功能是为了让一份proto文件能使用在多种语言背景中而提供的一些简单选项。举两个例子就很容易理解了:

2.1 deprecated

官方解释说明:

If set to true, indicates that the field is deprecated and should not be used by new code. In most languages this has no actual effect. In Java, this becomes a @Deprecated annotation. In the future, other language-specific code generators may generate deprecation annotations on the field’s accessors, which will in turn cause a warning to be emitted when compiling code which attempts to use the field.

范例代码:

int32 old_field = 6 [deprecated=true];

在field定义后面添加这样一点代码就能在Java里生成一段@Deprecated annotation。根据语言的不同,从这个option而产生的编译反应可能各不相同,这就是option的作用。

2.2 jstype

官方解释说明:[email protected]#L494

The jstype option determines the JavaScript type used for values of the field. The option is permitted only for 64 bit integral and fixed types(int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING is represented as JavaScript string, which avoids loss of precision that can happen when a large value is converted to a floating point JavaScript. Specifying JS_NUMBER for the jstype causes the generated JavaScript code to use the JavaScript “number” type. The behavior of the default option JS_NORMAL is implementation dependent.

范例代码:

int64 isbn = 1 [jstype=JS_STRING];

这个option帮助proto确定在生成代码的时候当前字段应该使用JS代码中的什么类型。在int64这种超长数字类型转换成JS代码的时候很有用,如果按数字类型定义直接把int64转换成原生JS代码中的number就会发生精度丢失。很多时候我们可以选择把int64转成字符串来保留内容。

3. 功能全集

Options的全集在文档里是没有完整描述的,需要查看的时候请查看对应的代码:descriptor.proto

The complete list of available options is defined in google/protobuf/descriptor.proto.

4. 自定义Option

当官方的Options不能满足需求的时候,还可以制作自定义的Option,官方文档描述如下:

Protocol Buffers also allows you to define and use your own options. This is an advanced feature which most people don’t need. If you do think you need to create your own options, see the Proto2 Language Guide for details. Note that creating custom options uses extensions, which are permitted only for custom options in proto3.

EOF

Published 2018/2/5

Some tech & personal blog posts