Documentation
¶
Overview ¶
Package encoding implements the lib0 binary encoding format used by Yjs.
This is a variable-length binary codec with no external dependencies. It is the foundation for all wire-format serialisation in ygo.
Reference: https://github.com/dmonad/lib0
Index ¶
- Variables
- func EncodeBytes(fn func(*Encoder)) (out []byte)
- func PutEncoder(e *Encoder)
- type BigInt
- type Decoder
- func (d *Decoder) HasContent() bool
- func (d *Decoder) ReadAny() (any, error)
- func (d *Decoder) ReadBigInt64() (int64, error)
- func (d *Decoder) ReadFloat32() (float32, error)
- func (d *Decoder) ReadFloat64() (float64, error)
- func (d *Decoder) ReadUint8() (uint8, error)
- func (d *Decoder) ReadVarBytes() ([]byte, error)
- func (d *Decoder) ReadVarInt() (int64, error)
- func (d *Decoder) ReadVarString() (string, error)
- func (d *Decoder) ReadVarUint() (uint64, error)
- func (d *Decoder) Remaining() int
- func (d *Decoder) RemainingBytes() []byte
- func (d *Decoder) RemainingBytesCopy() []byte
- type Encoder
- func (e *Encoder) Bytes() []byte
- func (e *Encoder) Reset()
- func (e *Encoder) WriteAny(v any)
- func (e *Encoder) WriteBigInt64(v int64)
- func (e *Encoder) WriteFloat32(v float32)
- func (e *Encoder) WriteFloat64(v float64)
- func (e *Encoder) WriteRaw(b []byte)
- func (e *Encoder) WriteUint8(v uint8)
- func (e *Encoder) WriteVarBytes(b []byte)
- func (e *Encoder) WriteVarInt(v int64)
- func (e *Encoder) WriteVarIntE(v int64) error
- func (e *Encoder) WriteVarString(s string)
- func (e *Encoder) WriteVarUint(v uint64)
- type IntDiffOptRleDecoder
- type IntDiffOptRleEncoder
- type RleByteDecoder
- type RleByteEncoder
- type StringDecoder
- type StringEncoder
- type UintOptRleDecoder
- type UintOptRleEncoder
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnexpectedEOF is returned when the buffer is exhausted before decoding completes. ErrUnexpectedEOF = errors.New("encoding: unexpected end of input") // ErrOverflow is returned when a VarUint exceeds the 53-bit safe integer range. // This matches JavaScript's Number.MAX_SAFE_INTEGER constraint in the Yjs protocol. ErrOverflow = errors.New("encoding: varuint overflow (> 53 bits)") // ErrUnknownTag is returned by ReadAny when the tag byte does not correspond // to a known Any variant. Returning an error (rather than nil, nil) prevents // crafted payloads from silently injecting nil values into the document. ErrUnknownTag = errors.New("encoding: unknown Any tag") // ErrInvalidUTF8 is returned by ReadVarString when the byte sequence is not // valid UTF-8. Matches lib0's TextDecoder('utf-8', { fatal: true }) which // throws on malformed input rather than producing a corrupt string. ErrInvalidUTF8 = errors.New("encoding: invalid UTF-8 in varstring") )
var ErrDepthExceeded = errors.New("encoding: nested Any exceeds maximum depth")
ErrDepthExceeded is returned when a nested Any value exceeds maxAnyDepth levels.
var ErrVarIntOutOfRange = errors.New("encoding: VarInt magnitude exceeds lib0 55-bit range")
ErrVarIntOutOfRange is returned by WriteVarIntE when the magnitude of v exceeds the lib0 VarInt encoding range ((1<<55)-1). The JS Yjs decoder rejects values outside this range, so producing one would be unwire-able.
Functions ¶
func EncodeBytes ¶ added in v1.17.0
EncodeBytes runs fn against a pooled Encoder and returns an independently-allocated copy of the resulting bytes. The encoder is returned to the pool before EncodeBytes returns; the returned slice is safe to retain across goroutines and outlive the call. This is the preferred wrapper for wire-framing call sites that hand bytes to a write channel or other long-lived consumer.
PutEncoder is deferred so a panic from fn still returns the encoder to the pool (GetEncoder calls Reset on the way out, so any partially- written bytes from the panicking call are discarded before the encoder is reused).
func PutEncoder ¶ added in v1.17.0
func PutEncoder(e *Encoder)
PutEncoder returns e to the pool for reuse. Callers must not access e or any slice obtained from e.Bytes() after this call returns.
Types ¶
type BigInt ¶ added in v1.8.0
type BigInt int64
BigInt represents lib0 writeAny tag 122, encoded as a signed 64-bit integer.
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder reads values from a byte slice using the lib0 encoding format. Decoder is not safe for concurrent use; each goroutine should use its own instance.
func NewDecoder ¶
NewDecoder returns a Decoder that reads from b.
func (*Decoder) HasContent ¶
HasContent reports whether there are unread bytes remaining.
func (*Decoder) ReadAny ¶
ReadAny decodes a tagged-union value written by Encoder.WriteAny. Nested arrays and maps are limited to maxAnyDepth levels to prevent stack-overflow DoS from crafted inputs.
func (*Decoder) ReadBigInt64 ¶ added in v1.8.0
ReadBigInt64 reads a signed 64-bit big-endian integer.
func (*Decoder) ReadFloat32 ¶
ReadFloat32 reads a 32-bit big-endian IEEE 754 float.
func (*Decoder) ReadFloat64 ¶
ReadFloat64 reads a 64-bit big-endian IEEE 754 float.
func (*Decoder) ReadVarBytes ¶
ReadVarBytes decodes a length-prefixed byte slice. The returned slice is a sub-slice of the decoder's buffer; copy if you need to retain it.
A field can be no larger than the bytes that remain in the buffer; a declared length beyond that is malformed and returns ErrUnexpectedEOF. Because the returned slice aliases the buffer (no allocation), the buffer length is the real bound — a crafted multi-GiB length prefix is rejected here without any large allocation. Bounding by the remaining buffer rather than a fixed ceiling (previously 16 MiB) lets a single large field — e.g. a big text node or binary embed — sync inside an otherwise-valid message, with the maximum message size policed by the provider layer (MaxMessageBytes, default 64 MiB) instead of being silently rejected here (N-12).
func (*Decoder) ReadVarInt ¶
ReadVarInt decodes a lib0 sign-magnitude variable-length integer. Returns ErrOverflow if the encoded magnitude exceeds 55 bits (the lib0 protocol's maximum).
func (*Decoder) ReadVarString ¶
ReadVarString decodes a length-prefixed UTF-8 string. Invalid UTF-8 byte sequences return ErrInvalidUTF8, matching lib0's TextDecoder fatal:true mode. Without this, malformed input would silently produce a corrupt Go string carrying non-UTF-8 bytes that downstream code may misinterpret.
func (*Decoder) ReadVarUint ¶
ReadVarUint decodes a variable-length unsigned integer. Returns ErrOverflow if the value exceeds 53 significant bits.
func (*Decoder) RemainingBytes ¶
RemainingBytes returns the unread portion of the buffer as a sub-slice.
The returned slice ALIASES the decoder's underlying buffer; mutating it (or extending its length via append beyond cap) corrupts the decoder. Callers must treat it as read-only and copy if they need a slice with an independent lifetime. Most callers in this codebase hand the bytes straight to ApplySyncMessage or json.Unmarshal, both of which read-only, so the zero-copy path is safe.
Use RemainingBytesCopy if you need an independent allocation.
func (*Decoder) RemainingBytesCopy ¶ added in v1.17.0
RemainingBytesCopy returns an independently-allocated copy of the unread portion of the buffer. Use when the caller needs to retain the bytes across mutations of the decoder's underlying buffer.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder writes values into a growing byte buffer using the lib0 encoding format. Encoder is not safe for concurrent use; each goroutine should use its own instance.
func GetEncoder ¶ added in v1.17.0
func GetEncoder() *Encoder
GetEncoder returns a Reset Encoder from the pool. The encoder MUST be returned to the pool via PutEncoder once its bytes are no longer needed. The byte slice returned by the encoder's Bytes() method aliases the pooled buffer and becomes invalid after PutEncoder — copy out anything that needs to outlive the Put.
func NewEncoder ¶
func NewEncoder() *Encoder
NewEncoder returns a new Encoder with a small pre-allocated buffer.
func (*Encoder) Reset ¶
func (e *Encoder) Reset()
Reset clears the buffer so the Encoder can be reused.
func (*Encoder) WriteAny ¶
WriteAny encodes an arbitrary value using lib0's tagged-union format. Supported Go types and their wire tags:
nil -> 126 (null) bool -> 120 (true) / 121 (false) int / int64 -> 125 + VarInt float32 -> 124 + 4 bytes BE float64 -> 123 + 8 bytes BE BigInt -> 122 + 8 bytes BE string -> 119 + VarString []byte -> 116 + VarBytes []any -> 117 + VarUint(len) + elements map[string]any -> 118 + VarUint(len) + key-value pairs
func (*Encoder) WriteBigInt64 ¶ added in v1.8.0
WriteBigInt64 writes a signed 64-bit integer in big-endian byte order.
func (*Encoder) WriteFloat32 ¶
WriteFloat32 writes a 32-bit IEEE 754 float in big-endian byte order.
func (*Encoder) WriteFloat64 ¶
WriteFloat64 writes a 64-bit IEEE 754 float in big-endian byte order.
func (*Encoder) WriteRaw ¶
WriteRaw appends raw bytes to the encoder buffer without any length prefix.
func (*Encoder) WriteVarBytes ¶
WriteVarBytes encodes b as VarUint(len) followed by raw bytes.
func (*Encoder) WriteVarInt ¶
WriteVarInt encodes a signed integer using the lib0 sign-magnitude format, matching the JavaScript lib0 library's writeVarInt.
Panics if the magnitude of v exceeds (1<<55)-1, which is the maximum encodable by the lib0 protocol (the decoder rejects anything larger). Most callers should prefer WriteVarIntE which returns this case as ErrVarIntOutOfRange instead of panicking.
func (*Encoder) WriteVarIntE ¶ added in v1.7.0
WriteVarIntE is the error-returning variant of WriteVarInt. Returns ErrVarIntOutOfRange if the magnitude of v exceeds the lib0 55-bit range. Preferred over WriteVarInt for callers who need to surface out-of-range inputs without a panic — for example, encoding pipelines that wrap user input or untrusted data.
Successful encoding is byte-identical to WriteVarInt(v) for the same v.
func (*Encoder) WriteVarString ¶
WriteVarString encodes s as VarUint(byteLength) followed by raw UTF-8 bytes.
func (*Encoder) WriteVarUint ¶
WriteVarUint encodes v using variable-length encoding: 7 data bits per byte, with the MSB as a continuation flag (1 = more bytes follow, 0 = last byte). Integers up to 2^53 are supported to match JavaScript's safe integer range.
type IntDiffOptRleDecoder ¶
type IntDiffOptRleDecoder struct {
// contains filtered or unexported fields
}
IntDiffOptRleDecoder decodes a stream produced by IntDiffOptRleEncoder.
func NewIntDiffOptRleDecoder ¶
func NewIntDiffOptRleDecoder(data []byte) *IntDiffOptRleDecoder
NewIntDiffOptRleDecoder returns a decoder for data from IntDiffOptRleEncoder.
func (*IntDiffOptRleDecoder) Read ¶
func (d *IntDiffOptRleDecoder) Read() (int64, error)
Read returns the next decoded value.
type IntDiffOptRleEncoder ¶
type IntDiffOptRleEncoder struct {
// contains filtered or unexported fields
}
IntDiffOptRleEncoder encodes signed integers using diff + optional RLE. Encodes the diff between successive values, with a run-length flag in the LSB. encodedDiff = diff*2 + (count==1 ? 0 : 1), written as VarInt. For runs (count > 1), also writes VarUint(count-2).
func (*IntDiffOptRleEncoder) Bytes ¶
func (e *IntDiffOptRleEncoder) Bytes() []byte
Bytes returns the encoded bytes. Call only once after all Write calls.
func (*IntDiffOptRleEncoder) Write ¶
func (e *IntDiffOptRleEncoder) Write(v int64)
Write appends v to the encoded sequence.
type RleByteDecoder ¶
type RleByteDecoder struct {
// contains filtered or unexported fields
}
RleByteDecoder run-length-decodes a byte stream produced by RleByteEncoder.
func NewRleByteDecoder ¶
func NewRleByteDecoder(data []byte) *RleByteDecoder
NewRleByteDecoder returns a decoder for data produced by RleByteEncoder.
func (*RleByteDecoder) Read ¶
func (d *RleByteDecoder) Read() (byte, error)
Read returns the next decoded byte.
type RleByteEncoder ¶
type RleByteEncoder struct {
// contains filtered or unexported fields
}
RleByteEncoder run-length-encodes a sequence of bytes. Format: [value, VarUint(count-1)] pairs. The LAST run's count is omitted (the decoder infers it from the end of stream).
func (*RleByteEncoder) Bytes ¶
func (e *RleByteEncoder) Bytes() []byte
Bytes returns the encoded bytes. Call only once after all Write calls.
func (*RleByteEncoder) Write ¶
func (e *RleByteEncoder) Write(v byte)
Write appends v to the encoded sequence.
type StringDecoder ¶
type StringDecoder struct {
// contains filtered or unexported fields
}
StringDecoder reads strings from a pool encoded by StringEncoder.
func NewStringDecoder ¶
func NewStringDecoder(data []byte) (*StringDecoder, error)
NewStringDecoder returns a decoder for data produced by StringEncoder.
func (*StringDecoder) Read ¶
func (d *StringDecoder) Read() (string, error)
Read returns the next decoded string.
type StringEncoder ¶
type StringEncoder struct {
// contains filtered or unexported fields
}
StringEncoder concatenates strings and encodes their UTF-16 lengths via UintOptRle. Format: VarString(all) + raw UintOptRle bytes (no length prefix).
func (*StringEncoder) Bytes ¶
func (e *StringEncoder) Bytes() []byte
Bytes returns the encoded bytes. Call only once after all Write calls.
func (*StringEncoder) Write ¶
func (e *StringEncoder) Write(s string)
Write appends s to the encoded string pool.
type UintOptRleDecoder ¶
type UintOptRleDecoder struct {
// contains filtered or unexported fields
}
UintOptRleDecoder decodes a stream produced by UintOptRleEncoder.
func NewUintOptRleDecoder ¶
func NewUintOptRleDecoder(data []byte) *UintOptRleDecoder
NewUintOptRleDecoder returns a decoder for data from UintOptRleEncoder.
func (*UintOptRleDecoder) Read ¶
func (d *UintOptRleDecoder) Read() (uint64, error)
Read returns the next decoded value.
type UintOptRleEncoder ¶
type UintOptRleEncoder struct {
// contains filtered or unexported fields
}
UintOptRleEncoder encodes unsigned integers using optional run-length encoding. Singles: VarInt(+v). Runs: VarInt(-v) + VarUint(count-2). Uses sign-magnitude VarInt so that -0 is distinct from +0.
func (*UintOptRleEncoder) Bytes ¶
func (e *UintOptRleEncoder) Bytes() []byte
Bytes returns the encoded bytes. Call only once after all Write calls.
func (*UintOptRleEncoder) Write ¶
func (e *UintOptRleEncoder) Write(v uint64)
Write appends v to the encoded sequence.