MessagePack 是一個有效率的二進制序列化格式,傳遞的資料內容有點像是 JSON,但是因為是二進制的序列化格式,所以資料量更快且更小。

像是下面這張官網的圖,可以看到 {“compact”:true,“schema”:0} 這樣的 JSON 資料換由 MessagePack 來處理,資料量會從 27 bytes 降到 18 bytes,減少了 67%。

1.png

不過官網這張圖只是簡單的示意,實際上 compact 與 schema 這兩個字串得替換為 ascii,所以實際傳送的資料會變為 82 a7 63 6f 6d 70 61 63 74 c3 a6 73 63 68 65 6d 61 00。

2.png

若想要讀懂 MessagePack 格式的資料,必需先了解 MessagePack 的 format,其定義如下:

format namefirst byte (in binary)first byte (in hex)
positive fixint0xxxxxxx0x00 - 0x7f
fixmap1000xxxx0x80 - 0x8f
fixarray1001xxxx0x90 - 0x9f
fixstr101xxxxx0xa0 - 0xbf
nil110000000xc0
(never used)110000010xc1
false110000100xc2
true110000110xc3
bin 8110001000xc4
bin 16110001010xc5
bin 32110001100xc6
ext 8110001110xc7
ext 16110010000xc8
ext 32110010010xc9
float 32110010100xca
float 64110010110xcb
uint 8110011000xcc
uint 16110011010xcd
uint 32110011100xce
uint 64110011110xcf
int 8110100000xd0
int 16110100010xd1
int 32110100100xd2
int 64110100110xd3
fixext 1110101000xd4
fixext 2110101010xd5
fixext 4110101100xd6
fixext 8110101110xd7
fixext 16110110000xd8
str 8110110010xd9
str 16110110100xda
str 32110110110xdb
array 16110111000xdc
array 32110111010xdd
map 16110111100xde
map 32110111110xdf
negative fixint111xxxxx0xe0 - 0xff

這邊舉幾個簡單的例子來看。

Nil、False、True 這些簡易資料可經由查表直接得知為 0xc0、0xc2、0xc3。

如果是正整數的話,其格式為 0xxxxxxx,所以 0 的話就是 00000000,也就是 0x00。1 的話就是 00000001,也就是 0x01。

如果是字串的話,其格式為 101xxxxx,xxxxx 的部份要用來描述字串的長度,後面要接字串的內容,所以像是 Compact 字串,就會變成 10100007 01100011 01101111 01101101 01110000 01100001 01100011 01110100,也就是 a7 63 6f 6d 70 61 63 74。