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
- Variables
- func DecodeCString(b []byte) (string, error)
- func EncodeCString(b []byte, v string)
- func Equal(v1, v2 any) bool
- func FindRaw(b []byte) (int, error)
- func FromDriver(v any) (any, error)
- func LogMessage(v any) string
- func LogMessageIndent(v any) string
- func Size(v any) int
- func SizeCString(v string) int
- func ToDriver(v any) (any, error)
- type AnyArray
- type AnyDocument
- type Array
- func (arr *Array) Add(value any) error
- func (arr *Array) All() iter.Seq2[int, any]
- func (arr *Array) Copy() *Array
- func (arr *Array) Decode() (*Array, error)
- func (arr *Array) Encode() (RawArray, error)
- func (arr *Array) Freeze()
- func (arr *Array) Get(index int) any
- func (arr *Array) Len() int
- func (arr *Array) LogMessage() string
- func (arr *Array) LogMessageIndent() string
- func (arr *Array) LogValue() slog.Value
- func (arr *Array) MarshalJSON() ([]byte, error)
- func (arr *Array) Replace(index int, value any) error
- func (arr *Array) SortInterface(less func(a, b any) bool) sort.Interface
- func (arr *Array) UnmarshalJSON(b []byte) error
- func (arr *Array) Values() iter.Seq[any]
- type Binary
- type BinarySubtype
- type CompositeType
- type Decimal128
- type Document
- func (doc *Document) Add(name string, value any) error
- func (doc *Document) All() iter.Seq2[string, any]
- func (doc *Document) Command() string
- func (doc *Document) Copy() *Document
- func (doc *Document) Decode() (*Document, error)
- func (doc *Document) Encode() (RawDocument, error)
- func (doc *Document) FieldNames() []stringdeprecated
- func (doc *Document) Fields() iter.Seq[string]
- func (doc *Document) Freeze()
- func (doc *Document) Get(name string) any
- func (doc *Document) Len() int
- func (doc *Document) LogMessage() string
- func (doc *Document) LogMessageIndent() string
- func (doc *Document) LogValue() slog.Value
- func (doc *Document) MarshalJSON() ([]byte, error)
- func (doc *Document) Remove(name string)
- func (doc *Document) Replace(name string, value any) error
- func (doc *Document) UnmarshalJSON(b []byte) error
- type NullType
- type ObjectID
- type RawArray
- type RawDocument
- type Regex
- type ScalarType
- type Timestamp
- type Type
- type UndefinedType
Constants ¶
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 ¶
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") )
var Null = NullType{}
Null represents BSON scalar value null.
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 ¶
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 ¶
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
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 ¶
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
FromDriver converts MongoDB driver v2 (and, temporary, v1) value (bson.D, bson.A, etc) to wirebson value.
func LogMessage ¶
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
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
Size returns the size of the encoding of value v in bytes.
It panics for invalid types.
func SizeCString ¶
SizeCString returns the size of the encoding of v cstring in bytes.
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 (*Array) Copy ¶ added in v0.1.0
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) Encode ¶
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) LogMessage ¶ added in v0.0.11
LogMessage implements AnyArray.
func (*Array) LogMessageIndent ¶ added in v0.0.11
LogMessageIndent implements AnyArray.
func (*Array) LogValue ¶
LogValue implements slog.LogValuer.
func (*Array) MarshalJSON ¶ added in v0.0.14
MarshalJSON implements json.Marshaler by encoding Canonical Extended JSON v2 representation of the array.
func (*Array) Replace ¶
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
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
UnmarshalJSON implements json.Unmarshaler by decoding Canonical Extended JSON v2 representation 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 ¶
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 ¶
MakeDocument creates a new empty Document with the given capacity.
func MustDocument ¶ added in v0.0.3
MustDocument is a variant of NewDocument that panics on error.
func NewDocument ¶
NewDocument creates a new Document from the given pairs of field names and values.
func (*Document) All ¶ added in v0.0.8
All returns an iterator over all field name/value pairs of the Document.
func (*Document) Command ¶
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
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) 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
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
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 ¶
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) LogMessage ¶ added in v0.0.11
LogMessage implements AnyDocument.
func (*Document) LogMessageIndent ¶ added in v0.0.11
LogMessageIndent implements AnyDocument.
func (*Document) LogValue ¶
LogValue implements slog.LogValuer.
func (*Document) MarshalJSON ¶ added in v0.0.14
MarshalJSON implements json.Marshaler by encoding Canonical Extended JSON v2 representation of the document.
func (*Document) Remove ¶
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 ¶
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
UnmarshalJSON implements json.Unmarshaler by decoding Canonical Extended JSON v2 representation of the document.
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 ¶
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 ¶
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 ¶
Encode returns itself to implement the AnyArray interface.
Receiver must not be nil.
func (RawArray) LogMessage ¶ added in v0.0.11
LogMessage implements AnyArray.
func (RawArray) LogMessageIndent ¶ added in v0.0.11
LogMessageIndent implements AnyArray.
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 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
NewTimestamp creates a Timestamp using the provided time and increment.
type UndefinedType ¶ added in v0.0.17
type UndefinedType struct{}
UndefinedType represents BSON scalar type undefined.