wirebson

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2025 License: Apache-2.0 Imports: 19 Imported by: 1

Documentation

Overview

Package wirebson implements encoding and decoding of BSON as defined by https://bsonspec.org/spec.html.

Types

The following BSON types are supported:

BSON                Go                        $type alias

Document/Object     *Document or RawDocument  object
Array               *Array or RawArray        array

Double              float64                   double
String              string                    string
Binary data         Binary                    binData
Undefined           UndefinedType             undefined
ObjectId            ObjectID                  objectId
Boolean             bool                      bool
Date                time.Time                 date
Null                NullType                  null
Regular Expression  Regex                     regex
32-bit integer      int32                     int
Timestamp           Timestamp                 timestamp
64-bit integer      int64                     long
Decimal128          Decimal128                decimal

Composite types (Document and Array) are passed by pointers. Raw composite type and scalars are passed by values.

Index

Constants

View Source
const (
	// BinaryGeneric represents a BSON Binary generic subtype.
	BinaryGeneric = BinarySubtype(0) // generic

	// BinaryFunction represents a BSON Binary function subtype.
	BinaryFunction = BinarySubtype(1) // function

	// BinaryGenericOld represents a BSON Binary generic-old subtype.
	BinaryGenericOld = BinarySubtype(2) // generic-old

	// BinaryUUIDOld represents a BSON Binary UUID old subtype.
	BinaryUUIDOld = BinarySubtype(3) // uuid-old

	// BinaryUUID represents a BSON Binary UUID subtype.
	BinaryUUID = BinarySubtype(4) // uuid

	// BinaryMD5 represents a BSON Binary MD5 subtype.
	BinaryMD5 = BinarySubtype(5) // md5

	// BinaryEncrypted represents a BSON Binary encrypted subtype.
	BinaryEncrypted = BinarySubtype(6) // encrypted

	// BinaryCompressed represents a BSON Binary compressed column subtype.
	BinaryCompressed = BinarySubtype(7) // compressed

	// BinarySensitive represents a BSON Binary sensitive subtype.
	BinarySensitive = BinarySubtype(8) // sensitive

	// BinaryVector represents a BSON Binary vector subtype.
	BinaryVector = BinarySubtype(9) // vector

	// BinaryUser represents a BSON Binary user-defined subtype.
	BinaryUser = BinarySubtype(128) // user
)

Variables

View Source
var (
	// ErrDecodeShortInput is returned wrapped by Decode functions if the input bytes slice is too short.
	ErrDecodeShortInput = errors.New("wirebson: short input")

	// ErrDecodeInvalidInput is returned wrapped by Decode functions if the input bytes slice is invalid.
	ErrDecodeInvalidInput = errors.New("wirebson: invalid input")
)
View Source
var Null = NullType{}

Null represents BSON scalar value null.

View Source
var Undefined = UndefinedType{}

Undefined represents BSON scalar value undefined.

Its usage is deprecated, but it is still used in a few places. See https://github.com/FerretDB/FerretDB/issues/2286 for an example.

Functions

func DecodeCString

func DecodeCString(b []byte) (string, error)

DecodeCString decodes cstring value from b.

If there is not enough bytes, DecodeCString will return a wrapped ErrDecodeShortInput. If the input is otherwise invalid, a wrapped ErrDecodeInvalidInput is returned.

func EncodeCString

func EncodeCString(b []byte, v string)

EncodeCString encodes cstring value v into b.

Slice must be at least len(v)+1 (SizeCString) bytes long; otherwise, EncodeString will panic. Only b[0:len(v)+1] bytes are modified.

func Equal added in v0.0.20

func Equal(v1, v2 any) bool

Equal returns true if two BSON values are equal.

It panics if invalid BSON type or decoding error is encountered. For that reason, it should not be used with user input.

See also the wiretest package for test helpers.

  • Documents and arrays are compared by their length and then by content. They are decoded as needed; raw values are compared directly without decoding.
  • float64 NaNs values are considered equal independently of their payload. Other values are compared by their bits. That handles all other values, including infinities, negative zeros, etc.
  • time.Time values are compared using the Equal method.
  • Regex options are compared ignoring order.

func FindRaw

func FindRaw(b []byte) (int, error)

FindRaw finds the first raw BSON document or array in b and returns its length l. It should start from the first byte of b. RawDocument(b[:l]) / RawArray(b[:l]) might not be valid. It is the caller's responsibility to check it.

Use RawDocument(b) / RawArray(b) conversion instead if b contains exactly one document/array and no extra bytes.

func FromDriver added in v0.0.23

func FromDriver(v any) (any, error)

FromDriver converts MongoDB driver v2 (and, temporary, v1) value (bson.D, bson.A, etc) to wirebson value.

func LogMessage

func LogMessage(v any) string

LogMessage returns a representation of any BSON value as a string, somewhat similar (but not identical) to JSON or Go syntax. It may change over time.

It panics on invalid BSON types.

The result is optimized for large values such as full request documents. All information is preserved.

func LogMessageIndent added in v0.0.10

func LogMessageIndent(v any) string

LogMessageIndent returns an indented representation of any BSON value as a string, somewhat similar (but not identical) to JSON or Go syntax. It may change over time.

It panics on invalid BSON types.

The result is optimized for large values such as full request documents. All information is preserved.

func Size added in v0.0.14

func Size(v any) int

Size returns the size of the encoding of value v in bytes.

It panics for invalid types.

func SizeCString

func SizeCString(v string) int

SizeCString returns the size of the encoding of v cstring in bytes.

func ToDriver added in v0.0.23

func ToDriver(v any) (any, error)

ToDriver converts wirebson value to MongoDB driver v2 value (bson.D, bson.A, etc).

Types

type AnyArray

type AnyArray interface {
	Encode() (RawArray, error)
	Decode() (*Array, error)
	LogMessage() string
	LogMessageIndent() string
	// contains filtered or unexported methods
}

AnyArray represents a BSON array type (both *Array and RawArray).

Note that the Encode and Decode methods could return the receiver itself, so care must be taken when results are modified.

type AnyDocument

type AnyDocument interface {
	Encode() (RawDocument, error)
	Decode() (*Document, error)
	LogMessage() string
	LogMessageIndent() string
	slog.LogValuer
	// contains filtered or unexported methods
}

AnyDocument represents a BSON document type (both *Document and RawDocument).

Note that the Encode and Decode methods could return the receiver itself, so care must be taken when results are modified.

type Array

type Array struct {
	// contains filtered or unexported fields
}

Array represents a BSON array in the (partially) decoded form.

func MakeArray

func MakeArray(cap int) *Array

MakeArray creates a new empty Array with the given capacity.

func MustArray added in v0.0.3

func MustArray(values ...any) *Array

MustArray is a variant of NewArray that panics on error.

func NewArray

func NewArray(values ...any) (*Array, error)

NewArray creates a new Array from the given values.

func (*Array) Add

func (arr *Array) Add(value any) error

Add adds a new value to the end of the Array.

func (*Array) All added in v0.0.8

func (arr *Array) All() iter.Seq2[int, any]

All returns an iterator over index/value pairs of the Array.

func (*Array) Copy added in v0.1.0

func (arr *Array) Copy() *Array

Copy returns a shallow copy of *Array. Only scalar values (including Binary) are copied. *Document, *Array, RawDocument, and RawArray are added without a copy, using the same pointer/slice.

func (*Array) Decode

func (arr *Array) Decode() (*Array, error)

Decode returns itself to implement AnyArray.

Receiver must not be nil.

func (*Array) Encode

func (arr *Array) Encode() (RawArray, error)

Encode encodes non-nil Array.

TODO https://github.com/FerretDB/wire/issues/21 This method should accept a slice of bytes, not return it. That would allow to avoid unnecessary allocations.

func (*Array) Freeze

func (arr *Array) Freeze()

Freeze prevents Array from further modifications. Any methods that would modify the Array will panic.

It is safe to call Freeze multiple times.

func (*Array) Get

func (arr *Array) Get(index int) any

Get returns the value at the given index. It panics if index is out of bounds.

func (*Array) Len

func (arr *Array) Len() int

Len returns the number of values in the Array.

func (*Array) LogMessage added in v0.0.11

func (arr *Array) LogMessage() string

LogMessage implements AnyArray.

func (*Array) LogMessageIndent added in v0.0.11

func (arr *Array) LogMessageIndent() string

LogMessageIndent implements AnyArray.

func (*Array) LogValue

func (arr *Array) LogValue() slog.Value

LogValue implements slog.LogValuer.

func (*Array) MarshalJSON added in v0.0.14

func (arr *Array) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler by encoding Canonical Extended JSON v2 representation of the array.

func (*Array) Replace

func (arr *Array) Replace(index int, value any) error

Replace sets the value of the element at the given index. It panics if index is out of bounds.

func (*Array) SortInterface added in v0.0.9

func (arr *Array) SortInterface(less func(a, b any) bool) sort.Interface

SortInterface returns sort.Interface that can be used to sort Array in place. Passed function should return true is a < b, false otherwise. It should be able to handle values of different types.

func (*Array) UnmarshalJSON added in v0.0.14

func (arr *Array) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler by decoding Canonical Extended JSON v2 representation of the array.

func (*Array) Values added in v0.0.8

func (arr *Array) Values() iter.Seq[any]

Values returns an iterator over values of the Array.

type Binary

type Binary struct {
	B       []byte
	Subtype BinarySubtype
}

Binary represents BSON scalar type binary.

type BinarySubtype

type BinarySubtype byte

BinarySubtype represents BSON Binary's subtype.

func (BinarySubtype) String added in v0.0.8

func (i BinarySubtype) String() string

type CompositeType

type CompositeType interface {
	*Document | *Array | RawDocument | RawArray
}

CompositeType represents a BSON composite type (including raw types).

type Decimal128

type Decimal128 struct {
	H uint64
	L uint64
}

Decimal128 represents BSON scalar type decimal128.

type Document

type Document struct {
	// contains filtered or unexported fields
}

Document represents a BSON document a.k.a object in the (partially) decoded form.

It may contain duplicate field names.

func MakeDocument

func MakeDocument(cap int) *Document

MakeDocument creates a new empty Document with the given capacity.

func MustDocument added in v0.0.3

func MustDocument(pairs ...any) *Document

MustDocument is a variant of NewDocument that panics on error.

func NewDocument

func NewDocument(pairs ...any) (*Document, error)

NewDocument creates a new Document from the given pairs of field names and values.

func (*Document) Add

func (doc *Document) Add(name string, value any) error

Add adds a new field to the end of the Document.

func (*Document) All added in v0.0.8

func (doc *Document) All() iter.Seq2[string, any]

All returns an iterator over all field name/value pairs of the Document.

func (*Document) Command

func (doc *Document) Command() string

Command returns the first field name. This is often used as a command name. It returns an empty string if Document is nil or empty.

func (*Document) Copy added in v0.1.0

func (doc *Document) Copy() *Document

Copy returns a shallow copy of *Document. Only scalar values (including Binary) are copied. *Document, *Array, RawDocument, and RawArray are added without a copy, using the same pointer/slice.

func (*Document) Decode

func (doc *Document) Decode() (*Document, error)

Decode returns itself to implement AnyDocument.

Receiver must not be nil.

func (*Document) Encode

func (doc *Document) Encode() (RawDocument, error)

Encode encodes non-nil Document.

TODO https://github.com/FerretDB/wire/issues/21 This method should accept a slice of bytes, not return it. That would allow to avoid unnecessary allocations.

func (*Document) FieldNames deprecated

func (doc *Document) FieldNames() []string

FieldNames returns a slice of field names in the Document in the original order.

If Document contains duplicate field names, the same name will appear multiple times.

Deprecated: use Document.Fields instead.

func (*Document) Fields added in v0.0.10

func (doc *Document) Fields() iter.Seq[string]

Fields returns an iterator over all field names of the Document.

func (*Document) Freeze

func (doc *Document) Freeze()

Freeze prevents Document from further field modifications. Any methods that would modify Document fields will panic.

It is safe to call Freeze multiple times.

func (*Document) Get

func (doc *Document) Get(name string) any

Get returns a value of the field with the given name.

It returns nil if the field is not found.

If Document contains duplicate field names, it returns the first one. To get other fields, a for/range loop can be used with Document.All.

func (*Document) Len added in v0.0.5

func (doc *Document) Len() int

Len returns the number of fields in the Document.

func (*Document) LogMessage added in v0.0.11

func (doc *Document) LogMessage() string

LogMessage implements AnyDocument.

func (*Document) LogMessageIndent added in v0.0.11

func (doc *Document) LogMessageIndent() string

LogMessageIndent implements AnyDocument.

func (*Document) LogValue

func (doc *Document) LogValue() slog.Value

LogValue implements slog.LogValuer.

func (*Document) MarshalJSON added in v0.0.14

func (doc *Document) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler by encoding Canonical Extended JSON v2 representation of the document.

func (*Document) Remove

func (doc *Document) Remove(name string)

Remove removes the first existing field with the given name. It does nothing if the field with that name does not exist.

func (*Document) Replace

func (doc *Document) Replace(name string, value any) error

Replace sets the value for the first existing field with the given name. It does nothing if the field with that name does not exist.

func (*Document) UnmarshalJSON added in v0.0.14

func (doc *Document) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler by decoding Canonical Extended JSON v2 representation of the document.

type NullType

type NullType struct{}

NullType represents BSON scalar type null.

type ObjectID

type ObjectID [12]byte

ObjectID represents BSON scalar type ObjectID.

type RawArray

type RawArray []byte

RawArray represents a single BSON array in the binary encoded form.

It generally references a part of a larger slice, not a copy.

func (RawArray) Decode

func (raw RawArray) Decode() (*Array, error)

Decode decodes a single non-nil BSON array that takes the whole non-nil byte slice.

Only top-level elements are decoded; nested documents and arrays are converted to RawDocument and RawArray respectively, using raw's subslices without copying.

func (RawArray) DecodeDeep

func (raw RawArray) DecodeDeep() (*Array, error)

DecodeDeep decodes a single non-nil BSON array that takes the whole non-nil byte slice.

All nested documents and arrays are decoded recursively.

Receiver must not be nil.

func (RawArray) Encode

func (raw RawArray) Encode() (RawArray, error)

Encode returns itself to implement the AnyArray interface.

Receiver must not be nil.

func (RawArray) LogMessage added in v0.0.11

func (raw RawArray) LogMessage() string

LogMessage implements AnyArray.

func (RawArray) LogMessageIndent added in v0.0.11

func (raw RawArray) LogMessageIndent() string

LogMessageIndent implements AnyArray.

func (RawArray) LogValue

func (raw RawArray) LogValue() slog.Value

LogValue implements slog.LogValuer.

type RawDocument

type RawDocument []byte

RawDocument represents a single BSON document a.k.a object in the binary encoded form.

It generally references a part of a larger slice, not a copy.

func (RawDocument) Decode

func (raw RawDocument) Decode() (*Document, error)

Decode decodes a single non-nil BSON document that takes the whole non-nil byte slice.

Only top-level fields are decoded; nested documents and arrays are converted to RawDocument and RawArray respectively, using raw's subslices without copying.

func (RawDocument) DecodeDeep

func (raw RawDocument) DecodeDeep() (*Document, error)

DecodeDeep decodes a single non-nil BSON document that takes the whole non-nil byte slice.

All nested documents and arrays are decoded recursively.

func (RawDocument) Encode

func (raw RawDocument) Encode() (RawDocument, error)

Encode returns itself to implement the AnyDocument interface.

Receiver must not be nil.

func (RawDocument) LogMessage added in v0.0.11

func (raw RawDocument) LogMessage() string

LogMessage implements AnyDocument.

func (RawDocument) LogMessageIndent added in v0.0.11

func (raw RawDocument) LogMessageIndent() string

LogMessageIndent implements AnyDocument.

func (RawDocument) LogValue

func (raw RawDocument) LogValue() slog.Value

LogValue implements slog.LogValuer.

type Regex

type Regex struct {
	Pattern string
	Options string
}

Regex represents BSON scalar type regular expression.

type ScalarType

type ScalarType interface {
	float64 | string | Binary | UndefinedType | ObjectID | bool | time.Time | NullType | Regex | int32 | Timestamp | int64 | Decimal128
}

ScalarType represents a BSON scalar type.

CString is not included as it is not a real BSON type.

type Timestamp

type Timestamp uint64

Timestamp represents BSON scalar type timestamp.

func NewTimestamp added in v0.0.17

func NewTimestamp(t, i uint32) Timestamp

NewTimestamp creates a Timestamp using the provided time and increment.

func (Timestamp) I added in v0.0.17

func (ts Timestamp) I() uint32

I returns the increment part of the timestamp.

func (Timestamp) T added in v0.0.17

func (ts Timestamp) T() uint32

T returns the time part of the timestamp.

type Type

type Type interface {
	CompositeType | ScalarType
}

Type represents a BSON type.

type UndefinedType added in v0.0.17

type UndefinedType struct{}

UndefinedType represents BSON scalar type undefined.

Jump to

Keyboard shortcuts

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