Module 0x2::bcs
This module implements BCS (de)serialization in Move. Full specification can be found here: https://github.com/diem/bcs
Short summary (for Move-supported types):
- address - sequence of X bytes
- bool - byte with 0 or 1
- u8 - a single u8 byte
- u16 / u32 / u64 / u128 / u256 - LE bytes
- vector - ULEB128 length + LEN elements
- option - first byte bool: None (0) or Some (1), then value
Usage example:
/// This function reads u8 and u64 value from the input
/// and returns the rest of the bytes.
fun deserialize(bytes: vector<u8>): (u8, u64, vector<u8>) {
use sui::bcs::{Self, BCS};
let prepared: BCS = bcs::new(bytes);
let (u8_value, u64_value) = (
prepared.peel_u8(),
prepared.peel_u64()
);
// unpack bcs struct
let leftovers = prepared.into_remainder_bytes();
(u8_value, u64_value, leftovers)
}
- Struct
BCS
- Constants
- Function
to_bytes
- Function
new
- Function
into_remainder_bytes
- Function
peel_address
- Function
peel_bool
- Function
peel_u8
- Function
peel_u16
- Function
peel_u32
- Function
peel_u64
- Function
peel_u128
- Function
peel_u256
- Function
peel_vec_length
- Function
peel_vec_address
- Function
peel_vec_bool
- Function
peel_vec_u8
- Function
peel_vec_vec_u8
- Function
peel_vec_u16
- Function
peel_vec_u32
- Function
peel_vec_u64
- Function
peel_vec_u128
- Function
peel_vec_u256
- Function
peel_option_address
- Function
peel_option_bool
- Function
peel_option_u8
- Function
peel_option_u16
- Function
peel_option_u32
- Function
peel_option_u64
- Function
peel_option_u128
- Function
peel_option_u256
use 0x1::bcs;
use 0x1::option;
use 0x1::vector;
use 0x2::address;
Struct BCS
A helper struct that saves resources on operations. For better vector performance, it stores reversed bytes of the BCS and enables use of vector::pop_back.
struct BCS has copy, drop, store
Fields
- bytes: vector<u8>
Constants
For when ULEB byte is out of range (or not found).
const ELenOutOfRange: u64 = 2;
For when the boolean value different than 0 or 1.
const ENotBool: u64 = 1;
For when bytes length is less than required for deserialization.
const EOutOfRange: u64 = 0;
Function to_bytes
Get BCS serialized bytes for any value. Re-exports stdlib bcs::to_bytes.
public fun to_bytes<T>(value: &T): vector<u8>
Implementation
public fun to_bytes<T>(value: &T): vector<u8> {
bcs::to_bytes(value)
}