cbor

A high-performance, standard-compliant CBOR (RFC 8949) serialization library for MoonBit.

cbor
serialization
binary
rfc8949
codec
moon add 2515050242/cbor@0.1.2
Download zip
Version
0.1.2
License
Apache-2.0
Last updated
5 hours ago
Downloads
15
README

#MoonBit CBOR (RFC 8949)

License: Apache 2.0 MoonBit Version

A CBOR (Concise Binary Object Representation, RFC 8949) serialization and deserialization library written in pure MoonBit.

This project was built for the CCF x MoonBit Open Source Competition (2026).

#Core Features

  • RFC 8949 data model coverage for signed/unsigned integers, bytes, text, arrays, maps, tags, simple values, and floating-point decoding.
  • CborDecode conversions for CborValue, Bool, Int64, UInt64, String, Bytes, and Double via decode_as.
  • Full-width unsigned values are preserved as CborValue::Unsigned(UInt64) instead of being narrowed through Int64.
  • Floating-point decoding across half, single, and double precision inputs.
  • Indefinite-length decoding for byte strings, text strings, arrays, and maps.
  • Deterministic map encoding with canonical key ordering.
  • Decoder validation for integer bounds, trailing bytes, malformed simple values, strict UTF-8, and non-canonical integer and length encodings.
  • Human-readable diagnostic notation output for debugging and examples.
  • Versioned application message envelopes for requests, responses, events, and commands.
  • Batch message encoding with producer/sequence metadata for queue and log transports.
  • Nested path queries, immutable document patches, object projection, and field merging.
  • Length-delimited streaming frames with partial-chunk decoding and bounded admission control.
  • Composable application validation reports, lifecycle message storage, retry/dead-letter state, document metrics, and recursive sensitive-field redaction.
  • Bounded application ingress policies that aggregate byte/node/depth limits across documents, messages, batches, and framed streams with indexed rejection reports.

#Installation

The project is verified with the MoonBit 0.10.x toolchain. CI installs the current official toolchain on every supported runner; the local acceptance environment currently uses moonc v0.10.7.

Add the package with the current MoonBit workflow:

moon add 2515050242/cbor

Or add it manually to moon.pkg:

import = [ "2515050242/cbor", ]

#Usage Example

import "2515050242/cbor"

fn main {
let value = cbor.Map([
(cbor.Text("hello"), cbor.Integer(42L)),
(cbor.Text("world"), cbor.Array([cbor.Integer(1L), cbor.Integer(2L)])),
])

let bytes = cbor.encode(value)
println("Encoded \{bytes.length()} bytes.")

let decoded = cbor.decode(bytes) catch {
err => fail("Failed to decode: \{err}")
}
println("Decoded Diagnostic:")
println(cbor.diagnostic(decoded))

let count : Int64 = cbor.decode_as(b"\x18\x2a") catch {
err => fail("Failed to decode Int64: \{err}")
}
println("Decoded integer: \{count}")
}

#CLI Example

The repository includes a runnable CLI in cmd/main:

moon run ./cmd/main moon run ./cmd/main -- decode-hex a26161016162820203 moon run ./cmd/main -- roundtrip-hex 5f42010243030405ff moon run ./cmd/main -- benchmark 20000 moon run ./cmd/main -- application-demo

The benchmark command reports four reproducible workloads: a small map, UTF-8 text containing a non-BMP scalar, a 256-byte binary payload, and a nested array/map value. Each line includes the iteration count, encoded payload size, and elapsed time.

The application demo exercises a versioned request/response batch, a framed transport buffer, nested field queries, validation reports, recursive redaction, and bounded-ingress accounting in one reproducible command.

#Performance Notes

  • The encoder is buffer-backed and streaming-oriented for integers, byte strings, arrays, and maps.
  • The current implementation is not globally zero-allocation: UTF-8 text encoding and canonical map-key sorting still use temporary buffers.
  • The repository documentation has been aligned to this implementation boundary so reviewer expectations match real behavior.

#Validation

Local acceptance loop:

moon fmt --check moon info moon check --target wasm-gc --deny-warn moon test --target wasm-gc --deny-warn

CI additionally runs moon check --target all --deny-warn and moon test --target all --deny-warn on Linux, macOS, and Windows, and checks that formatting and generated interface steps leave a clean checkout.

Windows PowerShell helper:

powershell -ExecutionPolicy Bypass -File .\scripts\verify_acceptance.ps1

Repository self-check report:

python ./scripts/check_repo_compliance.py

The self-check reports both physical MoonBit source lines and effective production source lines (non-empty, non-comment .mbt lines excluding tests). The local production-source gate is 3300 lines so that the project scope is backed by reusable implementation rather than documentation or generated files.

#Competition Notes

  • The repository is public and keeps README, license, CI, tests, and MoonBit-first source visible for OSC2026 review.
  • CI runs formatting, moon info, warning-free checks/tests for all backends, and CLI smoke tests on Linux, macOS, and Windows.
  • The test suite includes RFC 8949 Appendix A vectors plus malformed-input regressions for reviewer verification.
  • The application suite includes 52 deterministic tests covering policy limits, batch ingress, frame recovery, lifecycle transitions, redaction, and aggregate budget accounting.
  • Source attribution and acceptance notes are kept in docs/source-attribution.md and docs/acceptance-checklist.md.

#License

This project is licensed under Apache-2.0. See LICENSE for details.

#
CborDecode

pub trait CborDecode {
fn from_cbor(CborValue) -> Result[Self, CborError]
}

Trait for types that can be deserialized from CBOR.
impl CborDecode for Bool
impl CborDecode for Int64
impl CborDecode for Bytes

#
CborEncode

pub trait CborEncode {
fn to_cbor(Self) -> CborValue
}

Trait for types that can be serialized to CBOR.
impl CborEncode for Bool
impl CborEncode for Int
impl CborEncode for Int64

#
CborError

pub(all) suberror CborError {
UnexpectedEOF
UnexpectedBreak
InvalidMajorType(Byte)
InvalidAdditionalInfo(Byte)
InvalidIndefiniteChunk(Byte)
InvalidUtf8
NonCanonicalEncoding(String)
TrailingBytes(Int)
UnsupportedFloatWidth(Byte)
SemanticError(String)
} derive(Eq,
Debug
)

Errors that can occur during CBOR decoding.
impl Show for CborError

#
AppIngestResult

pub(all) struct AppIngestResult {
accepted : Bool
kind : AppIngressKind
value : CborValue?
values : Array[CborValue]
stats : CborDocumentStats
report : AppPolicyReport
} derive(
Debug
)

Result returned by the application ingress helpers.

#
AppIngressKind

pub(all) enum AppIngressKind {
IngressDocument
IngressMessage
IngressBatch
IngressFrames
} derive(Eq,
Debug
)

Identifies the ingress representation that was accepted.

#
AppMessage

pub(all) struct AppMessage {
version : Int
kind : AppMessageKind
id : String
correlation_id : String?
headers : Array[(String, String)]
payload : CborValue
} derive(Eq,
Debug
)

A versioned message envelope suitable for RPC, events, and queue records.

#
AppMessage::new

fn AppMessage::new(version~ : Int, kind~ : AppMessageKind, id~ : String, payload~ : CborValue) -> AppMessage

Create a message with no correlation ID or headers.

#
AppMessageBatch

pub(all) struct AppMessageBatch {
producer : String
sequence : UInt64
messages : Array[AppMessage]
} derive(Eq,
Debug
)

An ordered group of application messages for queue and log transports.

#
AppMessageKind

pub(all) enum AppMessageKind {
Request
Response
Event
Command
Notification
} derive(Eq,
Debug
)

Application-level message kinds for services built on top of CBOR.

#
AppMessageStore

pub(all) struct AppMessageStore {
records : Array[AppStoreRecord]
dead_letters : Array[AppMessage]
capacity : Int
max_retries : Int
} derive(
Debug
)

A bounded in-memory message store for demos, tests, and embedded workers.

#
AppPolicy

pub(all) struct AppPolicy {
max_bytes : Int
max_nodes : Int
max_depth : Int
max_headers : Int
max_batch_messages : Int
max_frame_bytes : Int
} derive(Eq,
Debug
)

Resource limits applied at an application ingress boundary.

#
AppPolicyIssue

pub(all) struct AppPolicyIssue {
path : String
code : String
message : String
} derive(Eq,
Debug
)

One policy violation suitable for logs or an API response.

#
AppPolicyReport

pub(all) struct AppPolicyReport {
valid : Bool
issues : Array[AppPolicyIssue]
} derive(Eq,
Debug
)

A policy report retains every independent limit violation.

#
AppStoreRecord

pub(all) struct AppStoreRecord {
message : AppMessage
state : AppStoreState
retries : Int
} derive(Eq,
Debug
)

An immutable record containing message lifecycle data.

#
AppStoreState

pub(all) enum AppStoreState {
Pending
Delivered
Acknowledged
DeadLetter
} derive(Eq,
Debug
)

Lifecycle state for an application message held by the local store.

#
AppStoreStats

pub(all) struct AppStoreStats {
total : Int
pending : Int
delivered : Int
acknowledged : Int
dead_letters : Int
retries : Int
} derive(Eq,
Debug
)

Metrics for observing a store without exposing its internal arrays.

#
CborDocumentStats

pub(all) struct CborDocumentStats {
nodes : Int
containers : Int
max_depth : Int
text_bytes : Int
binary_bytes : Int
encoded_bytes : Int
} derive(Eq,
Debug
)

Structural metrics for logging, admission control, and telemetry.

#
CborFrameDecoder

pub(all) struct CborFrameDecoder {
pending : Bytes
max_frame_size : Int
frames_seen : Int
bytes_seen : Int
} derive(
Debug
)

Decoder state for a bounded length-delimited CBOR stream.

#
CborFrameDecoder::new

fn CborFrameDecoder::new(max_frame_size : Int) -> CborFrameDecoder

Create a decoder that rejects frames larger than the configured limit.

#
CborFrameStats

pub(all) struct CborFrameStats {
frames : Int
payload_bytes : Int
wire_bytes : Int
} derive(Eq,
Debug
)

Counters returned by stream consumers and useful for telemetry.

#
CborPatch

A small immutable patch language for configuration and event documents.

#
CborPathSegment

pub(all) enum CborPathSegment {
Key(String)
Index(Int)
} derive(Eq,
Debug
)

A location inside a CBOR document.

#
CborValue

pub(all) enum CborValue {
Unsigned(UInt64)
Integer(Int64)
Bytes(Bytes)
Text(String)
Array(Array[CborValue])
Map(Array[(CborValue, CborValue)])
Tag(UInt64, CborValue)
Simple(Byte)
Float64(Double)
} derive(Eq,
Debug
)

CBOR Data Model as defined in RFC 8949.
impl Show for CborValue

#
ValidationIssue

pub(all) struct ValidationIssue {
path : String
code : String
message : String
} derive(Eq,
Debug
)

One machine-readable issue found during validation.

#
ValidationReport

pub(all) struct ValidationReport {
valid : Bool
issues : Array[ValidationIssue]
} derive(Eq,
Debug
)

A complete validation result; all independent issues are retained.

#
ValidationRule

pub(all) enum ValidationRule {
Required(String)
RequiredText(String)
RequiredBool(String)
RequiredInteger(String)
IntegerRange(String, Int64, Int64)
TextLength(String, Int, Int)
ArrayLength(String, Int, Int)
ObjectFields(String, Array[ValidationRule])
ArrayItems(String, Array[ValidationRule])
OneOfText(String, Array[String])
} derive(Eq,
Debug
)

Validation rules for common CBOR application payloads.

#
app_batch_append

fn app_batch_append(batch : AppMessageBatch, message : AppMessage) -> AppMessageBatch

Return a copy with one message appended.

#
app_batch_correlated_response_count

fn app_batch_correlated_response_count(batch : AppMessageBatch) -> Int

Return the number of request/response pairs represented in a batch.

#
app_batch_encoded_size

fn app_batch_encoded_size(batch : AppMessageBatch) -> Int

Return the encoded size of a batch for transport admission control.

#
app_batch_filter_kind

fn app_batch_filter_kind(batch : AppMessageBatch, kind : AppMessageKind) -> AppMessageBatch

Select messages of one kind while preserving their order.

#
app_batch_find

fn app_batch_find(batch : AppMessageBatch, id : String) -> AppMessage?

Find a message in a batch by its stable ID.

#
app_batch_first

fn app_batch_first(batch : AppMessageBatch) -> AppMessage?

Return the first message in a batch, if any.

#
app_batch_fits_policy

fn app_batch_fits_policy(batch : AppMessageBatch, policy : AppPolicy) -> Bool

Return whether a batch can be framed under the policy.

#
app_batch_from_cbor

fn app_batch_from_cbor(value : CborValue) -> AppMessageBatch raise CborError

Decode and validate a batch from a CBOR value.

#
app_batch_has_unique_ids

fn app_batch_has_unique_ids(batch : AppMessageBatch) -> Bool

Return true when all message IDs in the batch are unique.

#
app_batch_ids

fn app_batch_ids(batch : AppMessageBatch) -> Array[String]

Return all message IDs for audit and deduplication.

#
app_batch_is_empty

fn app_batch_is_empty(batch : AppMessageBatch) -> Bool

Return whether a batch contains no messages.

#
app_batch_kind_count

fn app_batch_kind_count(batch : AppMessageBatch, kind : AppMessageKind) -> Int

Count messages of one lifecycle kind.

#
app_batch_kind_summary

fn app_batch_kind_summary(batch : AppMessageBatch) -> String

Return a deterministic kind histogram for operational dashboards.

#
app_batch_last

fn app_batch_last(batch : AppMessageBatch) -> AppMessage?

Return the last message in a batch, if any.

#
app_batch_new

fn app_batch_new(producer~ : String, sequence~ : UInt64, messages~ : Array[AppMessage]) -> AppMessageBatch

Construct a batch with producer and monotonically increasing sequence metadata.

#
app_batch_next_sequence

fn app_batch_next_sequence(batch : AppMessageBatch) -> UInt64

Return the next sequence number for a producer.

#
app_batch_payload_bytes

fn app_batch_payload_bytes(batch : AppMessageBatch) -> Int

Return the total encoded payload bytes without envelope overhead.

#
app_batch_payload_nodes

fn app_batch_payload_nodes(batch : AppMessageBatch) -> Int

Count all CBOR nodes carried by batch payloads.

#
app_batch_payloads_within_budget

fn app_batch_payloads_within_budget(batch : AppMessageBatch, max_nodes : Int) -> Bool

Return true when every payload remains under a node budget.

#
app_batch_responses_for

fn app_batch_responses_for(batch : AppMessageBatch, request_id : String) -> Array[AppMessage]

Return all response messages correlated to a request ID.

#
app_batch_summary

fn app_batch_summary(batch : AppMessageBatch) -> String

Return a compact audit summary for a batch.

#
app_batch_to_cbor

fn app_batch_to_cbor(batch : AppMessageBatch) -> CborValue

Encode a batch using an explicit versioned map representation.

#
app_event

fn app_event(id : String, topic : String, payload : CborValue) -> AppMessage

Build an event message with a topic header.

#
app_ingest_add_business_issue

fn app_ingest_add_business_issue(result : AppIngestResult, path : String, code : String, message : String) -> AppIngestResult

Reject a report with a caller-provided business rule.

#
app_ingest_is_valid

fn app_ingest_is_valid(result : AppIngestResult) -> Bool

A single status predicate for adapters that should reject invalid ingress.

#
app_ingest_issue_codes

fn app_ingest_issue_codes(result : AppIngestResult) -> Array[String]

Return all policy issue codes in stable order.

#
app_ingest_primary_issue

fn app_ingest_primary_issue(result : AppIngestResult) -> String?

Return the first issue code for a stable caller-facing rejection reason.

#
app_ingest_summary

fn app_ingest_summary(result : AppIngestResult) -> String

Return a compact summary of an ingress result for metrics.

#
app_ingest_values_encoded_bytes

fn app_ingest_values_encoded_bytes(result : AppIngestResult) -> Int

Return the exact re-encoded size of values retained by an ingress result.

#
app_ingest_values_nodes

fn app_ingest_values_nodes(result : AppIngestResult) -> Int

Return the aggregate node count recorded in an ingress result.

#
app_message_from_cbor

fn app_message_from_cbor(value : CborValue) -> AppMessage raise CborError

Decode and validate an application message envelope.

#
app_message_header

fn app_message_header(message : AppMessage, name : String) -> String?

Find the first header with a given name.

#
app_message_summary

fn app_message_summary(message : AppMessage) -> String

Return a compact application-message summary for logs.

#
app_message_to_cbor

fn app_message_to_cbor(message : AppMessage) -> CborValue

Convert an application message into its stable CBOR representation.

#
app_message_with_correlation

fn app_message_with_correlation(message : AppMessage, correlation_id : String) -> AppMessage

Return a copy with a correlation ID used to link a response to a request.

#
app_message_with_header

fn app_message_with_header(message : AppMessage, name : String, value : String) -> AppMessage

Return a copy with one application header appended.

#
app_message_with_payload

fn app_message_with_payload(message : AppMessage, payload : CborValue) -> AppMessage

Copy a message while replacing its payload.

#
app_messages_are_correlated

fn app_messages_are_correlated(request : AppMessage, response : AppMessage) -> Bool

Return true when two messages can be paired as request and response.

#
app_policy_budget_summary

fn app_policy_budget_summary(values : Array[CborValue], policy : AppPolicy) -> String

Produce a compact budget snapshot for logs and telemetry.

#
app_policy_collection_fits_transport

fn app_policy_collection_fits_transport(values : Array[CborValue], policy : AppPolicy) -> Bool

Check the encoded collection against both storage and transport budgets.

#
app_policy_combine

fn app_policy_combine(first : AppPolicyReport, second : AppPolicyReport) -> AppPolicyReport

Combine policy reports from multiple documents.

#
app_policy_default

fn app_policy_default() -> AppPolicy

A practical default policy for service and edge workloads.

#
app_policy_is_sane

fn app_policy_is_sane(policy : AppPolicy) -> Bool

Validate that a policy is internally coherent before accepting config.

#
app_policy_is_stricter_or_equal

fn app_policy_is_stricter_or_equal(policy : AppPolicy, other : AppPolicy) -> Bool

Check whether a policy has no looser resource limit than another policy.

#
app_policy_issue_to_string

fn app_policy_issue_to_string(issue : AppPolicyIssue) -> String

Render one policy issue in a stable log-friendly form.

#
app_policy_many_within_budget

fn app_policy_many_within_budget(values : Array[CborValue], policy : AppPolicy) -> Bool

Check aggregate byte and node budgets without losing per-document errors.

#
app_policy_prefix

fn app_policy_prefix(prefix : String, report : AppPolicyReport) -> AppPolicyReport

Prefix issues when a payload is embedded in a larger protocol object.

#
app_policy_report_code_count

fn app_policy_report_code_count(report : AppPolicyReport, code : String) -> Int

Count occurrences of a policy code for dashboards and alert grouping.

#
app_policy_report_has_code

fn app_policy_report_has_code(report : AppPolicyReport, code : String) -> Bool

Test whether a report contains a particular admission failure class.

#
app_policy_report_to_string

fn app_policy_report_to_string(report : AppPolicyReport) -> String

Render all policy issues in insertion order.

#
app_policy_strict

fn app_policy_strict() -> AppPolicy

A smaller policy useful for untrusted public endpoints.

#
app_policy_summary

fn app_policy_summary(policy : AppPolicy) -> String

Return a policy line for startup logs and configuration audits.

#
app_policy_transport_limit

fn app_policy_transport_limit(policy : AppPolicy) -> Int

Return the configured maximum transport size.

#
app_policy_with_limits

fn app_policy_with_limits(base : AppPolicy, max_bytes : Int, max_nodes : Int, max_depth : Int, max_headers : Int, max_batch_messages : Int, max_frame_bytes : Int) -> AppPolicy

Build a policy with explicit limits for deterministic tests and deployments.

#
app_request

fn app_request(id : String, operation : String, payload : CborValue) -> AppMessage

Build a request message with an operation header.

#
app_response

fn app_response(id : String, correlation_id : String, payload : CborValue) -> AppMessage

Build a response correlated to a request.

#
app_store_ack

fn app_store_ack(store : AppMessageStore, id : String) -> AppMessageStore

Mark a message as successfully processed.

#
app_store_append

fn app_store_append(store : AppMessageStore, message : AppMessage) -> (AppMessageStore, Bool)

Insert a message; the Boolean is false for duplicate IDs or a full store.

#
app_store_append_batch

fn app_store_append_batch(store : AppMessageStore, messages : Array[AppMessage]) -> (AppMessageStore, Int)

Insert messages in order and return the accepted count.

#
app_store_available_capacity

fn app_store_available_capacity(store : AppMessageStore) -> Int

Return the number of available capacity slots.

#
app_store_contains

fn app_store_contains(store : AppMessageStore, id : String) -> Bool

Return true when an ID is already known to the store.

#
app_store_dead_letters

fn app_store_dead_letters(store : AppMessageStore) -> Array[AppMessage]

Return the stored dead-letter messages.

#
app_store_drain_dead_letters

fn app_store_drain_dead_letters(store : AppMessageStore) -> (AppMessageStore, Array[AppMessage])

Drain dead letters and return the cleared store plus the drained messages.

#
app_store_get

fn app_store_get(store : AppMessageStore, id : String) -> AppMessage?

Find a message by ID, including messages awaiting acknowledgement.

#
app_store_ids

fn app_store_ids(store : AppMessageStore) -> Array[String]

Return all message IDs in insertion order.

#
app_store_is_acknowledged

fn app_store_is_acknowledged(store : AppMessageStore, id : String) -> Bool

Return whether a message has reached a terminal success state.

#
app_store_mark_delivered

fn app_store_mark_delivered(store : AppMessageStore, id : String) -> AppMessageStore

Mark a message as delivered to a worker.

#
app_store_new

fn app_store_new(capacity : Int, max_retries : Int) -> AppMessageStore

Create an empty bounded store.

#
app_store_next_pending

fn app_store_next_pending(store : AppMessageStore) -> AppMessage?

Return the next pending message in insertion order.

#
app_store_pending

fn app_store_pending(store : AppMessageStore) -> Array[AppStoreRecord]

Return all records that are ready for delivery.

#
app_store_record

fn app_store_record(store : AppMessageStore, id : String) -> AppStoreRecord?

Return a record with lifecycle metadata.

#
app_store_record_retry

fn app_store_record_retry(store : AppMessageStore, id : String) -> AppMessageStore

Record a retry; messages over the retry budget move to the dead-letter list.

#
app_store_remove_acknowledged

fn app_store_remove_acknowledged(store : AppMessageStore) -> AppMessageStore

Remove a record after acknowledgement and preserve all other records.

#
app_store_resize

fn app_store_resize(store : AppMessageStore, capacity : Int) -> AppMessageStore

Change the capacity only when it can hold the current records.

#
app_store_retry_count

fn app_store_retry_count(store : AppMessageStore, id : String) -> Int

Return the retry count for a message, or zero when it is unknown.

#
app_store_set_retry_budget

fn app_store_set_retry_budget(store : AppMessageStore, max_retries : Int) -> AppMessageStore

Return a copy with a new retry budget for future failures.

#
app_store_stats

fn app_store_stats(store : AppMessageStore) -> AppStoreStats

Calculate lifecycle counters for dashboards and tests.

#
app_store_summary

fn app_store_summary(store : AppMessageStore) -> String

Create a compact audit string for operational logs.

#
append_cbor_frame

fn append_cbor_frame(buffer :
Buffer
, value : CborValue, max_frame_size : Int) -> Unit raise CborError

Encode frames incrementally into a caller-owned buffer.

#
append_frame_with_stats

fn append_frame_with_stats(buffer :
Buffer
, value : CborValue, max_frame_size : Int, stats : CborFrameStats) -> CborFrameStats raise CborError

Add a frame to a buffer and return the resulting statistics.

#
cbor_apply_patch_with_label

fn cbor_apply_patch_with_label(value : CborValue, patch : CborPatch) -> (String, CborValue) raise CborError

Apply exactly one patch and return its operation label with the result.

#
cbor_apply_patches

fn cbor_apply_patches(value : CborValue, patches : Array[CborPatch]) -> CborValue raise CborError

Apply patches in order, returning a new document.

#
cbor_apply_patches_bounded

fn cbor_apply_patches_bounded(value : CborValue, patches : Array[CborPatch], max_nodes : Int) -> CborValue raise CborError

Apply a batch and reject documents that exceed a node budget.

#
cbor_clear_object

fn cbor_clear_object(value : CborValue) -> Array[CborPatch] raise CborError

Return a patch list that removes every top-level key in an object.

#
cbor_diff_objects

fn cbor_diff_objects(before : CborValue, after : CborValue) -> Array[CborPatch] raise CborError

Construct patches for changed or newly added top-level object fields.

#
cbor_document_binary_count

fn cbor_document_binary_count(value : CborValue) -> Int

Return the number of byte-string payloads in a document.

#
cbor_document_contains_text

fn cbor_document_contains_text(value : CborValue, target : String) -> Bool

Search both object keys and values for an exact text value.

#
cbor_document_encoded_size

fn cbor_document_encoded_size(value : CborValue) -> Int

Return the encoded byte size of a document.

#
cbor_document_field_count

fn cbor_document_field_count(value : CborValue) -> Int

Return the number of map entries, including nested objects.

#
cbor_document_largest_binary

fn cbor_document_largest_binary(value : CborValue) -> Int

Return the largest byte-string payload length in a document.

#
cbor_document_leaf_paths

fn cbor_document_leaf_paths(value : CborValue, max_depth : Int) -> Array[String]

Collect leaf paths for audit logs without exposing leaf contents.

#
cbor_document_numeric_count

fn cbor_document_numeric_count(value : CborValue) -> Int

Count numeric leaves, including integer and floating-point values.

#
cbor_document_stats

fn cbor_document_stats(value : CborValue) -> CborDocumentStats

Compute node, container, depth, payload, and encoded-size metrics.

#
cbor_document_summary

fn cbor_document_summary(value : CborValue) -> String

Create a stable summary for an observability event.

#
cbor_document_tag_count

fn cbor_document_tag_count(value : CborValue) -> Int

Count tagged values to support application-specific extension audits.

#
cbor_document_text_count

fn cbor_document_text_count(value : CborValue) -> Int

Return the number of text values in a document.

#
cbor_document_within_budget

fn cbor_document_within_budget(value : CborValue, max_nodes : Int, max_encoded_bytes : Int, max_depth : Int) -> Bool

Return true when the document fits both structural budgets.

#
cbor_frame_decoder_feed

fn cbor_frame_decoder_feed(decoder : CborFrameDecoder, chunk : Bytes) -> (CborFrameDecoder, Array[CborValue]) raise CborError

Feed a chunk and return all complete values plus the updated decoder.

#
cbor_frame_decoder_finish

fn cbor_frame_decoder_finish(decoder : CborFrameDecoder) -> Unit raise CborError

Signal end-of-input and reject an incomplete frame header or payload.

#
cbor_frame_decoder_frames

fn cbor_frame_decoder_frames(decoder : CborFrameDecoder) -> Int

Return the number of complete frames emitted by a decoder.

#
cbor_frame_decoder_limit

fn cbor_frame_decoder_limit(decoder : CborFrameDecoder) -> Int

Return the maximum payload accepted by a decoder.

#
cbor_frame_decoder_pending_bytes

fn cbor_frame_decoder_pending_bytes(decoder : CborFrameDecoder) -> Int

Return the number of bytes currently buffered but not yet decoded.

#
cbor_frame_decoder_stats

fn cbor_frame_decoder_stats(decoder : CborFrameDecoder) -> CborFrameStats

Decode frames while retaining a stable stream statistics snapshot.

#
cbor_frame_wire_size

fn cbor_frame_wire_size(value : CborValue) -> Int

Return the wire size of a frame for admission control.

#
cbor_ingest_batch

fn cbor_ingest_batch(bytes : Bytes, policy : AppPolicy) -> AppIngestResult raise CborError

Decode and policy-check one ordered application batch.

#
cbor_ingest_document

fn cbor_ingest_document(bytes : Bytes, policy : AppPolicy) -> AppIngestResult raise CborError

Decode and policy-check a raw CBOR document at an application boundary.

#
cbor_ingest_frames

fn cbor_ingest_frames(bytes : Bytes, policy : AppPolicy) -> AppIngestResult raise CborError

Decode and policy-check every value in a length-delimited frame stream.

#
cbor_ingest_message

fn cbor_ingest_message(bytes : Bytes, policy : AppPolicy) -> AppIngestResult raise CborError

Decode and policy-check one versioned application message.

#
cbor_message_policy_accepts

fn cbor_message_policy_accepts(message : AppMessage, policy : AppPolicy) -> Bool

Validate a message payload together with its application headers.

#
cbor_object_get

fn cbor_object_get(value : CborValue, key : String) -> CborValue?

Read a top-level object field without constructing a path.

#
cbor_object_has

fn cbor_object_has(value : CborValue, key : String) -> Bool

Return whether an object contains a text key.

#
cbor_object_keys

fn cbor_object_keys(value : CborValue) -> Array[String]

Return all text keys in insertion order.

#
cbor_object_merge

fn cbor_object_merge(base : CborValue, overlay : CborValue) -> CborValue raise CborError

Merge two objects; fields from overlay replace fields from base.

#
cbor_object_project

fn cbor_object_project(value : CborValue, keys : Array[String]) -> CborValue raise CborError

Project an object onto a list of keys, preserving the requested order.

#
cbor_object_remove

fn cbor_object_remove(value : CborValue, key : String) -> CborValue raise CborError

Return a copy of an object with a field removed.

#
cbor_object_set

fn cbor_object_set(value : CborValue, key : String, replacement : CborValue) -> CborValue raise CborError

Return a copy of an object with a text field inserted or replaced.

#
cbor_partition_frames

fn cbor_partition_frames(values : Array[CborValue], max_wire_bytes : Int, max_frame_size : Int) -> Array[Array[CborValue]] raise CborError

Split a batch into transport-sized frame batches without losing order.

#
cbor_patch_audit_line

fn cbor_patch_audit_line(patches : Array[CborPatch]) -> String

Return a deterministic audit line for a patch batch.

#
cbor_patch_is_noop

fn cbor_patch_is_noop(value : CborValue, patch : CborPatch) -> Bool raise CborError

Return true when applying a patch does not change the encoded document.

#
cbor_patch_merge

fn cbor_patch_merge(path : Array[CborPathSegment], value : CborValue) -> CborPatch

Create an object merge patch.

#
cbor_patch_operation

fn cbor_patch_operation(patch : CborPatch) -> String

Return a short operation name for metrics and audit logs.

#
cbor_patch_path

fn cbor_patch_path(patch : CborPatch) -> Array[CborPathSegment]

Return the path targeted by a patch.

#
cbor_patch_remove

fn cbor_patch_remove(path : Array[CborPathSegment]) -> CborPatch

Create a removal patch.

#
cbor_patch_set

fn cbor_patch_set(path : Array[CborPathSegment], value : CborValue) -> CborPatch

Create a replacement patch.

#
cbor_path_segment_to_string

fn cbor_path_segment_to_string(segment : CborPathSegment) -> String

Return a readable path fragment for diagnostics and logs.

#
cbor_path_to_string

fn cbor_path_to_string(path : Array[CborPathSegment]) -> String

Format a path without introducing a dependency on a JSON pointer package.

#
cbor_policy_accepts

fn cbor_policy_accepts(value : CborValue, policy : AppPolicy) -> Bool

Return true when a raw document passes the configured policy.

#
cbor_policy_check

fn cbor_policy_check(value : CborValue, policy : AppPolicy) -> AppPolicyReport

Check structural resource limits for one CBOR document.

#
cbor_policy_check_many

fn cbor_policy_check_many(values : Array[CborValue], policy : AppPolicy) -> AppPolicyReport

Check every document in an ordered collection and retain indexed paths.

#
cbor_policy_many_encoded_bytes

fn cbor_policy_many_encoded_bytes(values : Array[CborValue]) -> Int

Measure the exact encoded footprint of a collection.

#
cbor_policy_many_nodes

fn cbor_policy_many_nodes(values : Array[CborValue]) -> Int

Count nodes across a collection for admission control and metrics.

#
cbor_query_at

fn cbor_query_at(value : CborValue, path : Array[CborPathSegment]) -> CborValue raise CborError

Resolve a path one segment at a time and return the selected value.

#
cbor_query_bool

fn cbor_query_bool(value : CborValue, path : Array[CborPathSegment]) -> Bool raise CborError

Read a boolean field at a nested path.

#
cbor_query_bytes

fn cbor_query_bytes(value : CborValue, path : Array[CborPathSegment]) -> Bytes raise CborError

Read a byte string field at a nested path.

#
cbor_query_double

fn cbor_query_double(value : CborValue, path : Array[CborPathSegment]) -> Double raise CborError

Read a floating-point field, accepting integer CBOR numbers as well.

#
cbor_query_int64

fn cbor_query_int64(value : CborValue, path : Array[CborPathSegment]) -> Int64 raise CborError

Read an integer field at a nested path without narrowing unsafely.

#
cbor_query_optional

fn cbor_query_optional(value : CborValue, path : Array[CborPathSegment]) -> CborValue? raise CborError

Resolve a path, returning None only when a field is absent.

#
cbor_query_preview

fn cbor_query_preview(value : CborValue, max_chars : Int) -> String

Convert a value to a compact log-safe diagnostic with a length limit.

#
cbor_query_text

fn cbor_query_text(value : CborValue, path : Array[CborPathSegment]) -> String raise CborError

Read a text field at a nested path.

#
cbor_query_uint64

fn cbor_query_uint64(value : CborValue, path : Array[CborPathSegment]) -> UInt64 raise CborError

Read a full-width unsigned integer field.

#
cbor_redact_fields

fn cbor_redact_fields(value : CborValue, fields : Array[String], replacement : CborValue) -> CborValue

Recursively replace values whose object key is in a sensitive-field list.

#
cbor_redacted_preview

fn cbor_redacted_preview(value : CborValue, fields : Array[String], max_chars : Int) -> String

Return a redacted preview bounded by a character budget.

#
cbor_set_path

fn cbor_set_path(value : CborValue, path : Array[CborPathSegment], replacement : CborValue) -> CborValue raise CborError

Replace a nested path while preserving all untouched values.

#
cbor_value_depth

fn cbor_value_depth(value : CborValue) -> Int

Return the maximum nesting depth of a document.

#
cbor_value_fits_frame

fn cbor_value_fits_frame(value : CborValue, max_frame_size : Int) -> Bool

Return whether a value can be emitted under a frame limit.

#
cbor_value_node_count

fn cbor_value_node_count(value : CborValue) -> Int

Count descendants in a document for lightweight telemetry.

#
count_cbor_frames

fn count_cbor_frames(bytes : Bytes, max_frame_size : Int) -> Int raise CborError

Count complete frames in a wire buffer without decoding payloads.

#
decode

fn decode(bytes : Bytes) -> CborValue raise CborError

Decode a CBOR value from a byte array.

#
decode_app_batch

fn decode_app_batch(bytes : Bytes) -> AppMessageBatch raise CborError

Decode a complete application message batch.

#
decode_app_message

fn decode_app_message(bytes : Bytes) -> AppMessage raise CborError

Decode a complete application message.

#
decode_as

fn[T : CborDecode] decode_as(bytes : Bytes) -> T raise CborError

Decode a complete CBOR payload into a target type via CborDecode.

#
decode_cbor_frames

fn decode_cbor_frames(bytes : Bytes, max_frame_size : Int) -> Array[CborValue] raise CborError

Decode a complete transport buffer.

#
decode_from_offset

fn decode_from_offset(bytes : Bytes, offset : Array[Int]) -> CborValue raise CborError

Decode a CBOR value from a byte array starting at the given offset.

#
diagnostic

fn diagnostic(value : CborValue) -> String

Convert a CborValue to CBOR Diagnostic Notation (RFC 8949 Section 8)

#
encode

fn encode(value : CborValue) -> Bytes

Encode a CBOR value to a byte array.

#
encode_app_batch

fn encode_app_batch(batch : AppMessageBatch) -> Bytes raise CborError

Encode a complete application message batch.

#
encode_app_message

fn encode_app_message(message : AppMessage) -> Bytes raise CborError

Encode a validated application message.

#
encode_cbor_frame

fn encode_cbor_frame(value : CborValue, max_frame_size : Int) -> Bytes raise CborError

Encode one CBOR value as a length-delimited frame.

#
encode_cbor_frames

fn encode_cbor_frames(values : Array[CborValue], max_frame_size : Int) -> Bytes raise CborError

Encode a batch of values into a single transport buffer.

#
encode_to_buffer

fn encode_to_buffer(value : CborValue, buf :
Buffer
) -> Unit

Encode a CBOR value into a mutable Buffer.

#
inspect_cbor_frames

fn inspect_cbor_frames(bytes : Bytes, max_frame_size : Int) -> CborFrameStats raise CborError

Calculate transport statistics from a complete frame stream.

#
validate_app_batch

fn validate_app_batch(batch : AppMessageBatch) -> Unit raise CborError

Validate batch metadata and every contained envelope.

#
validate_app_batch_for_transport

fn validate_app_batch_for_transport(batch : AppMessageBatch, max_encoded_bytes : Int) -> Unit raise CborError

Validate an upper bound and ID uniqueness in one operation.

#
validate_app_message

fn validate_app_message(message : AppMessage) -> Unit raise CborError

Validate message invariants without encoding the payload.

#
validate_message_payload

fn validate_message_payload(message : AppMessage, rules : Array[ValidationRule]) -> ValidationReport

Validate a message payload and prefix its errors with the message ID.

#
validate_object_payload

fn validate_object_payload(value : CborValue, rules : Array[ValidationRule]) -> ValidationReport

Validate an object and retain every independent field issue.

#
validation_array_length

fn validation_array_length(name : String, minimum : Int, maximum : Int) -> ValidationRule

Construct an inclusive array length rule.

#
validation_business_error

fn validation_business_error(path : String, code : String, message : String) -> ValidationReport

Return a report containing one explicit business-rule error.

#
validation_combine

fn validation_combine(first : ValidationReport, second : ValidationReport) -> ValidationReport

Compose two reports without losing issue order.

#
validation_error_count

fn validation_error_count(report : ValidationReport) -> Int

Return the number of errors in a validation report.

#
validation_int_range

fn validation_int_range(name : String, minimum : Int64, maximum : Int64) -> ValidationRule

Construct an inclusive integer range rule.

#
validation_issue_to_string

fn validation_issue_to_string(issue : ValidationIssue) -> String

Return a stable single-line representation for log aggregation.

#
validation_items

fn validation_items(name : String, rules : Array[ValidationRule]) -> ValidationRule

Construct a rule applied to every item in an array.

#
validation_object

fn validation_object(name : String, rules : Array[ValidationRule]) -> ValidationRule

Construct a nested object rule.

#
validation_one_of

fn validation_one_of(name : String, allowed : Array[String]) -> ValidationRule

Construct a finite text enumeration rule.

#
validation_prefix

fn validation_prefix(prefix : String, report : ValidationReport) -> ValidationReport

Add a path prefix to every issue in a report.

#
validation_report_to_string

fn validation_report_to_string(report : ValidationReport) -> String

Render all issues in deterministic order.

#
validation_required

fn validation_required(name : String) -> ValidationRule

Construct a required-field rule.

#
validation_required_bool

fn validation_required_bool(name : String) -> ValidationRule

Construct a required boolean rule.

#
validation_required_integer

fn validation_required_integer(name : String) -> ValidationRule

Construct a required integer rule.

#
validation_required_text

fn validation_required_text(name : String) -> ValidationRule

Construct a required non-empty text rule.

#
validation_succeeds

fn validation_succeeds(value : CborValue, rules : Array[ValidationRule]) -> Bool

Return true when a value passes a set of object rules.

#
validation_text_length

fn validation_text_length(name : String, minimum : Int, maximum : Int) -> ValidationRule

Construct an inclusive UTF-16 string length rule.

#
validation_unknown_fields

fn validation_unknown_fields(value : CborValue, allowed : Array[String]) -> ValidationReport

Reject unknown text fields when an application has a closed schema.