From aa006e2dab71a4aef6d6ab00b4cd7f8d0251bef3 Mon Sep 17 00:00:00 2001 From: asahi Date: Mon, 24 Feb 2025 20:46:29 +0800 Subject: [PATCH] =?UTF-8?q?=E9=98=85=E8=AF=BBprotobuf=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- protobuf/protobuf.md | 45 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 protobuf/protobuf.md diff --git a/protobuf/protobuf.md b/protobuf/protobuf.md new file mode 100644 index 0000000..01bf0a6 --- /dev/null +++ b/protobuf/protobuf.md @@ -0,0 +1,45 @@ +- [protobuf](#protobuf) + - [language guide(proto3)](#language-guideproto3) + - [定义message type](#定义message-type) + - [Assign Field Numbers](#assign-field-numbers) + - [重复使用filed number的后果](#重复使用filed-number的后果) + + +# protobuf +## language guide(proto3) +### 定义message type +如下为一个定义search request message format的示例, +```proto +synatx="proto3" + +message SearchRequest { + string query = 1; + int32 page_number = 2; + int32 results_per_page = 3; +} +``` +上述示例含义如下: +- `synatx = "proto3"`: + - 代表当前protobuf的language版本为`proto3` + - 如果没有指定`syntax`,那么protocol buffer compiler默认会假设在使用`proto2` +- `Search Request`消息定义了3个fields,每个field都代表`希望包含在message中的一部分数据` + +### Assign Field Numbers +可以为message中的每个field定义一个整数,范围为`[1,536,870,911]`,并有如下约束 +- message中所有field的给定数字必须唯一 +- field number `[19,000, 19,999]`是为`Protocol Buffer`实现保留的,如果使用这些数字,protocol buffer compiler将会报错 + +一旦消息类型被使用后,field number就不能被改变,field number代表message wire format中的field。 + +如果对field的field number进行了修改,代表删除旧的field并且新建一个相同类型的field。 + +filed number不应该被重用。 + +对于`频繁被设置`的fields,应该将其的field number设置为`[1,15]`。在wire format中,field number的值越小占用空间越小。 + +> 例如,`[1,15]`在编码时只占用1字节,而`[16, 2047]`则会占用2字节。 + +### 重复使用filed number的后果 +如果重复使用field number,将会造成解码wire-format message的二义性。 + +protobuf wire format \ No newline at end of file