moonbin

A lightweight binary serialization and deserialization library for MoonBit.

binary
serialization
moonbit
moon add hourizon/moonbin@0.1.0
Download zip
Author
Version
0.1.0
License
MIT
Last updated
last month
Downloads
9
README

#moonbin

moonbin 第一版以 BinValue 作为核心数据模型,编码器和解码器围绕:

BinValue <-> Bytes

展开。

#编解码示例

///|
test "encode and decode a value" {
let value = BinValue::Object([
("name", BinValue::String("Hou")),
("age", BinValue::Int(18)),
])
let bytes = encode(value)
assert_true(decode(bytes) == Ok(value))
}

#基础值示例

///|
test "create primitive bin values" {
inspect(BinValue::Null.kind(), content="null")
inspect(BinValue::Bool(true).kind(), content="bool")
inspect(BinValue::Int(42).kind(), content="int")
inspect(BinValue::Double(3.14).kind(), content="double")
inspect(BinValue::String("moonbin").kind(), content="string")
}

#结构化数据示例

用户结构体第一版可以手写转换为 BinValue::Object,避免依赖运行时反射:

///|
struct User {
name : String
age : Int
}

///|
fn User::to_bin(self : User) -> BinValue {
BinValue::Object([
("name", BinValue::String(self.name)),
("age", BinValue::Int(self.age)),
])
}

///|
fn User::from_bin(value : BinValue) -> Result[User, DecodeError] {
match value {
BinValue::Object(
[("name", BinValue::String(name)), ("age", BinValue::Int(age))]
) => Ok({ name, age })
other => Err(DecodeError::InvalidType("User object", other.kind()))
}
}

完整的可执行测试位于 adapter_test.mbt

#错误模型示例

///|
test "decode error categories" {
inspect(DecodeError::UnexpectedEOF.kind(), content="unexpected_eof")
inspect(DecodeError::InvalidTag(255).kind(), content="invalid_tag")
}

#
BinValue

pub(all) enum BinValue {
Null
Bool(Bool)
Int(Int)
Double(Double)
String(String)
Bytes(Bytes)
Array(Array[BinValue])
Object(Array[(String, BinValue)])
} derive(Eq,
Debug
)

Core moonbin value model.

BinValue is the stable intermediate representation that moonbin v1 encodes to bytes and decodes from bytes. User-defined structs can be mapped to this model explicitly without relying on runtime reflection.

#
BinValue::kind

fn BinValue::kind(self : BinValue) -> String

Returns the human-readable kind name of a BinValue.

#
ByteReader

pub struct ByteReader {
data : Bytes
offset : Int
}

Byte reader used by moonbin decoders.

#
ByteReader::is_empty

fn ByteReader::is_empty(self : ByteReader) -> Bool

Returns whether there are no unread byte values.

#
ByteReader::len

fn ByteReader::len(self : ByteReader) -> Int

Returns the total number of byte values in this reader.

#
ByteReader::new

fn ByteReader::new(data : Bytes) -> ByteReader

Creates a byte reader from an array of byte values.

#
ByteReader::position

fn ByteReader::position(self : ByteReader) -> Int

Returns the current read position.

#
ByteReader::read_bytes

fn ByteReader::read_bytes(self : ByteReader, length : Int) -> Result[Bytes, DecodeError]

Reads exactly length raw bytes.

#
ByteReader::read_f64

fn ByteReader::read_f64(self : ByteReader) -> Result[Double, DecodeError]

Reads an IEEE 754 double in big-endian byte order.

#
ByteReader::read_i64

fn ByteReader::read_i64(self : ByteReader) -> Result[Int64, DecodeError]

Reads a signed 64-bit integer in big-endian byte order.

#
ByteReader::read_u32

fn ByteReader::read_u32(self : ByteReader) -> Result[UInt, DecodeError]

Reads an unsigned 32-bit integer in big-endian byte order.

#
ByteReader::read_u8

fn ByteReader::read_u8(self : ByteReader) -> Result[Int, DecodeError]

Reads one unsigned byte value and advances the read position.

#
ByteReader::remaining

fn ByteReader::remaining(self : ByteReader) -> Int

Returns how many byte values are still unread.

#
ByteWriter

pub struct ByteWriter {
buffer :
Buffer

}

Byte writer used by moonbin encoders.

#
ByteWriter::is_empty

fn ByteWriter::is_empty(self : ByteWriter) -> Bool

Returns whether no byte values have been written.

#
ByteWriter::len

fn ByteWriter::len(self : ByteWriter) -> Int

Returns the number of byte values written so far.

#
ByteWriter::new

fn ByteWriter::new() -> ByteWriter

Creates an empty byte writer.

#
ByteWriter::to_bytes

fn ByteWriter::to_bytes(self : ByteWriter) -> Bytes

Returns a copy of all bytes written so far.

#
ByteWriter::write_bytes

fn ByteWriter::write_bytes(self : ByteWriter, value : Bytes) -> Unit

Appends raw bytes.

#
ByteWriter::write_f64

fn ByteWriter::write_f64(self : ByteWriter, value : Double) -> Unit

Writes an IEEE 754 double in big-endian byte order.

#
ByteWriter::write_i64

fn ByteWriter::write_i64(self : ByteWriter, value : Int64) -> Unit

Writes a signed 64-bit integer in big-endian byte order.

#
ByteWriter::write_u32

fn ByteWriter::write_u32(self : ByteWriter, value : UInt) -> Unit

Writes an unsigned 32-bit integer in big-endian byte order.

#
ByteWriter::write_u8

fn ByteWriter::write_u8(self : ByteWriter, value : Int) -> Bool

Writes one unsigned byte value.

Returns false when value is outside the valid byte range.

#
DecodeError

pub(all) enum DecodeError {
UnexpectedEOF
InvalidTag(Int)
InvalidType(String, String)
InvalidLength(String)
LimitExceeded(String)
TrailingBytes(Int)
} derive(Eq,
Debug
)

Decode errors returned by moonbin readers and decoders.

The first version keeps errors small and explicit. Later decoder modules can attach these variants to concrete byte-reading and type-checking failures.

#
DecodeError::kind

fn DecodeError::kind(self : DecodeError) -> String

Returns a stable category name for a decode error.

#
DecodeError::message

fn DecodeError::message(self : DecodeError) -> String

Returns a short human-readable message for a decode error.

#
DecodeLimits

pub(all) struct DecodeLimits {
max_depth : Int
max_collection_items : Int
max_value_bytes : Int
} derive(Eq,
Debug
)

Resource limits applied while decoding untrusted input.

#
decode

fn decode(bytes : Bytes) -> Result[BinValue, DecodeError]

Decodes exactly one moonbin v1 value using conservative default limits.

#
decode_with_limits

fn decode_with_limits(bytes : Bytes, limits : DecodeLimits) -> Result[BinValue, DecodeError]

Decodes exactly one moonbin v1 value using explicit resource limits.

The function rejects unread trailing bytes after the top-level value.

#
default_decode_limits

fn default_decode_limits() -> DecodeLimits

Returns conservative default limits for one decoded value.

#
encode

fn encode(value : BinValue) -> Bytes

Encodes one BinValue into the moonbin v1 wire format.

#
error_model_name

fn error_model_name() -> String

Returns the name of the decode error model used by moonbin v1.

#
value_model_name

fn value_model_name() -> String

Returns the name of the core data model used by moonbin v1.

#
version

fn version() -> String

Returns the current moonbin package version.