typed_bytes_check
stdlib/typed/typed_bytes_check.nbv
typed_bytes_check(bytes, static types, static lens)
Constrain bytes to be a typed byte string in postcard's encoding with the static schema types (one type tag per field, see typed_width) and lens (each field's parameter): the fields concatenated as postcard serializes a tuple or struct. The schema fixes the total length and every byte is constrained to 0..255, bool fields to 0 or 1, option markers and bytes length prefixes to their values from the schema and integer varints to the shortest encoding of a value of their type, as the postcard serializer writes them.
Returns the bits of bytes, least significant bit of each byte first (see bytes_to_bits), ready for hashing.
- Calls
bits/bytes_to_bits,calloc,slice,bits/to_bits_exact,typed/typed_varint_static,typed/typed_width- Precompiles
assert_eq!,clone!,constrain_eq!,constrain_mul!,if_eq!,if_lt!,len!,loop!,loop_flat_map!- Used by
typed/typed_bytes_lattice
Source
# Constrain `bytes` to be a typed byte string in postcard's encoding with the
# static schema `types` (one type tag per field, see typed_width) and `lens`
# (each field's parameter): the fields concatenated as postcard serializes a
# tuple or struct. The schema fixes the total length and every byte is
# constrained to 0..255, bool fields to 0 or 1, option markers and bytes
# length prefixes to their values from the schema and integer varints to the
# shortest encoding of a value of their type, as the postcard serializer
# writes them.
#
# Returns the bits of `bytes`, least significant bit of each byte first (see
# bytes_to_bits), ready for hashing.
(bytes, static types, static lens)
# the bits of the last varint byte above the type's range, at the maximum
# varint length
static LAST_BITS = [2 4 1 2]
static VARINT_MAX = [3 5 10 19]
static fields = len! types
assert_eq! fields, len! lens
static mut total = 0
loop! fields, i {
total = total + typed_width(types[i], lens[i])
}
assert_eq! total, len! bytes
let bits = bytes_to_bits(clone! bytes)
static mut offset = 0
loop! fields, i {
static t = types[i]
static n = lens[i]
if_eq! t, 0 {
constrain_mul! bytes[offset], bytes[offset], bytes[offset]
}
if_lt! 1, t {
if_lt! t, 6 {
# continuation bits: set on all but the last byte
static mut cont[n]
loop! n - 1, j {
cont[j] = 1
}
let cont_bits = loop_flat_map! n, j {
slice((clone! bits), 8 * (offset + j) + 7, 1)
}
constrain_eq! cont_bits, cont
static last = offset + n - 1
# shortest encoding: a last byte of 1..127 when there are several
if_lt! 1, n {
let nonzero = to_bits_exact(bytes[last] - 1, 7)
}
if_eq! n, VARINT_MAX[t - 2] {
static k = LAST_BITS[t - 2]
constrain_eq! slice((clone! bits), 8 * last + k, 7 - k), calloc(7 - k)
}
}
}
if_eq! t, 6 {
static prefix = typed_varint_static(n)
constrain_eq! slice((clone! bytes), offset, len! prefix), prefix
}
if_eq! t, 7 {
constrain_eq! bytes[offset], n
}
offset = offset + typed_width(t, n)
}
bits