MessagePack类型实战:同样三个字节,为什么字符串长度和数组长度不能用一把尺

10-08 8阅读

MessagePack数组头写三,后面不一定只有三个字节;字符串头写三,也不一定只有三个字符。相同的长度数字,究竟数元素还是数字节,要先看首字节所属的格式家族。忽略这一步,嵌套结构里的读取位置很快就会错开。

本文独立实现整数、布尔、空值、字符串、二进制和数组这个子集。它不支持映射、浮点数或扩展类型,拒绝它们表示能力有限,不能把这些合法类型说成格式损坏。完整程序只依赖标准库,使用固定向量、类型敏感比较和随机树测试。

MessagePack类型实战:同样三个字节,为什么字符串长度和数组长度不能用一把尺
AI模型生成概念插图:字节托盘与嵌套元素托盘表达长度单位差异;非精确格式字段或实际测量结果。

类型系统与字节格式不是一一对应

同一个整数可以通过正fixint、负fixint以及不同宽度的有符号或无符号格式表达。编码器应优先选择更短形式,但解码器不能仅因整数一用了较宽表示就认定它不合法。本例接受CD 00 01,并恢复整数一。

另一方面,字符串和二进制即使载荷字节完全相同,也属于不同类型。文字中经UTF-8编码得到三个字节,二进制对象也可以恰好保存这三个字节;前者使用str家族,后者使用bin家族,接收端应分别返回文字与bytes。

一张数组里同时观察三种长度

主样本是一个三元素数组:文字中、同样的UTF-8字节串,以及包含零和一的二元素数组。外层93表示三个对象,而不是三个后续字节。A3表示三个字符串载荷字节;C4 03也表示三个载荷字节,但类型是二进制。

最后的92表示接下来递归读取两个完整对象。每个对象占多少线上字节,必须由各自的头部继续决定。不能用数组长度直接切出一段bytes,再把它当作数组的全部内容。元素计数与字节计数在递归入口处就已经分开。

字符数必须在编码后重新计算

fixstr的短长度最多容纳31字节。十个汉字中占30个UTF-8字节,可以使用短头;十一个则占33字节,需要切换成str8,而不是因为字符串的字符长度只有十一就继续使用fixstr。

程序先调用UTF-8编码,再计算实际字节数并选择头部。对于二进制则不作字符转换,直接使用bytes长度。示例另外检查255与256字节二进制之间的头部宽度变化,以及十五和十六元素数组之间的短头边界。

布尔值不能靠整数相等来蒙混过关

Python中False等于零,True等于一,bool还是int的子类。因此只做普通相等的往返断言,可能让一个把布尔写成整数的错误编码器通过测试。本文先按精确类型判断bool,再进入整数分支。

解码C2与C3返回布尔值,零字节返回整数零。测试用same递归比较类型和内容,而不是仅比较值相等。这样嵌套数组里出现的False与零也能被区分,避免类型信息在最外层测试看不见的地方悄悄丢失。

宽度与符号由格式标签决定

整数载荷使用高位在前的字节序,有符号格式按补码恢复。负fixint则把整个首字节当作八位有符号数解释,例如FF得到负一。它不是CBOR的负一减参数,也不是每字节七位载荷的Varint。

本子集接受从负二的六十三次方到二的六十四次方减一,编码时明确检查两端。Python可以保存更大整数,但线上整数家族不能自动随Python数值扩展;超出范围必须由上层另选表示,不能无声截断或转成浮点数。

无效UTF-8是接口策略的一部分

官方规格说明,字符串家族可能出现无效字节序列,不同实现的解码行为可能不同。本例采用严格UTF-8策略,A1 FF被拒绝;同一个FF若放进bin8,则作为合法原始字节返回。拒绝原因是本接口的文字合同,而不是宣称所有MessagePack实现都必须如此。

调用方若需要保留不能解码的字符串载荷,应设计显式的原始字符串包装类型或使用提供该能力的库,不能失败后直接把所有str标签改解释成bin。那会让原本不同的线上类型在业务层无从区分。

先限制声明值,再读取树

入口限制总输入65536字节,单字符串或二进制4096字节,单数组256元素,嵌套深度十六层与总节点2048。数组声明极大时直接拒绝,不先建一个那么长的结果列表。字节长度通过检查后,还要确认真实载荷确实存在。

这些是演示预算,不是规范给出的统一限制。编码器和解码器的预算也不构成通用、完全对称的生产schema;本实验只生成受限树。接入实际系统时,应把双方的总字节、总节点和每层容器限额写成共同合同。

完整对象与前缀读取需要不同入口

本文unpack要求输入恰好包含一个对象。读完第一个零后如果还有另一个字节,会报告尾部数据,而不默默丢掉。用于连续消息流时,应另设返回下一偏移的读取接口,或明确外层分帧,不能靠不断试探截断位置来找边界。

程序核对固定十六进制样本、千份固定种子生成的类型树、主样本的全部不完整前缀,以及保留标签、缺失数组元素、超预算长度和坏UTF-8。通过这些测试只验证本文子集,不代表完整MessagePack互操作性;映射键规则、扩展类型和浮点特殊值仍需要独立设计。

完整程序与本次实际输出

将以下程序保存为demo.py,执行python3 demo.py。本次在Linux、CPython 3.12.14运行,退出码为0,标准错误为空。程序只使用标准库与内存样本,不安装软件、不访问网络或业务文件。

from random import Random


def length_header(size, fixed, cutoff, tags):
    if fixed is not None and size < cutoff:
        return bytes([fixed | size])
    for tag, width in tags:
        if size < 1 << (8 * width):
            return bytes([tag]) + size.to_bytes(width, 'big')
    raise ValueError('length too large')


def pack(value, depth=0):
    if depth > 16:
        raise ValueError('nesting budget')
    if value is None:
        return b'\xc0'
    if type(value) is bool:
        return b'\xc3' if value else b'\xc2'
    if type(value) is int:
        if not -(1 << 63) <= value < 1 << 64:
            raise ValueError('integer range')
        if 0 <= value <= 127:
            return bytes([value])
        if -32 <= value < 0:
            return bytes([value & 255])
        widths = ((0xcc, 1), (0xcd, 2), (0xce, 4), (0xcf, 8)) if value >= 0 else ((0xd0, 1), (0xd1, 2), (0xd2, 4), (0xd3, 8))
        for tag, width in widths:
            if value >= 0 or -(1 << (width * 8 - 1)) <= value:
                if value < 1 << (width * 8):
                    return bytes([tag]) + value.to_bytes(width, 'big', signed=value < 0)
    if type(value) in (str, bytes):
        raw = value.encode('utf-8') if type(value) is str else value
        if len(raw) > 4096:
            raise ValueError('byte-string budget')
        if type(value) is str:
            return length_header(len(raw), 0xa0, 32, ((0xd9,1),(0xda,2),(0xdb,4))) + raw
        return length_header(len(raw), None, 0, ((0xc4,1),(0xc5,2),(0xc6,4))) + raw
    if type(value) is list and len(value) <= 256:
        payload = b''.join(pack(x, depth + 1) for x in value)
        if len(payload) > 65536:
            raise ValueError('encoded payload budget')
        return length_header(len(value), 0x90, 16, ((0xdc,2),(0xdd,4))) + payload
    raise ValueError('unsupported type or array budget')


def unpack(data):
    if type(data) is not bytes or len(data) > 65536:
        raise ValueError('input budget')
    pos = 0; nodes = 0

    def take(size):
        nonlocal pos
        if pos + size > len(data):
            raise ValueError('truncated item')
        result = data[pos:pos + size]; pos += size
        return result

    def read(depth=0):
        nonlocal nodes
        nodes += 1
        if depth > 16 or nodes > 2048:
            raise ValueError('tree budget')
        tag = take(1)[0]
        if tag <= 127:
            return tag
        if tag >= 0xe0:
            return tag - 256
        if tag == 0xc0:
            return None
        if tag in (0xc2, 0xc3):
            return tag == 0xc3
        if 0xcc <= tag <= 0xd3:
            width = (1,2,4,8)[(tag - 0xcc) % 4]
            return int.from_bytes(take(width), 'big', signed=tag >= 0xd0)
        if 0xa0 <= tag <= 0xbf:
            kind, size = 'str', tag & 31
        elif 0x90 <= tag <= 0x9f:
            kind, size = 'array', tag & 15
        elif tag in (0xc4,0xc5,0xc6,0xd9,0xda,0xdb,0xdc,0xdd):
            widths = {0xc4:1,0xc5:2,0xc6:4,0xd9:1,0xda:2,0xdb:4,0xdc:2,0xdd:4}
            size = int.from_bytes(take(widths[tag]), 'big')
            kind = 'bin' if tag <= 0xc6 else 'str' if tag <= 0xdb else 'array'
        else:
            raise ValueError('reserved tag or unsupported format family')
        if kind == 'array':
            if size > 256:
                raise ValueError('array budget')
            return [read(depth + 1) for _ in range(size)]
        if size > 4096:
            raise ValueError('byte-string budget')
        raw = take(size)
        return raw.decode('utf-8', errors='strict') if kind == 'str' else raw

    value = read()
    if pos != len(data):
        raise ValueError('trailing item or bytes')
    return value


def same(a, b):
    return type(a) is type(b) and (all(same(x,y) for x,y in zip(a,b)) and len(a)==len(b) if type(a) is list else a==b)


sample = ['中', '中'.encode(), [0, 1]]
wire = pack(sample)
assert wire.hex() == '93a3e4b8adc403e4b8ad920001' and same(unpack(wire), sample)
print('typed nested sample:', wire.hex(' '))
for value in ('中'*10, '中'*11, b'x'*255, b'x'*256, [0]*15, [0]*16):
    wire = pack(value); assert same(unpack(wire), value)
    print(type(value).__name__, len(value), 'header:', wire[:3].hex(' '))
assert pack([False, 0, True, None]).hex() == '94c200c3c0'
assert same(unpack(bytes.fromhex('94c200c3c0')), [False, 0, True, None])
assert unpack(bytes.fromhex('cd0001')) == 1  # Wider valid representation accepted.
rng = Random(7513)
atoms = [None, False, True, -33, -32, 127, 128, 65536, -(1<<63), (1<<64)-1, '中', b'\xff', '', b'']
def tree(depth):
    if depth and rng.randrange(3) == 0:
        return [tree(depth-1) for _ in range(rng.randrange(5))]
    return rng.choice(atoms)
for _ in range(1000):
    value = tree(4); assert same(unpack(pack(value)), value)
print('typed random-tree roundtrips:', 1000)
wire = pack(sample)
for cut in range(len(wire)):
    try:
        unpack(wire[:cut])
    except ValueError:
        pass
    else:
        raise AssertionError('partial document accepted')
for hx in ('c1', 'a1ff', 'c40200', 'ddffffffff', '9200', '0001', '80'):
    try:
        unpack(bytes.fromhex(hx))
    except ValueError:
        pass
    else:
        raise AssertionError('bad or unsupported document')
assert unpack(bytes.fromhex('c401ff')) == b'\xff'
print('bool identity, wide integer, UTF-8 policy, truncation and budget checks: PASS')

以下是上述完整程序本次实际标准输出,复制运行时不要把输出块带入代码。

typed nested sample: 93 a3 e4 b8 ad c4 03 e4 b8 ad 92 00 01
str 10 header: be e4 b8
str 11 header: d9 21 e4
bytes 255 header: c4 ff 78
bytes 256 header: c5 01 00
list 15 header: 9f 00 00
list 16 header: dc 00 10
typed random-tree roundtrips: 1000
bool identity, wide integer, UTF-8 policy, truncation and budget checks: PASS

参考资料

一手资料与本地运行核验日期:2026年10月8日。本文实现、样本及测试独立编写,有限实验不代表完整生产系统或性能保证。


文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。