MoonbitBSON

A BSON encoding and decoding library

moon add ZSeanYves/MoonbitBSON@0.3.0
Download zip
Author
Version
0.3.0
License
Apache-2.0
Last updated
26 days ago
Downloads
20
README

#MoonbitBSON

License

Strict BSON 1.1 encoding and decoding for MoonBit. The package uses only MoonBit core libraries and supports wasm, wasm-gc, JavaScript, and native. The 0.3 API adds typed DateTime, ObjectId, UUID, raw element access, and generic BSON serialization traits.

#Install

moon add ZSeanYves/MoonbitBSON

import {
"ZSeanYves/MoonbitBSON",
}

#Usage

let user = @MoonbitBSON.Document::new()
.set("name", @MoonbitBSON.Bson::String("Ada"))
.set("age", @MoonbitBSON.Bson::Int32(37))
.set("active", @MoonbitBSON.Bson::Boolean(true))
.set(
"scores",
@MoonbitBSON.Bson::Array([
@MoonbitBSON.Bson::Double(9.5),
@MoonbitBSON.Bson::Double(10.0),
]),
)

let bytes = user.to_bytes()
let decoded = @MoonbitBSON.Document::from_bytes(bytes)

assert_eq(decoded.require_string("name"), "Ada")
assert_eq(decoded.require_int32("age"), 37)

decode rejects trailing bytes. For framed data, use decode_prefix, which returns the decoded document and consumed byte count. RawDocument validates and preserves the original wire bytes, including order and duplicate keys. Use RawDocument::elements or get_element when a caller needs to inspect or decode only selected fields.

#Supported BSON types

Double, String, Document, Array, Binary (including modern subtypes), Undefined, ObjectId, Boolean, UTC DateTime, Null, Regex, DBPointer, JavaScript, Symbol, JavaScript with scope, Int32, Timestamp, Int64, Decimal128, MinKey, and MaxKey.

Deprecated BSON wire types remain decodable for interoperability.

#Safety and errors

  • Declared document and array lengths are hard boundaries.
  • Exact decoding rejects trailing bytes and invalid terminators.
  • UTF-8, Boolean bytes, old binary lengths, ObjectId/Decimal128 sizes, Regex options, depth, and total size are validated.
  • Every BsonError carries a category, byte offset, document path, and message.
  • Degenerate BSON array keys are accepted and normalized as required by the MongoDB BSON Corpus. Strict applications can enable DecodeOptions::new(require_canonical_array_keys=true).

#Extended JSON

Canonical Extended JSON encoding and parsing is available through Document::to_extended_json, to_extended_json_string, from_extended_json, and from_extended_json_string.

Relaxed output is available through to_relaxed_extended_json and to_relaxed_extended_json_string. It emits finite numbers as native JSON and UTC DateTime values from 1970 through year 9999 as RFC 3339 strings; dates outside that range retain the lossless $numberLong wrapper.

Decimal128 supports exact IEEE 754-2008 text conversion through Decimal128::from_string and Decimal128::to_string, including signed zero, subnormal values, exponent clamping, NaN, and infinity. Canonical and Relaxed Extended JSON both use the standard $numberDecimal representation.

DateTime is a typed UTC millisecond value with RFC 3339 parsing and formatting. Uuid supports canonical, compact, and URN text forms and BSON binary subtype 4. ObjectId::from_parts accepts caller-controlled timestamp, process-unique bytes, and counter values; ObjectId::new uses OS/Web Crypto entropy and fails explicitly when the host cannot provide it.

ToBson and FromBson provide opt-in generic conversions for application types, including arrays, maps, options, and the typed BSON values.

MoonBit does not allow user-defined traits in the compiler's built-in derive set. The current compiler reports E4077 for derive(ToBson); #custom.* attributes are metadata for external tools and do not register a compiler derive. For serde-style generated implementations, use the checked-in schema codegen tool or the annotation-driven struct generator:

node tools/bson-codegen.mjs codegen/example.schema.json src/codegen_generated_test.mbt

node tools/bson-derive.mjs src/derive_types_test.mbt src/derive_generated_test.mbt

The generated output is checked in and can be verified with --check in CI.

RawDocumentView and RawElementView retain BytesView slices and decode values only when requested. RawBsonRef keeps nested values, string payloads, and binary payloads borrowed until to_bson is called. BsonStreamDecoder and BsonStreamRawDecoder handle arbitrarily split and batched frames; the latter returns raw views without materializing Document values. A frame split across input chunks is assembled in internal pending storage, while returned views remain valid after later push calls. Its max_size argument defaults to 16 MiB and rejects oversized declared frames before they are buffered. BsonStreamEncoder appends owned frames. ObjectId::new uses OS/Web Crypto entropy and raises UnsupportedEntropy on hosts without a secure source. WASM hosts can install a secure callback with install_secure_entropy_provider; src/wasm_entropy is a small import adapter for hosts exposing the secure_random_u32 function in the moonbit:bson WebAssembly import module.

#Development

moon fmt --check src moon check --target all --deny-warn --warn-list +73 moon test --target all --deny-warn --warn-list +73 moon test --release --target all --deny-warn --warn-list +73 moon bench --target native --release moon coverage analyze -- -f summary node tools/bson-codegen.mjs --check codegen/example.schema.json src/codegen_generated_test.mbt node tools/bson-derive.mjs --check src/derive_types_test.mbt src/derive_generated_test.mbt node tools/decimal128-differential.mjs moon info --target all moon package --list

Tests include the complete MongoDB BSON Corpus JSON suite vendored under testdata/bson-corpus, all truncation points for mixed documents, generated property cases, bounded decoder fuzz smoke cases, strict malformed-input cases, Decimal128 text vectors, and Canonical/Relaxed Extended JSON.

See CHANGELOG.md for the breaking 0.3.0 migration and MAINTENANCE.md for implementation status and remaining work. The long-running native AFL++ decoder harness is documented in tools/README.md.

#License

Apache-2.0. See LICENSE.

#MoonbitBSON

MoonbitBSON implements strict BSON 1.1 binary encoding and decoding with an owned, insertion-ordered Document model.

///|
test "build and roundtrip a document" {
let user = Document::new()
.set("name", String("Ada"))
.set("age", Int32(37))
.set("active", Boolean(true))
.set("scores", Array([Double(9.5), Double(10.0)]))
let encoded = user.to_bytes()
let decoded = Document::from_bytes(encoded)
assert_eq(decoded.require_string("name"), "Ada")
assert_eq(decoded.require_int32("age"), 37)
}

decode consumes exactly one document. Use decode_prefix for framed streams.

///|
test "decode a framed document" {
let encoded = Document::new().set("x", Int64(42L)).to_bytes()
let framed = encoded + b"remaining"
let (document, consumed) = decode_prefix(framed[:])
assert_eq(document.require_int64("x"), 42L)
assert_eq(consumed, encoded.length())
}

Canonical and Relaxed Extended JSON are available for every BSON value. Decimal128 uses an exact IEEE 754-2008 text codec, and Relaxed DateTime values use RFC 3339 strings when they are between the Unix epoch and year 9999.

///|
test "canonical Extended JSON" {
let document = Document::new()
.set("count", Int64(9007199254740993L))
.set("decimal", Decimal128(Decimal128::from_string("1.2500")))
let text = document.to_extended_json_string()
let decoded = Document::from_extended_json_string(text)
assert_eq(decoded, document)
}

Typed DateTime, UUID, ObjectId, and generic serialization APIs keep BSON-only invariants out of application code. Raw elements can be inspected before their values are decoded.

///|
test "typed and raw APIs" {
let uuid = Uuid::from_string("00112233-4455-6677-8899-aabbccddeeff")
let document = Document::new()
.set("created", DateTime(DateTime::from_millis(0L)))
.set("request_id", Binary(uuid.to_binary()))
let raw = RawDocument::from_bytes(serialize_to_bytes(document))
assert_eq(raw.get_element("created").unwrap().type_code(), 0x09)
let decoded : Document = deserialize_from_bytes(raw.bytes())
assert_eq(decoded.require_datetime("created").to_millis(), 0L)
assert_eq(decoded.require_uuid("request_id"), uuid)
}

For a single borrowed frame, keep its input allocation alive and use the raw view. For high-throughput framing, use one of the stream decoders:

///|
test "borrowed view and split stream" {
let bytes = Document::new().set("ok", Boolean(true)).to_bytes()
let view = RawDocumentView::from_bytes(bytes[:])
assert_eq(view.iter().next().unwrap().key(), "ok")
let stream = BsonStreamDecoder::new()
assert_eq(stream.push(bytes[:2]).length(), 0)
assert_eq(stream.push(bytes[2:])[0].require_bool("ok"), true)
stream.finish()
}

RawBsonRef extends the borrowed API to nested documents, arrays, UTF-8 string payloads, and binary payloads. Values remain borrowed until the caller chooses to_bson, to_document, or to_array.

BsonStreamRawDecoder is the borrowed counterpart to BsonStreamDecoder:

///|
test "raw stream view" {
let first = Document::new().set("ok", Boolean(true)).to_bytes()
let second = Document::new().set("count", Int32(2)).to_bytes()
let stream = BsonStreamRawDecoder::new()
let views = stream.push(first + second)
assert_eq(views.length(), 2)
assert_eq(views[0].get("ok").unwrap().to_bson(), Boolean(true))
assert_eq(views[1].get("count").unwrap().to_bson(), Int32(2))
stream.finish()
}

Complete frames are sliced from an immutable pending Bytes buffer. A frame split across chunks is assembled in that buffer; returned views retain their backing bytes and remain valid after later push calls. This avoids per-frame Document materialization, but cannot be end-to-end zero-copy when the input frame arrives in separate allocations. BsonStreamRawDecoder::new defaults to a 16 MiB per-frame limit and rejects oversized declared lengths before buffering.

MoonBit cannot derive user-defined traits with the compiler's built-in derive system. The current compiler reports E4077 for derive(ToBson), while #custom.* attributes are intentionally ignored by the compiler and can only be consumed by external tools. Use tools/bson-derive.mjs for checked-in serde-like implementations; the /// @bson.derive and /// @bson.rename("...") annotations are source-level metadata consumed by that generator.

#
SecureEntropyProvider

type SecureEntropyProvider = (Int) -> Bytes?

Host-provided secure entropy hook for portable targets such as Wasm. The callback must return exactly count unpredictable bytes, or None when it cannot satisfy the request.

#
FromBson

pub(open) trait FromBson {
fn from_bson(Bson) -> Self raise BsonError
}

Convert a BSON value into a MoonBit value.
impl FromBson for Bool
impl FromBson for Int
impl FromBson for Int64
impl FromBson for Double
impl FromBson for String
impl FromBson for Option[T]
impl FromBson for Bytes
impl FromBson for Array[T]
impl FromBson for Map[String, T]

#
ToBson

pub(open) trait ToBson {
fn to_bson(Self) -> Bson raise BsonError
}

Convert a MoonBit value into the BSON data model.
impl ToBson for Bool
impl ToBson for Int
impl ToBson for Int64
impl ToBson for Double
impl ToBson for String
impl ToBson for Option[T]
impl ToBson for Bytes
impl ToBson for Array[T]
impl ToBson for Map[String, T]

#
BsonError

pub suberror BsonError {
Failure(BsonErrorInfo)
} derive(Eq,
Debug
)

The single error raised by the public BSON APIs.

#
BsonError::info

fn BsonError::info(self : BsonError) -> BsonErrorInfo

#
Binary

pub struct Binary {
subtype : BinarySubtype
bytes : Bytes
} derive(Eq,
Debug
)

#
Binary::as_uuid

fn Binary::as_uuid(self : Binary) -> Uuid?

#
Binary::bytes

fn Binary::bytes(self : Binary) -> Bytes

#
Binary::new

fn Binary::new(subtype : BinarySubtype, bytes : Bytes) -> Binary

#
Binary::subtype

fn Binary::subtype(self : Binary) -> BinarySubtype

#
BinarySubtype

pub(all) enum BinarySubtype {
Generic
Function
BinaryOld
UuidOld
Uuid
Md5
Encrypted
Column
Sensitive
Vector
Reserved(Byte)
UserDefined(Byte)
} derive(Eq,
Debug
)

BSON binary subtypes, including the subtypes added by BSON 1.1.

#
BinarySubtype::from_byte

fn BinarySubtype::from_byte(value : Byte) -> BinarySubtype

#
BinarySubtype::to_byte

fn BinarySubtype::to_byte(self : BinarySubtype) -> Byte

#
Bson

pub(all) enum Bson {
Double(Double)
String(String)
Document(Document)
Array(Array[Bson])
Binary(Binary)
Undefined
ObjectId(ObjectId)
Boolean(Bool)
DateTime(DateTime)
Null
Regex(Regex)
DbPointer(DbPointer)
JavaScript(String)
Symbol(String)
JavaScriptWithScope(JavaScriptWithScope)
Int32(Int)
Timestamp(Timestamp)
Int64(Int64)
Decimal128(Decimal128)
MinKey
MaxKey
} derive(Eq,
Debug
)

Complete BSON 1.1 value model, including deprecated wire types for decoding.
impl FromBson for Bson
impl ToBson for Bson

#
Bson::as_array

fn Bson::as_array(self : Bson) -> Array[Bson]?

#
Bson::as_binary

fn Bson::as_binary(self : Bson) -> Binary?

#
Bson::as_bool

fn Bson::as_bool(self : Bson) -> Bool?

#
Bson::as_datetime

fn Bson::as_datetime(self : Bson) -> DateTime?

#
Bson::as_decimal128

fn Bson::as_decimal128(self : Bson) -> Decimal128?

#
Bson::as_document

fn Bson::as_document(self : Bson) -> Document?

#
Bson::as_double

fn Bson::as_double(self : Bson) -> Double?

#
Bson::as_int32

fn Bson::as_int32(self : Bson) -> Int?

#
Bson::as_int64

fn Bson::as_int64(self : Bson) -> Int64?

#
Bson::as_object_id

fn Bson::as_object_id(self : Bson) -> ObjectId?

#
Bson::as_regex

fn Bson::as_regex(self : Bson) -> Regex?

#
Bson::as_string

fn Bson::as_string(self : Bson) -> String?

#
Bson::as_timestamp

fn Bson::as_timestamp(self : Bson) -> Timestamp?

#
Bson::as_uuid

fn Bson::as_uuid(self : Bson) -> Uuid?

#
Bson::from_extended_json

fn Bson::from_extended_json(value : Json) -> Bson raise BsonError

#
Bson::to_extended_json

fn Bson::to_extended_json(self : Bson) -> Json raise BsonError

#
Bson::to_relaxed_extended_json

fn Bson::to_relaxed_extended_json(self : Bson) -> Json raise BsonError

Convert a BSON value to Relaxed Extended JSON.

#
Bson::type_name

fn Bson::type_name(self : Bson) -> String

#
BsonErrorInfo

pub struct BsonErrorInfo {
kind : BsonErrorKind
offset : Int
path : String
message : String
} derive(Eq,
Debug
)

Structured context attached to every BSON error.

#
BsonErrorInfo::kind

#
BsonErrorInfo::message

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

#
BsonErrorInfo::offset

fn BsonErrorInfo::offset(self : BsonErrorInfo) -> Int

#
BsonErrorInfo::path

fn BsonErrorInfo::path(self : BsonErrorInfo) -> String

#
BsonErrorKind

pub(all) enum BsonErrorKind {
UnexpectedEnd
InvalidLength
InvalidUtf8
InvalidCString
InvalidBoolean
InvalidArrayIndex
InvalidBinary
InvalidObjectId
InvalidUuid
InvalidDateTime
InvalidDecimal128
InvalidRegex
UnsupportedType
TrailingData
DepthLimit
SizeLimit
InvalidExtendedJson
TypeMismatch
UnsupportedEntropy
} derive(Eq,
Debug
)

Stable categories for BSON encoding, decoding, and Extended JSON failures.

#
BsonStreamDecoder

pub struct BsonStreamDecoder {
pending : Bytes
} derive(
Debug
)

A chunked BSON frame decoder for transports that split documents arbitrarily.

#
BsonStreamDecoder::finish

fn BsonStreamDecoder::finish(self : BsonStreamDecoder) -> Unit raise BsonError

Finish the stream, rejecting an incomplete trailing frame.

#
BsonStreamDecoder::new

#
BsonStreamDecoder::push

fn BsonStreamDecoder::push(self : BsonStreamDecoder, chunk : BytesView) -> Array[Document] raise BsonError

Feed a chunk and return every complete document now available.

#
BsonStreamEncoder

pub struct BsonStreamEncoder {
buffer :
Buffer

}

Append-only frame encoder for transports that batch complete BSON frames.

#
BsonStreamEncoder::bytes

fn BsonStreamEncoder::bytes(self : BsonStreamEncoder) -> Bytes

#
BsonStreamEncoder::new

fn BsonStreamEncoder::new(size_hint? : Int) -> BsonStreamEncoder

#
BsonStreamEncoder::push

fn BsonStreamEncoder::push(self : BsonStreamEncoder, document : Document) -> Unit raise BsonError

Encode one complete document and append it as one frame.

#
BsonStreamRawDecoder

pub struct BsonStreamRawDecoder {
pending : Bytes
max_size : Int
} derive(
Debug
)

A chunked BSON frame decoder that returns borrowed raw document views.

Complete frames are sliced from the decoder's immutable pending buffer; no Document or per-frame byte copy is created. A frame split across chunks is assembled in that buffer, and returned views remain valid after later push calls.

#
BsonStreamRawDecoder::finish

fn BsonStreamRawDecoder::finish(self : BsonStreamRawDecoder) -> Unit raise BsonError

Finish the stream, rejecting an incomplete trailing raw frame.

#
BsonStreamRawDecoder::new

fn BsonStreamRawDecoder::new(max_size? : Int) -> BsonStreamRawDecoder

Create a raw decoder with a per-frame size limit (16 MiB by default).

#
BsonStreamRawDecoder::push

fn BsonStreamRawDecoder::push(self : BsonStreamRawDecoder, chunk : BytesView) -> Array[RawDocumentView] raise BsonError

Feed a chunk and return every complete raw view now available.

#
DateTime

pub struct DateTime {
milliseconds : Int64
} derive(Eq,
Debug
)

A BSON UTC datetime with millisecond precision.
impl ToBson for DateTime

#
DateTime::from_millis

fn DateTime::from_millis(milliseconds : Int64) -> DateTime

#
DateTime::from_rfc3339

fn DateTime::from_rfc3339(value : String) -> DateTime raise BsonError

#
DateTime::now

fn DateTime::now() -> DateTime

#
DateTime::to_millis

fn DateTime::to_millis(self : DateTime) -> Int64

#
DateTime::to_rfc3339

fn DateTime::to_rfc3339(self : DateTime) -> String raise BsonError

#
DbPointer

pub struct DbPointer {
collection : String
id : ObjectId
} derive(Eq,
Debug
)

#
DbPointer::collection

fn DbPointer::collection(self : DbPointer) -> String

#
DbPointer::id

fn DbPointer::id(self : DbPointer) -> ObjectId

#
DbPointer::new

fn DbPointer::new(collection : String, id : ObjectId) -> DbPointer

#
Decimal128

pub struct Decimal128 {
bytes : Bytes
} derive(Eq,
Debug
)

Decimal128 is kept in its canonical 16-byte IEEE 754-2008 representation.

#
Decimal128::bytes

fn Decimal128::bytes(self : Decimal128) -> Bytes

#
Decimal128::from_bytes

fn Decimal128::from_bytes(bytes : Bytes) -> Decimal128 raise BsonError

#
Decimal128::from_string

fn Decimal128::from_string(value : String) -> Decimal128 raise BsonError

Parse an exact IEEE 754 Decimal128 string.

#
Decimal128::to_string

fn Decimal128::to_string(self : Decimal128) -> String

Format this Decimal128 using MongoDB's canonical text representation.

#
DecodeOptions

pub struct DecodeOptions {
max_depth : Int
max_size : Int
require_canonical_array_keys : Bool
} derive(Eq,
Debug
)

#
DecodeOptions::max_depth

fn DecodeOptions::max_depth(self : DecodeOptions) -> Int

#
DecodeOptions::max_size

fn DecodeOptions::max_size(self : DecodeOptions) -> Int

#
DecodeOptions::new

fn DecodeOptions::new(max_depth? : Int, max_size? : Int, require_canonical_array_keys? : Bool) -> DecodeOptions

#
DecodeOptions::require_canonical_array_keys

fn DecodeOptions::require_canonical_array_keys(self : DecodeOptions) -> Bool

#
Document

pub struct Document {
values : Map[String, Bson]
} derive(Eq,
Debug
)

An insertion-ordered, owned BSON document.
impl ToBson for Document

#
Document::contains

fn Document::contains(self : Document, key : String) -> Bool

#
Document::entries

fn Document::entries(self : Document) -> Array[(String, Bson)]

#
Document::from_array

fn Document::from_array(values : Array[(String, Bson)]) -> Document

#
Document::from_bytes

fn Document::from_bytes(data : Bytes) -> Document raise BsonError

#
Document::from_extended_json

fn Document::from_extended_json(value : Json) -> Document raise BsonError

#
Document::from_extended_json_string

fn Document::from_extended_json_string(value : String) -> Document raise BsonError

#
Document::get

fn Document::get(self : Document, key : String) -> Bson?

#
Document::get_array

fn Document::get_array(self : Document, key : String) -> Array[Bson]?

#
Document::get_binary

fn Document::get_binary(self : Document, key : String) -> Binary?

#
Document::get_bool

fn Document::get_bool(self : Document, key : String) -> Bool?

#
Document::get_datetime

fn Document::get_datetime(self : Document, key : String) -> DateTime?

#
Document::get_decimal128

fn Document::get_decimal128(self : Document, key : String) -> Decimal128?

#
Document::get_document

fn Document::get_document(self : Document, key : String) -> Document?

#
Document::get_double

fn Document::get_double(self : Document, key : String) -> Double?

#
Document::get_int32

fn Document::get_int32(self : Document, key : String) -> Int?

#
Document::get_int64

fn Document::get_int64(self : Document, key : String) -> Int64?

#
Document::get_object_id

fn Document::get_object_id(self : Document, key : String) -> ObjectId?

#
Document::get_regex

fn Document::get_regex(self : Document, key : String) -> Regex?

#
Document::get_string

fn Document::get_string(self : Document, key : String) -> String?

#
Document::get_timestamp

fn Document::get_timestamp(self : Document, key : String) -> Timestamp?

#
Document::get_uuid

fn Document::get_uuid(self : Document, key : String) -> Uuid?

#
Document::is_empty

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

#
Document::length

fn Document::length(self : Document) -> Int

#
Document::new

fn Document::new() -> Document

#
Document::remove

fn Document::remove(self : Document, key : String) -> Unit

#
Document::require

fn Document::require(self : Document, key : String) -> Bson raise BsonError

#
Document::require_array

fn Document::require_array(self : Document, key : String) -> Array[Bson] raise BsonError

#
Document::require_binary

fn Document::require_binary(self : Document, key : String) -> Binary raise BsonError

#
Document::require_bool

fn Document::require_bool(self : Document, key : String) -> Bool raise BsonError

#
Document::require_datetime

fn Document::require_datetime(self : Document, key : String) -> DateTime raise BsonError

#
Document::require_decimal128

fn Document::require_decimal128(self : Document, key : String) -> Decimal128 raise BsonError

#
Document::require_document

fn Document::require_document(self : Document, key : String) -> Document raise BsonError

#
Document::require_double

fn Document::require_double(self : Document, key : String) -> Double raise BsonError

#
Document::require_int32

fn Document::require_int32(self : Document, key : String) -> Int raise BsonError

#
Document::require_int64

fn Document::require_int64(self : Document, key : String) -> Int64 raise BsonError

#
Document::require_object_id

fn Document::require_object_id(self : Document, key : String) -> ObjectId raise BsonError

#
Document::require_regex

fn Document::require_regex(self : Document, key : String) -> Regex raise BsonError

#
Document::require_string

fn Document::require_string(self : Document, key : String) -> String raise BsonError

#
Document::require_timestamp

fn Document::require_timestamp(self : Document, key : String) -> Timestamp raise BsonError

#
Document::require_uuid

fn Document::require_uuid(self : Document, key : String) -> Uuid raise BsonError

#
Document::set

fn Document::set(self : Document, key : String, value : Bson) -> Document

#
Document::to_array

fn Document::to_array(self : Document) -> Array[(String, Bson)]

#
Document::to_bytes

fn Document::to_bytes(self : Document) -> Bytes raise BsonError

#
Document::to_extended_json

fn Document::to_extended_json(self : Document) -> Json raise BsonError

Convert a document to Canonical Extended JSON.

#
Document::to_extended_json_string

fn Document::to_extended_json_string(self : Document, indent? : Int) -> String raise BsonError

#
Document::to_relaxed_extended_json

fn Document::to_relaxed_extended_json(self : Document) -> Json raise BsonError

Convert a document to Relaxed Extended JSON.

#
Document::to_relaxed_extended_json_string

fn Document::to_relaxed_extended_json_string(self : Document, indent? : Int) -> String raise BsonError

#
Document::write_to

fn Document::write_to(self : Document, buffer :
Buffer
) -> Unit raise BsonError

Append this document to an existing official MoonBit Buffer.

#
EncodeOptions

pub struct EncodeOptions {
max_depth : Int
max_size : Int
} derive(Eq,
Debug
)

#
EncodeOptions::max_depth

fn EncodeOptions::max_depth(self : EncodeOptions) -> Int

#
EncodeOptions::max_size

fn EncodeOptions::max_size(self : EncodeOptions) -> Int

#
EncodeOptions::new

fn EncodeOptions::new(max_depth? : Int, max_size? : Int) -> EncodeOptions

#
JavaScriptWithScope

pub struct JavaScriptWithScope {
code : String
scope : Document
} derive(Eq,
Debug
)

#
JavaScriptWithScope::code

fn JavaScriptWithScope::code(self : JavaScriptWithScope) -> String

#
JavaScriptWithScope::new

fn JavaScriptWithScope::new(code : String, scope : Document) -> JavaScriptWithScope

#
JavaScriptWithScope::scope

#
ObjectId

pub struct ObjectId {
bytes : Bytes
} derive(Eq,
Debug
)

A 12-byte BSON ObjectId.
impl ToBson for ObjectId

#
ObjectId::bytes

fn ObjectId::bytes(self : ObjectId) -> Bytes

#
ObjectId::from_bytes

fn ObjectId::from_bytes(bytes : Bytes) -> ObjectId raise BsonError

#
ObjectId::from_hex

fn ObjectId::from_hex(value : String) -> ObjectId raise BsonError

#
ObjectId::from_parts

fn ObjectId::from_parts(timestamp : UInt, process_unique : Bytes, counter : UInt) -> ObjectId raise BsonError

#
ObjectId::new

fn ObjectId::new() -> ObjectId raise BsonError

Generate an ObjectId using an OS/Web Crypto secure random process value and counter seed. Portable Wasm without a host entropy provider raises UnsupportedEntropy; it never falls back to a deterministic PRNG.

#
ObjectId::new_secure

fn ObjectId::new_secure() -> ObjectId raise BsonError

Explicit alias for callers that want to document the entropy requirement.

#
ObjectId::timestamp

fn ObjectId::timestamp(self : ObjectId) -> DateTime

#
ObjectId::to_hex

fn ObjectId::to_hex(self : ObjectId) -> String

#
RawArrayView

pub struct RawArrayView {
document : RawDocumentView
} derive(Eq,
Debug
)

A borrowed BSON array, represented by its wire document view.

#
RawArrayView::document

fn RawArrayView::document(self : RawArrayView) -> RawDocumentView

#
RawArrayView::from_bytes

fn RawArrayView::from_bytes(bytes : BytesView) -> RawArrayView raise BsonError

#
RawArrayView::get

fn RawArrayView::get(self : RawArrayView, index : Int) -> RawBsonRef? raise BsonError

#
RawArrayView::iter

#
RawArrayView::to_array

fn RawArrayView::to_array(self : RawArrayView) -> Array[Bson] raise BsonError

Convert a borrowed array to owned values explicitly.

#
RawBinaryRef

pub struct RawBinaryRef {
subtype : BinarySubtype
bytes : BytesView
} derive(Eq,
Debug
)

Borrowed BSON binary payload.

#
RawBinaryRef::bytes

fn RawBinaryRef::bytes(self : RawBinaryRef) -> BytesView

#
RawBinaryRef::subtype

fn RawBinaryRef::subtype(self : RawBinaryRef) -> BinarySubtype

#
RawBsonRef

pub(all) enum RawBsonRef {
Double(Double)
String(RawStringRef)
Document(RawDocumentView)
Array(RawArrayView)
Binary(RawBinaryRef)
Undefined
ObjectId(BytesView)
Boolean(Bool)
DateTime(Int64)
Null
Regex(RawRegexRef)
DbPointer(RawDbPointerRef)
JavaScript(RawStringRef)
Symbol(RawStringRef)
JavaScriptWithScope(RawJavaScriptWithScopeRef)
Int32(Int)
Timestamp(Timestamp)
Int64(Int64)
Decimal128(BytesView)
MinKey
MaxKey
} derive(Eq,
Debug
)

A BSON value that borrows all byte payloads from its source document.

#
RawBsonRef::to_bson

fn RawBsonRef::to_bson(self : RawBsonRef) -> Bson raise BsonError

Explicitly materialize a borrowed value into the owned BSON model.

#
RawDbPointerRef

pub struct RawDbPointerRef {
namespace_value : RawStringRef
id : BytesView
} derive(Eq,
Debug
)

Borrowed BSON DBPointer.

#
RawDbPointerRef::id_bytes

fn RawDbPointerRef::id_bytes(self : RawDbPointerRef) -> BytesView

#
RawDbPointerRef::namespace_value

fn RawDbPointerRef::namespace_value(self : RawDbPointerRef) -> RawStringRef

#
RawDocument

pub struct RawDocument {
bytes : Bytes
} derive(Eq,
Debug
)

Validated owned raw BSON. It preserves field order, duplicate keys, and bytes.

#
RawDocument::bytes

fn RawDocument::bytes(self : RawDocument) -> Bytes

#
RawDocument::elements

fn RawDocument::elements(self : RawDocument) -> Array[RawElement] raise BsonError

Return the top-level elements without decoding their values.

#
RawDocument::from_bytes

fn RawDocument::from_bytes(data : Bytes) -> RawDocument raise BsonError

#
RawDocument::from_prefix

fn RawDocument::from_prefix(data : BytesView) -> (RawDocument, Int) raise BsonError

#
RawDocument::get_element

fn RawDocument::get_element(self : RawDocument, key : String) -> RawElement? raise BsonError

#
RawDocument::to_document

fn RawDocument::to_document(self : RawDocument) -> Document raise BsonError

#
RawDocument::view

fn RawDocument::view(self : RawDocument) -> BytesView

#
RawDocumentView

pub struct RawDocumentView {
bytes : BytesView
} derive(Eq,
Debug
)

A borrowed BSON document view backed by an existing Bytes allocation.

Construction and element iteration keep the original bytes as BytesView; no document-wide copy or value allocation is performed until a value is decoded explicitly.

#
RawDocumentView::bytes

fn RawDocumentView::bytes(self : RawDocumentView) -> BytesView

#
RawDocumentView::from_bytes

fn RawDocumentView::from_bytes(bytes : BytesView) -> RawDocumentView raise BsonError

#
RawDocumentView::from_prefix

fn RawDocumentView::from_prefix(bytes : BytesView) -> (RawDocumentView, Int) raise BsonError

Create a borrowed view over the first BSON frame in bytes.

#
RawDocumentView::get

fn RawDocumentView::get(self : RawDocumentView, key : String) -> RawBsonRef? raise BsonError

#
RawDocumentView::iter

Return an iterator that keeps element keys and values as byte views.

#
RawDocumentView::length

fn RawDocumentView::length(self : RawDocumentView) -> Int

#
RawDocumentView::to_document

fn RawDocumentView::to_document(self : RawDocumentView) -> Document raise BsonError

#
RawElement

pub struct RawElement {
document : RawDocument
key : String
type_code : Byte
value_start : Int
value_end : Int
} derive(Eq,
Debug
)

A validated BSON element backed by its owning RawDocument.

#
RawElement::key

fn RawElement::key(self : RawElement) -> String

#
RawElement::raw_bytes

fn RawElement::raw_bytes(self : RawElement) -> BytesView

#
RawElement::to_bson

fn RawElement::to_bson(self : RawElement) -> Bson raise BsonError

#
RawElement::type_code

fn RawElement::type_code(self : RawElement) -> Byte

#
RawElementView

pub struct RawElementView {
document : RawDocumentView
key_start : Int
key_end : Int
type_code : Byte
value_start : Int
value_end : Int
} derive(Eq,
Debug
)

A single borrowed BSON element. key() allocates a String; key_bytes() does not.

#
RawElementView::as_binary_bytes

fn RawElementView::as_binary_bytes(self : RawElementView) -> (BinarySubtype, BytesView)? raise BsonError

Borrow binary payload bytes and retain the wire subtype.

#
RawElementView::as_bool

fn RawElementView::as_bool(self : RawElementView) -> Bool? raise BsonError

#
RawElementView::as_datetime_millis

fn RawElementView::as_datetime_millis(self : RawElementView) -> Int64? raise BsonError

#
RawElementView::as_double

fn RawElementView::as_double(self : RawElementView) -> Double? raise BsonError

#
RawElementView::as_int32

fn RawElementView::as_int32(self : RawElementView) -> Int? raise BsonError

#
RawElementView::as_int64

fn RawElementView::as_int64(self : RawElementView) -> Int64? raise BsonError

#
RawElementView::as_string_bytes

fn RawElementView::as_string_bytes(self : RawElementView) -> BytesView? raise BsonError

Borrow a BSON string payload without decoding UTF-8 or allocating a String.

#
RawElementView::key

fn RawElementView::key(self : RawElementView) -> String raise BsonError

#
RawElementView::key_bytes

fn RawElementView::key_bytes(self : RawElementView) -> BytesView

#
RawElementView::raw_bytes

fn RawElementView::raw_bytes(self : RawElementView) -> BytesView

#
RawElementView::to_bson

fn RawElementView::to_bson(self : RawElementView) -> Bson raise BsonError

#
RawElementView::type_code

fn RawElementView::type_code(self : RawElementView) -> Byte

#
RawElementView::value

Return the borrowed value represented by this element.

#
RawElementViewIter

pub struct RawElementViewIter {
document : RawDocumentView
position : Int
end : Int
}

A stateful iterator over borrowed top-level elements.

#
RawElementViewIter::next

#
RawJavaScriptWithScopeRef

pub struct RawJavaScriptWithScopeRef {
code : RawStringRef
scope : RawDocumentView
} derive(Eq,
Debug
)

Borrowed JavaScript-with-scope value.

#
RawJavaScriptWithScopeRef::code

#
RawJavaScriptWithScopeRef::scope

#
RawRegexRef

pub struct RawRegexRef {
pattern : BytesView
options : BytesView
} derive(Eq,
Debug
)

Borrowed BSON regular expression.

#
RawRegexRef::options

fn RawRegexRef::options(self : RawRegexRef) -> BytesView

#
RawRegexRef::pattern

fn RawRegexRef::pattern(self : RawRegexRef) -> BytesView

#
RawRegexRef::to_regex

fn RawRegexRef::to_regex(self : RawRegexRef) -> Regex raise BsonError

#
RawStringRef

pub struct RawStringRef {
bytes : BytesView
} derive(Eq,
Debug
)

A BSON string whose UTF-8 payload remains borrowed.

#
RawStringRef::bytes

fn RawStringRef::bytes(self : RawStringRef) -> BytesView

#
RawStringRef::to_string

fn RawStringRef::to_string(self : RawStringRef) -> String raise BsonError

#
Regex

pub struct Regex {
pattern : String
options : String
} derive(Eq,
Debug
)

#
Regex::new

fn Regex::new(pattern : String, options : String) -> Regex

#
Regex::options

fn Regex::options(self : Regex) -> String

#
Regex::pattern

fn Regex::pattern(self : Regex) -> String

#
Timestamp

pub struct Timestamp {
time : UInt
increment : UInt
} derive(Eq,
Debug
)

BSON timestamps store an increment followed by seconds since the epoch.

#
Timestamp::increment

fn Timestamp::increment(self : Timestamp) -> UInt

#
Timestamp::new

fn Timestamp::new(time : UInt, increment : UInt) -> Timestamp

#
Timestamp::time

fn Timestamp::time(self : Timestamp) -> UInt

#
Uuid

pub struct Uuid {
bytes : Bytes
} derive(Eq,
Debug
)

A standard RFC 4122 UUID encoded as BSON Binary subtype 4.
impl FromBson for Uuid
impl ToBson for Uuid

#
Uuid::bytes

fn Uuid::bytes(self : Uuid) -> Bytes

#
Uuid::from_binary

fn Uuid::from_binary(binary : Binary) -> Uuid raise BsonError

#
Uuid::from_bytes

fn Uuid::from_bytes(bytes : Bytes) -> Uuid raise BsonError

#
Uuid::from_string

fn Uuid::from_string(value : String) -> Uuid raise BsonError

#
Uuid::to_binary

fn Uuid::to_binary(self : Uuid) -> Binary

#
Uuid::to_string

fn Uuid::to_string(self : Uuid) -> String

#
clear_secure_entropy_provider

fn clear_secure_entropy_provider() -> Unit

#
decode

fn decode(data : Bytes) -> Document raise BsonError

Decode exactly one BSON document and reject trailing bytes.

#
decode_prefix

fn decode_prefix(data : BytesView) -> (Document, Int) raise BsonError

Decode the first document in a byte view and return the consumed byte count.

#
decode_prefix_with_options

fn decode_prefix_with_options(data : BytesView, options : DecodeOptions) -> (Document, Int) raise BsonError

#
decode_with_options

fn decode_with_options(data : Bytes, options : DecodeOptions) -> Document raise BsonError

#
deserialize_from_bytes

fn[T : FromBson] deserialize_from_bytes(value : Bytes) -> T raise BsonError

#
encode

fn encode(document : Document) -> Bytes raise BsonError

Encode an owned BSON document using the default safety limits.

#
encode_to

fn encode_to(document : Document, buffer :
Buffer
) -> Unit raise BsonError

#
encode_to_with_options

fn encode_to_with_options(document : Document, buffer :
Buffer
, options : EncodeOptions) -> Unit raise BsonError

#
encode_with_options

fn encode_with_options(document : Document, options : EncodeOptions) -> Bytes raise BsonError

#
from_bson

fn[T : FromBson] from_bson(value : Bson) -> T raise BsonError

#
install_secure_entropy_provider

fn install_secure_entropy_provider(provider : (Int) -> Bytes?) -> Unit

#
secure_entropy_from_provider

fn secure_entropy_from_provider(count : Int) -> Bytes? raise BsonError

#
serialize_to_bytes

fn[T : ToBson] serialize_to_bytes(value : T) -> Bytes raise BsonError

#
to_bson

fn[T : ToBson] to_bson(value : T) -> Bson raise BsonError