encoding

package
v1.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2026 License: MIT Imports: 7 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

This section is empty.

Variables

View Source
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")
)
View Source
var ErrDepthExceeded = errors.New("encoding: nested Any exceeds maximum depth")

ErrDepthExceeded is returned when a nested Any value exceeds maxAnyDepth levels.

View Source
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

This section is empty.

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

func NewDecoder(b []byte) *Decoder

NewDecoder returns a Decoder that reads from b.

func (*Decoder) HasContent

func (d *Decoder) HasContent() bool

HasContent reports whether there are unread bytes remaining.

func (*Decoder) ReadAny

func (d *Decoder) ReadAny() (any, error)

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

func (d *Decoder) ReadBigInt64() (int64, error)

ReadBigInt64 reads a signed 64-bit big-endian integer.

func (*Decoder) ReadFloat32

func (d *Decoder) ReadFloat32() (float32, error)

ReadFloat32 reads a 32-bit big-endian IEEE 754 float.

func (*Decoder) ReadFloat64

func (d *Decoder) ReadFloat64() (float64, error)

ReadFloat64 reads a 64-bit big-endian IEEE 754 float.

func (*Decoder) ReadUint8

func (d *Decoder) ReadUint8() (uint8, error)

ReadUint8 reads a single byte.

func (*Decoder) ReadVarBytes

func (d *Decoder) ReadVarBytes() ([]byte, error)

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. Returns ErrOverflow if the declared length exceeds maxStringBytes (16 MiB) to prevent OOM from a crafted 4 GB length prefix.

func (*Decoder) ReadVarInt

func (d *Decoder) ReadVarInt() (int64, error)

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

func (d *Decoder) ReadVarString() (string, error)

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

func (d *Decoder) ReadVarUint() (uint64, error)

ReadVarUint decodes a variable-length unsigned integer. Returns ErrOverflow if the value exceeds 53 significant bits.

func (*Decoder) Remaining

func (d *Decoder) Remaining() int

Remaining returns the number of unread bytes.

func (*Decoder) RemainingBytes

func (d *Decoder) RemainingBytes() []byte

RemainingBytes returns a copy of the unread portion of the 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 NewEncoder

func NewEncoder() *Encoder

NewEncoder returns a new Encoder with a small pre-allocated buffer.

func (*Encoder) Bytes

func (e *Encoder) Bytes() []byte

Bytes returns the encoded bytes accumulated so far.

func (*Encoder) Reset

func (e *Encoder) Reset()

Reset clears the buffer so the Encoder can be reused.

func (*Encoder) WriteAny

func (e *Encoder) WriteAny(v any)

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

func (e *Encoder) WriteBigInt64(v int64)

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

func (*Encoder) WriteFloat32

func (e *Encoder) WriteFloat32(v float32)

WriteFloat32 writes a 32-bit IEEE 754 float in big-endian byte order.

func (*Encoder) WriteFloat64

func (e *Encoder) WriteFloat64(v float64)

WriteFloat64 writes a 64-bit IEEE 754 float in big-endian byte order.

func (*Encoder) WriteRaw

func (e *Encoder) WriteRaw(b []byte)

WriteRaw appends raw bytes to the encoder buffer without any length prefix.

func (*Encoder) WriteUint8

func (e *Encoder) WriteUint8(v uint8)

WriteUint8 writes a single byte.

func (*Encoder) WriteVarBytes

func (e *Encoder) WriteVarBytes(b []byte)

WriteVarBytes encodes b as VarUint(len) followed by raw bytes.

func (*Encoder) WriteVarInt

func (e *Encoder) WriteVarInt(v int64)

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

func (e *Encoder) WriteVarIntE(v int64) error

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

func (e *Encoder) WriteVarString(s string)

WriteVarString encodes s as VarUint(byteLength) followed by raw UTF-8 bytes.

func (*Encoder) WriteVarUint

func (e *Encoder) WriteVarUint(v uint64)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL