birch

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2023 License: Apache-2.0 Imports: 19 Imported by: 12

README

==================================================================
``birch`` -- Flexible Document Encoding and Manipulation Framework
==================================================================

Overview
--------

``birch``, is a Go library for manipulating "documents." Documents are
collections of key-value types with richly typed values, and in the same sense
as the documents at the core of MongoDB's data model. Indeed, it is descended
from an early version of `the BSON library for the current MongoDB Go Driver
<https://github.com/mongodb/mongo-go-driver/>`_; however, the goals of
``birch`` have diverged. ``birch`` exists to provide an API for creating and
manipulating documents without using reflection or the MongoDB
driver, without loosing type fidelity, while still producing valid BSON and
JSON representations of a document.

In addition to document production, the birch package contains two other
additional areas of functionality that build upon the core document
manipulation layer:

- ``ftdc`` provides a document-based, columnar, format ideal for storing
  timeseries data. This package is useful for storing high resolution system
  or application metrics data. The format is highly compressed and the tools
  can support high volume data collection tools. This is the same format that
  the MongoDB service produces for its internal diagnostic data capture, and
  this package provides an API for reading and writing data in this format, as
  well as tools in support of creating metrics for this format.

- ``mrpc`` provides a set of low level tools for interacting with
  ""mongodb-wire-protocol" RPC services. This might be useful for writing
  fairly low-level interactions with MongoDB services, you might also be able
  to use this as the basis for providing the *server* half that is compatible
  with most MongoDB protocol implementations.

In most cases if you have Go objects that (structs, etc) that you want to
convert to BSON you should use the Go driver's bson library. However, if you
need to programatically interact with BSON and want a reasonable, type-safe,
API for that, birch is may be the right thing!

API and Documentation
---------------------

See `the godoc <https://pkg.go.dev/github.com/tychoish/birch>`_ for full
API documentation.

Development
-----------

The API is stable, and the library is largely feature complete. The following
areas may see some additional development:

- adding additional higher-level tools for interacting with
  timeseries data, including new collectors and first-class support for
  additional data formats.

- additional document and element constructors for new types and
  type-combinations, to improve the behavior of the ``birch.EC.Interface()``
  constructor.

The existing API wouldn't change to add support for these features.

Documentation

Overview

Package birch is a bson library built on top of the legacy bson.Document type for building and interacting with bson documents. For most bson interaction use the github.com/mongodb/mongo-go-driver library.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func MarshalDocumentBSON

func MarshalDocumentBSON(dm DocumentMarshaler) ([]byte, error)

MarshalDocumentBSON provides a convience function to convert document marshalers directly to bson.

Types

type Array

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

Array represents an array in BSON. The methods of this type are more expensive than those on Document because they require potentially updating multiple keys to ensure the array stays valid at all times.

Example
internalVersion := "1234567"

f := func(appName string) *Array {
	arr := NewArray()
	arr.Append(
		VC.DocumentFromElements(
			EC.String("name", "mongo-go-driver"),
			EC.String("version", internalVersion),
		),
		VC.DocumentFromElements(
			EC.String("type", "darwin"),
			EC.String("architecture", "amd64"),
		),
		VC.String("go1.9.2"),
	)

	if appName != "" {
		arr.Append(VC.DocumentFromElements(EC.String("name", appName)))
	}

	return arr
}

buf, err := f("hello-world").MarshalBSON()
if err != nil {
	fmt.Println(err)
}

fmt.Println(buf)
Output:

[154 0 0 0 3 48 0 52 0 0 0 2 110 97 109 101 0 16 0 0 0 109 111 110 103 111 45 103 111 45 100 114 105 118 101 114 0 2 118 101 114 115 105 111 110 0 8 0 0 0 49 50 51 52 53 54 55 0 0 3 49 0 46 0 0 0 2 116 121 112 101 0 7 0 0 0 100 97 114 119 105 110 0 2 97 114 99 104 105 116 101 99 116 117 114 101 0 6 0 0 0 97 109 100 54 52 0 0 2 50 0 8 0 0 0 103 111 49 46 57 46 50 0 3 51 0 27 0 0 0 2 110 97 109 101 0 12 0 0 0 104 101 108 108 111 45 119 111 114 108 100 0 0 0]

func MakeArray

func MakeArray(size int) *Array

MakeArray creates a new array with the size hint (capacity) specified.

func NewArray

func NewArray(values ...*Value) *Array

NewArray creates a new array with the specified value.

func (*Array) Append

func (a *Array) Append(values ...*Value) *Array

Append adds the given values to the end of the array. It returns a reference to itself.

func (*Array) Delete

func (a *Array) Delete(index uint) *Value

Delete removes the value at the given index from the array.

func (*Array) Extend

func (a *Array) Extend(ar2 *Array) *Array

Extend adds the values from the second array to the first array, returning the original array for chaining.

func (*Array) ExtendFromDocument

func (a *Array) ExtendFromDocument(doc *Document) *Array

ExtendFromDocument adds the values from the elements in the document returning the array for chaining.

func (*Array) Interface

func (a *Array) Interface() []any

Interface returns a slice of any typed values for every element in the array using the Value.Interface() method to export. the values.

func (*Array) Iterator

func (a *Array) Iterator() fun.Iterator[*Value]

Iterator returns a ArrayIterator that can be used to iterate through the elements of this Array.

func (*Array) Len

func (a *Array) Len() int

Len returns the number of elements in the array.

func (*Array) Lookup

func (a *Array) Lookup(index uint) (*Value, error)

LookupErr returns the value at the specified index, returning an OutOfBounds error if that element doesn't exist.

func (*Array) LookupElemdent

func (a *Array) LookupElemdent(index uint) (*Element, error)

LookupElement returns the element at the specified index, returning an OutOfBounds error if that element doesn't exist.

func (*Array) MarshalBSON

func (a *Array) MarshalBSON() ([]byte, error)

MarshalBSON implements the Marshaler interface.

func (*Array) MarshalJSON

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

MarshalJSON produces a JSON representation of an Array preserving the type information for the types that have no JSON equivalent using MongoDB's extended JSON format where needed.

func (*Array) Reset

func (a *Array) Reset()

Reset clears all elements from the array.

func (*Array) Set

func (a *Array) Set(index uint, value *Value) *Array

Set replaces the value at the given index with the parameter value. It panics if the index is out of bounds.

func (*Array) String

func (a *Array) String() string

String implements the fmt.Stringer interface.

func (*Array) UnmarshalJSON

func (a *Array) UnmarshalJSON(in []byte) error

func (*Array) Validate

func (a *Array) Validate() (uint32, error)

Validate ensures that the array's underlying BSON is valid. It returns the the number of bytes in the underlying BSON if it is valid or an error if it isn't.

type Document

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

Document is a mutable ordered map that compactly represents a BSON document.

Example
internalVersion := "1234567"

f := func(appName string) *Document {
	doc := DC.Elements(
		EC.SubDocumentFromElements("driver",
			EC.String("name", "mongo-go-driver"),
			EC.String("version", internalVersion),
		),
		EC.SubDocumentFromElements("os",
			EC.String("type", "darwin"),
			EC.String("architecture", "amd64"),
		),
		EC.String("platform", "go1.9.2"),
	)

	if appName != "" {
		doc.Append(EC.SubDocumentFromElements("application", EC.String("name", appName)))
	}

	return doc
}

buf, err := f("hello-world").MarshalBSON()
if err != nil {
	fmt.Println(err)
}

fmt.Println(buf)
Output:

[177 0 0 0 3 100 114 105 118 101 114 0 52 0 0 0 2 110 97 109 101 0 16 0 0 0 109 111 110 103 111 45 103 111 45 100 114 105 118 101 114 0 2 118 101 114 115 105 111 110 0 8 0 0 0 49 50 51 52 53 54 55 0 0 3 111 115 0 46 0 0 0 2 116 121 112 101 0 7 0 0 0 100 97 114 119 105 110 0 2 97 114 99 104 105 116 101 99 116 117 114 101 0 6 0 0 0 97 109 100 54 52 0 0 2 112 108 97 116 102 111 114 109 0 8 0 0 0 103 111 49 46 57 46 50 0 3 97 112 112 108 105 99 97 116 105 111 110 0 27 0 0 0 2 110 97 109 101 0 12 0 0 0 104 101 108 108 111 45 119 111 114 108 100 0 0 0]

func ReadDocument

func ReadDocument(b []byte) (*Document, error)

ReadDocument will create a Document using the provided slice of bytes. If the slice of bytes is not a valid BSON document, this method will return an error.

func (*Document) Append

func (d *Document) Append(elems ...*Element) *Document

Append adds each element to the end of the document, in order. If a nil element is passed as a parameter this method will panic. To change this behavior to silently ignore a nil element, set IgnoreNilInsert to true on the Document.

If a nil element is inserted and this method panics, it does not remove the previously added elements.

func (*Document) AppendOmitEmpty

func (d *Document) AppendOmitEmpty(elems ...*Element) *Document

AppendOmitEmpty adds all non-empty values to the document, and has no impact otherwise.

func (*Document) Copy

func (d *Document) Copy() *Document

Copy makes a shallow copy of this document.

func (*Document) Delete

func (d *Document) Delete(key string) *Element

Delete removes the keys from the Document. The deleted element is returned. If the key does not exist, then nil is returned and the delete is a no-op.

func (*Document) ElementAt

func (d *Document) ElementAt(index uint) *Element

ElementAt retrieves the element at the given index in a Document. It panics if the index is out-of-bounds.

func (*Document) ElementAtOK

func (d *Document) ElementAtOK(index uint) (*Element, bool)

ElementAtOK is the same as ElementAt, but returns a boolean instead of panicking.

func (*Document) Elements

func (d *Document) Elements() Elements

Elements provides access to a slice of the Elements in the document. Mutating this list will mutate the content of the document.

func (*Document) ExportMap

func (d *Document) ExportMap() map[string]any

ExportMap converts the values of the document to a map of strings to interfaces, recursively, using the Value.Interface() method.

func (*Document) Extend

func (d *Document) Extend(d2 *Document) *Document

Extend merges a second document into the document. It may produce a document with duplicate keys.

func (*Document) Iterator

func (d *Document) Iterator() fun.Iterator[*Element]

Iterator creates an Iterator for this document and returns it.

func (*Document) Len

func (d *Document) Len() int

Len returns the number of elements in the document.

func (*Document) Lookup

func (d *Document) Lookup(key string) *Value

Lookup iterates through the elements in a document looking for one with the correct key and returns the value for that key. It is NOT recursive. When the element is not present.

func (*Document) LookupElement

func (d *Document) LookupElement(key string) *Element

LookupElement iterates through the elements in a document looking for one with the correct key and returns that element. It is NOT recursive. When the element is not defined, the return value is nil.

func (*Document) LookupElementErr

func (d *Document) LookupElementErr(key string) (*Element, error)

LookupElementErr iterates through the elements in a document looking for one with the correct key and returns the Element for that key. It is NOT recursive. When the element is not defined, it returns a ElementNotFound error.

func (*Document) LookupErr

func (d *Document) LookupErr(key string) (*Value, error)

LookupErr iterates through the elements in a document looking for one with the correct key and returns the value for that key. It is NOT recursive. When the element is not defined, it returns a ElementNotFound error.

func (*Document) Map added in v0.2.0

func (d *Document) Map() DocumentMap

Map returns a map-based view of the document. If a key appears in a document more than once only the first occurrence is included. birch.Document's cache the document map, so as logn as the document doesn't change rebuilding the map is cheap.

The object returned contains pointers to the underlying elements of the document, but is a copy of the cached map, and multiple calls to Map() will return different maps.

func (*Document) MarshalBSON

func (d *Document) MarshalBSON() ([]byte, error)

MarshalBSON implements the Marshaler interface.

func (*Document) MarshalDocument

func (d *Document) MarshalDocument() (*Document, error)

MarshalDocument satisfies the DocumentMarshaler interface, and returns the document itself.

func (*Document) MarshalJSON

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

MarshalJSON produces a JSON representation of the Document, preserving the order of the keys, and type information for types that have no JSON equivlent using MongoDB's extended JSON format where needed.

func (*Document) ReadFrom

func (d *Document) ReadFrom(r io.Reader) (int64, error)

ReadFrom will read one BSON document from the given io.Reader.

func (*Document) Reset

func (d *Document) Reset()

Reset clears a document so it can be reused. This method clears references to the underlying pointers to elements so they can be garbage collected.

func (*Document) Search

func (d *Document) Search(keys ...string) (*Element, error)

Search iterates through the keys in the document, returning the element with the matching key, and nil othe

func (*Document) Set

func (d *Document) Set(elem *Element) *Document

Set replaces an element of a document. If an element with a matching key is found, the element will be replaced with the one provided. If the document does not have an element with that key, the element is appended to the document instead. If a nil element is passed as a parameter this method will panic.

If a nil element is inserted and this method panics.

func (*Document) Sorted

func (d *Document) Sorted() *Document

Sorted returns a new document containing a (shallow copy) of the elements from the source document ordered according to their value.

func (*Document) String

func (d *Document) String() string

String implements the fmt.Stringer interface.

func (*Document) Unmarshal

func (d *Document) Unmarshal(into any) error

Unmarshal attempts to read the bson document into the interface value provided, with the semantics dependent on the input type. The semantics are loose (particularly for sized integers), work reasonably well for simple map types and will not always round trip. While unmarshal will overwrite values in an existing input structure, it will not delete other values, and will avoid writing fields in the document which cannot be easily converted. While this method does not work with arbitrary types that do not implement DocumentUnmarshaler, it does not use reflection.

func (*Document) UnmarshalBSON

func (d *Document) UnmarshalBSON(b []byte) error

UnmarshalBSON implements the Unmarshaler interface.

func (*Document) UnmarshalDocument

func (d *Document) UnmarshalDocument(in *Document) error

UnmarshalDocument satisfies the DocumentUnmarshaler interface and appends the elements of the input document to the underlying document. If the document is populated this could result in a document that has multiple identical keys.

func (*Document) UnmarshalJSON

func (d *Document) UnmarshalJSON(in []byte) error

UnmarshalJSON converts the contents of a document to JSON recursively, preserving the order of keys and the rich types from bson using MongoDB's extended JSON format for BSON types that have no equivalent in JSON.

The underlying document is not emptied before this operation, which for non-empty documents could result in duplicate keys.

func (*Document) Validate

func (d *Document) Validate() (uint32, error)

Validate validates the document and returns its total size.

func (*Document) WriteTo

func (d *Document) WriteTo(w io.Writer) (int64, error)

WriteTo implements the io.WriterTo interface.

TODO(skriptble): We can optimize this by having creating implementations of writeByteSlice that write directly to an io.Writer instead.

type DocumentConstructor

type DocumentConstructor struct{}

DocumentConstructor is used as a namespace for document constructor functions. Constructor methods may panic in cases when invalid input would cause them to error when using the DocumentConstructorError

DC is a convenience variable provided for access to the DocumentConstructor methods.

func (DocumentConstructor) Elements

func (DocumentConstructor) Elements(elems ...*Element) *Document

Elements returns a document initialized with the elements passed as arguments.

func (DocumentConstructor) ElementsOmitEmpty

func (DocumentConstructor) ElementsOmitEmpty(elems ...*Element) *Document

ElementsOmitEmpty crates a document with all non-empty values.

func (DocumentConstructor) Interface

func (DocumentConstructor) Interface(value any) *Document

func (DocumentConstructor) JSONX

func (DocumentConstructor) Make

func (DocumentConstructor) Make(n int) *Document

Make returns a document with the underlying storage allocated as specified. Provides some efficiency when building larger documents iteratively.

func (DocumentConstructor) MapInterface

func (DocumentConstructor) MapInterface(in map[string]any) *Document

func (DocumentConstructor) MapInterfaceInterface

func (DocumentConstructor) MapInterfaceInterface(in map[any]any) *Document

func (DocumentConstructor) MapString

func (DocumentConstructor) MapString(in map[string]string) *Document

func (DocumentConstructor) Marshaler

func (DocumentConstructor) Marshaler(in Marshaler) *Document

func (DocumentConstructor) New

New returns an empty document.

func (DocumentConstructor) ReadFrom

func (DocumentConstructor) ReadFrom(in io.Reader) *Document

ReadFrom builds a document reading a bytes sequence from an io.Reader, panicing if there's a problem reading from the reader.

func (DocumentConstructor) Reader

func (DocumentConstructor) Reader(r Reader) *Document

Reader constructs a document from a bson reader, which is a wrapper around a byte slice representation of a bson document. Reader panics if there is a problem reading the document.

type DocumentConstructorError

type DocumentConstructorError struct{}

DocumentConstructor is used as a namespace for document constructor functions. These methods return errors rather than panicing in the case of invalid input

DCE is a convenience variable provided for access to the DocumentConstructorError methods.

func (DocumentConstructorError) Interface

func (DocumentConstructorError) Interface(value any) (*Document, error)

func (DocumentConstructorError) JSONX

func (DocumentConstructorError) MapInterface

func (DocumentConstructorError) MapInterface(in map[string]any) (*Document, error)

func (DocumentConstructorError) MapInterfaceInterface

func (DocumentConstructorError) MapInterfaceInterface(in map[any]any) (*Document, error)

func (DocumentConstructorError) Marshaler

func (DocumentConstructorError) ReadFrom

func (DocumentConstructorError) ReadFrom(in io.Reader) (*Document, error)

ReadFromErr builds a document reading a bytes sequence from an io.Reader, returning an error if there's a problem reading from the reader.

func (DocumentConstructorError) Reader

ReaderErr constructs a document from a bson reader, which is a wrapper around a byte slice representation of a bson document. Reader returns an error if there is a problem reading the document.

type DocumentMap added in v0.2.0

type DocumentMap map[string]*Element

DocumentMap is a map-based view of a document, used for key-lookups, and providing another option in document construction.

func (DocumentMap) Copy added in v0.2.0

func (dm DocumentMap) Copy() DocumentMap

Copy returns a new map with the same values as the source map, but in a different map object that callers have ownership over.

func (DocumentMap) MarshalBSON added in v0.2.0

func (dm DocumentMap) MarshalBSON() ([]byte, error)

func (DocumentMap) MarshalDocument added in v0.2.0

func (dm DocumentMap) MarshalDocument() (*Document, error)

func (DocumentMap) UnmarshalBSON added in v0.2.0

func (dm DocumentMap) UnmarshalBSON(in []byte) error

func (DocumentMap) UnmarshalDocument added in v0.2.0

func (dm DocumentMap) UnmarshalDocument(in *Document) error

func (DocumentMap) Validate added in v0.2.0

func (dm DocumentMap) Validate() error

Validate checks the validity of each element in the DocumentMap, and ensures that every key in the map matches the key value of the element itself.

type DocumentMarshaler

type DocumentMarshaler interface {
	MarshalDocument() (*Document, error)
}

DocumentMarshaler describes types that are able to produce Document represntations of themselves.

type DocumentUnmarshaler

type DocumentUnmarshaler interface {
	UnmarshalDocument(*Document) error
}

DocumentUnmarshaler describes a type that can populate itself from a document.

type Element

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

Element represents a BSON element, i.e. key-value pair of a BSON document.

NOTE: Element cannot be the value of a map nor a property of a struct without special handling. The default encoders and decoders will not process Element correctly. To do so would require information loss since an Element contains a key, but the keys used when encoding a struct are the struct field names. Instead of using an Element, use a Value as the property of a struct field as that is the correct type in this circumstance.

func (*Element) Copy

func (e *Element) Copy() *Element

Copy creates a new Element which has a copy of the content from original value, but is otherwise entirely independent.

func (*Element) Equal

func (e *Element) Equal(e2 *Element) bool

Equal compares this element to element and returns true if they are equal.

func (*Element) Key

func (e *Element) Key() string

Key returns the key for this element. It returns the empty string if the element is not initialized.

func (*Element) MarshalBSON

func (e *Element) MarshalBSON() ([]byte, error)

MarshalBSON implements the Marshaler interface.

func (*Element) SetValue

func (e *Element) SetValue(v *Value)

SetValue makes it possible to modify the value of an element in place

func (*Element) String

func (e *Element) String() string

String implements the fmt.Stringer interface.

func (*Element) Validate

func (e *Element) Validate() (uint32, error)

Validate validates the element and returns its total size.

func (*Element) Value

func (e *Element) Value() *Value

Value returns the value associated with the BSON element.

func (*Element) WriteTo

func (e *Element) WriteTo(w io.Writer) (int64, error)

WriteTo implements the io.WriterTo interface.

type ElementConstructor

type ElementConstructor struct{}

ElementConstructor is used as a namespace for document element constructor functions.

EC is a convenience variable provided for access to the ElementConstructor methods.

func (ElementConstructor) Array

func (ElementConstructor) Array(key string, a *Array) *Element

Array creates an array element with the given key and value.

func (ElementConstructor) ArrayFromElements

func (ElementConstructor) ArrayFromElements(key string, values ...*Value) *Element

ArrayFromElements creates an element with the given key. The elements passed as arguments will be used to create a new array as the value.

func (ElementConstructor) Binary

func (ElementConstructor) Binary(key string, b []byte) *Element

Binary creates a binary element with the given key and value.

func (ElementConstructor) BinaryWithSubtype

func (ElementConstructor) BinaryWithSubtype(key string, b []byte, btype byte) *Element

BinaryWithSubtype creates a binary element with the given key. It will create a new BSON binary value with the given data and subtype.

func (ElementConstructor) Boolean

func (ElementConstructor) Boolean(key string, b bool) *Element

Boolean creates a boolean element with the given key and value.

func (ElementConstructor) CodeWithScope

func (ElementConstructor) CodeWithScope(key string, code string, scope *Document) *Element

CodeWithScope creates a JavaScript code with scope element with the given key and value.

func (ElementConstructor) DBPointer

func (ElementConstructor) DBPointer(key string, ns string, oid types.ObjectID) *Element

DBPointer creates a dbpointer element with the given key and value.

func (ElementConstructor) DateTime

func (ElementConstructor) DateTime(key string, dt int64) *Element

DateTime creates a datetime element with the given key and value. dt represents milliseconds since the Unix epoch

func (ElementConstructor) Decimal128

func (ElementConstructor) Decimal128(key string, d types.Decimal128) *Element

Decimal128 creates a decimal element with the given key and value.

func (ElementConstructor) DocumentMarshaler

func (ElementConstructor) DocumentMarshaler(key string, val DocumentMarshaler) *Element

func (ElementConstructor) Double

func (ElementConstructor) Double(key string, f float64) *Element

Double creates a double element with the given key and value.

func (ElementConstructor) Duration

func (ElementConstructor) Duration(key string, t time.Duration) *Element

func (ElementConstructor) Int

func (ElementConstructor) Int(key string, i int) *Element

func (ElementConstructor) Int32

func (ElementConstructor) Int32(key string, i int32) *Element

Int32 creates a int32 element with the given key and value.

func (ElementConstructor) Int64

func (ElementConstructor) Int64(key string, i int64) *Element

Int64 creates a int64 element with the given key and value.

func (ElementConstructor) Interface

func (ElementConstructor) Interface(key string, value any) *Element

Interface will attempt to turn the provided key and value into an Element. For common types, type casting is used, for all slices and all other complex types, this relies on the Marshaler interface.

If the value cannot be converted to bson, a null Element is constructed with the key. This method will never return a nil *Element. If an error turning the value into an Element is desired, use the InterfaceErr method.

func (ElementConstructor) JavaScript

func (ElementConstructor) JavaScript(key string, code string) *Element

JavaScript creates a JavaScript code element with the given key and value.

func (ElementConstructor) Marshaler

func (ElementConstructor) Marshaler(key string, val Marshaler) *Element

func (ElementConstructor) MaxKey

func (ElementConstructor) MaxKey(key string) *Element

MaxKey creates a maxkey element with the given key and value.

func (ElementConstructor) MinKey

func (ElementConstructor) MinKey(key string) *Element

MinKey creates a minkey element with the given key and value.

func (ElementConstructor) Null

func (ElementConstructor) Null(key string) *Element

Null creates a null element with the given key.

func (ElementConstructor) ObjectID

func (ElementConstructor) ObjectID(key string, oid types.ObjectID) *Element

ObjectID creates a objectid element with the given key and value.

func (ElementConstructor) Regex

func (ElementConstructor) Regex(key string, pattern, options string) *Element

Regex creates a regex element with the given key and value.

func (ElementConstructor) SliceDuration

func (ElementConstructor) SliceDuration(key string, in []time.Duration) *Element

func (ElementConstructor) SliceFloat32

func (ElementConstructor) SliceFloat32(key string, in []float32) *Element

func (ElementConstructor) SliceFloat64

func (ElementConstructor) SliceFloat64(key string, in []float64) *Element

func (ElementConstructor) SliceInt

func (ElementConstructor) SliceInt(key string, in []int) *Element

func (ElementConstructor) SliceInt32

func (ElementConstructor) SliceInt32(key string, in []int32) *Element

func (ElementConstructor) SliceInt64

func (ElementConstructor) SliceInt64(key string, in []int64) *Element

func (ElementConstructor) SliceInterface

func (ElementConstructor) SliceInterface(key string, in []any) *Element

func (ElementConstructor) SliceString

func (ElementConstructor) SliceString(key string, in []string) *Element

func (ElementConstructor) SliceTime

func (ElementConstructor) SliceTime(key string, in []time.Time) *Element

func (ElementConstructor) String

func (ElementConstructor) String(key string, val string) *Element

String creates a string element with the given key and value.

func (ElementConstructor) SubDocument

func (ElementConstructor) SubDocument(key string, d *Document) *Element

SubDocument creates a subdocument element with the given key and value.

func (ElementConstructor) SubDocumentFromElements

func (ElementConstructor) SubDocumentFromElements(key string, elems ...*Element) *Element

SubDocumentFromElements creates a subdocument element with the given key. The elements passed as arguments will be used to create a new document as the value.

func (ElementConstructor) SubDocumentFromReader

func (ElementConstructor) SubDocumentFromReader(key string, r Reader) *Element

func (ElementConstructor) Symbol

func (ElementConstructor) Symbol(key string, symbol string) *Element

Symbol creates a symbol element with the given key and value.

func (ElementConstructor) Time

func (ElementConstructor) Time(key string, t time.Time) *Element

Time creates a datetime element with the given key and value.

func (ElementConstructor) Timestamp

func (ElementConstructor) Timestamp(key string, t uint32, i uint32) *Element

Timestamp creates a timestamp element with the given key and value.

func (ElementConstructor) Undefined

func (ElementConstructor) Undefined(key string) *Element

Undefined creates a undefined element with the given key.

func (ElementConstructor) Value

func (ElementConstructor) Value(key string, value *Value) *Element

Value constructs an element using the underlying value.

type ElementConstructorError added in v0.2.0

type ElementConstructorError struct{}

func (ElementConstructorError) DocumentMarshaler added in v0.2.0

func (ElementConstructorError) DocumentMarshaler(key string, val DocumentMarshaler) (*Element, error)

func (ElementConstructorError) Interface added in v0.2.0

func (ElementConstructorError) Interface(key string, value any) (*Element, error)

InterfaceErr does what Interface does, but returns an error when it cannot properly convert a value into an *Element. See Interface for details.

func (ElementConstructorError) Marshaler added in v0.2.0

func (ElementConstructorError) Marshaler(key string, val Marshaler) (*Element, error)

func (ElementConstructorError) SliceInterface added in v0.2.0

func (ElementConstructorError) SliceInterface(key string, in []any) (*Element, error)

type Elements

type Elements []*Element

Elements is a representation of a slice of elements, and implements the sort.Interface to support ordering the keys of a document.

func (Elements) Copy

func (c Elements) Copy() Elements

Copy returns a new Elements slice with the same underlying Elements. The copy is "shallow."

func (Elements) Len

func (c Elements) Len() int

func (Elements) Less

func (c Elements) Less(i, j int) bool

func (Elements) Swap

func (c Elements) Swap(i, j int)

type Marshaler

type Marshaler interface {
	MarshalBSON() ([]byte, error)
}

Marshaler describes types that know how to marshal a document representation of themselves into bson. Do not use this interface for types that would marshal themselves into values.

type Reader

type Reader []byte

Reader is a wrapper around a byte slice. It will interpret the slice as a BSON document. Most of the methods on Reader are low cost and are meant for simple operations that are run a few times. Because there is no metadata stored all methods run in O(n) time. If a more efficient lookup method is necessary then the Document type should be used.

func NewFromIOReader

func NewFromIOReader(r io.Reader) (Reader, error)

NewFromIOReader reads in a document from the given io.Reader and constructs a bson.Reader from it.

func (Reader) ElementAt

func (r Reader) ElementAt(index uint) (*Element, error)

ElementAt searches for a retrieves the element at the given index. This method will validate all the elements up to and including the element at the given index.

func (Reader) Iterator

func (r Reader) Iterator() (fun.Iterator[*Element], error)

Iterator returns a ReaderIterator that can be used to iterate through the elements of this Reader.

func (Reader) MarshalBSON

func (r Reader) MarshalBSON() ([]byte, error)

MarshalBSON implements the bsoncodec.Marshaler interface.

This method does not copy the bytes from r.

func (Reader) RecursiveLookup

func (r Reader) RecursiveLookup(key ...string) (*Element, error)

RecursiveLookup search the document, potentially recursively, for the given key. If there are multiple keys provided, this method will recurse down, as long as the top and intermediate nodes are either documents or arrays. If any key except for the last is not a document or an array, an error will be returned.

TODO(skriptble): Implement better error messages.

TODO(skriptble): Determine if this should return an error on empty key and key not found.

func (Reader) String

func (r Reader) String() string

String implements the fmt.Stringer interface.

func (Reader) Validate

func (r Reader) Validate() (size uint32, err error)

Validate validates the document. This method only validates the first document in the slice, to validate other documents, the slice must be resliced.

Example
rdr := make(Reader, 500)
rdr[250], rdr[251], rdr[252], rdr[253], rdr[254] = '\x05', '\x00', '\x00', '\x00', '\x00'
n, err := rdr[250:].Validate()
fmt.Println(n, err)
Output:

5 <nil>

type Unmarshaler

type Unmarshaler interface {
	UnmarshalBSON([]byte) error
}

Unmarshaler describes types that can take a byte slice representation of bson and poulate themselves from this data.

type Value

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

Value represents a BSON value. It can be obtained as part of a bson.Element or created for use in a bson.Array with the bson.VC constructors.

func (*Value) Binary

func (v *Value) Binary() (subtype byte, data []byte)

Binary returns the BSON binary value the Value represents. It panics if the value is a BSON type other than binary.

func (*Value) BinaryOK

func (v *Value) BinaryOK() (subtype byte, data []byte, ok bool)

BinaryOK is the same as Binary, except it returns a boolean instead of panicking.

func (*Value) Boolean

func (v *Value) Boolean() bool

Boolean returns the boolean value the Value represents. It panics if the value is a BSON type other than boolean.

func (*Value) BooleanOK

func (v *Value) BooleanOK() (bool, bool)

BooleanOK is the same as Boolean, except it returns a boolean instead of panicking.

func (*Value) Copy

func (v *Value) Copy() *Value

Copy constructs an entirely new value object with the same data as the original.

func (*Value) DBPointer

func (v *Value) DBPointer() (string, types.ObjectID)

DBPointer returns the BSON dbpointer value the Value represents. It panics if the value is a BSON type other than DBPointer.

func (*Value) DBPointerOK

func (v *Value) DBPointerOK() (string, types.ObjectID, bool)

DBPointerOK is the same as DBPoitner, except that it returns a boolean instead of panicking.

func (*Value) DateTime

func (v *Value) DateTime() int64

DateTime returns the BSON datetime value the Value represents as a unix timestamp. It panics if the value is a BSON type other than datetime.

func (*Value) DateTimeOK

func (v *Value) DateTimeOK() (int64, bool)

DateTimeOK is the same as DateTime, except it returns a boolean instead of panicking.

func (*Value) Decimal128

func (v *Value) Decimal128() types.Decimal128

Decimal128 returns the decimal the Value represents. It panics if the value is a BSON type other than decimal.

func (*Value) Decimal128OK

func (v *Value) Decimal128OK() (types.Decimal128, bool)

Decimal128OK is the same as Decimal128, except that it returns a boolean instead of panicking.

func (*Value) Double

func (v *Value) Double() float64

Double returns the float64 value for this element. It panics if e's BSON type is not double ('\x01') or if e is uninitialized.

func (*Value) DoubleOK

func (v *Value) DoubleOK() (float64, bool)

DoubleOK is the same as Double, but returns a boolean instead of panicking.

func (*Value) Equal

func (v *Value) Equal(v2 *Value) bool

Equal compares v to v2 and returns true if they are equal. This method will ensure that the values are logically equal, even if their internal structure is different. This method should be used over reflect.DeepEqual which will not return true for Values that are logically the same but not internally the same.

func (*Value) Int

func (v *Value) Int() int

Int returns a flexible integer value, from an underlying bson value that is either an int32 or an int64. Int() panics if the value is a different type.

func (*Value) Int32

func (v *Value) Int32() int32

Int32 returns the int32 the Value represents. It panics if the value is a BSON type other than int32.

func (*Value) Int32OK

func (v *Value) Int32OK() (int32, bool)

Int32OK is the same as Int32, except that it returns a boolean instead of panicking.

func (*Value) Int64

func (v *Value) Int64() int64

Int64 returns the int64 the Value represents. It panics if the value is a BSON type other than int64.

func (*Value) Int64OK

func (v *Value) Int64OK() (int64, bool)

Int64OK is the same as Int64, except that it returns a boolean instead of panicking.

func (*Value) IntOK

func (v *Value) IntOK() (int, bool)

IntOK returns a flexible integer value from an underlying bson value that is either an int32 or int64. The second value is false when the underlying type is a different type, or the value is invalid.

func (*Value) Interface

func (v *Value) Interface() any

Interface returns the Go value of this Value as an empty interface.

For embedded documents and arrays, Interface will convert the elements to map[string]any or []any as possible.

The underlying types of the values returned by this method are their native corresponding type when possible.

func (*Value) IsEmpty

func (v *Value) IsEmpty() bool

IsEmpty returns true if a value held by a bson type is equivalent to it's empty or zero type. Nil-ish types are all not empty. Nil values are always Empty.

func (*Value) JavaScript

func (v *Value) JavaScript() string

JavaScript returns the BSON JavaScript code value the Value represents. It panics if the value is a BSON type other than JavaScript code.

func (*Value) JavaScriptOK

func (v *Value) JavaScriptOK() (string, bool)

JavaScriptOK is the same as Javascript, excepti that it returns a boolean instead of panicking.

func (*Value) MarshalJSON

func (v *Value) MarshalJSON() ([]byte, error)

func (*Value) MutableArray

func (v *Value) MutableArray() *Array

MutableArray returns the array for this element.

func (*Value) MutableArrayOK

func (v *Value) MutableArrayOK() (*Array, bool)

MutableArrayOK is the same as MutableArray, except it returns a boolean instead of panicking.

func (*Value) MutableDocument

func (v *Value) MutableDocument() *Document

MutableDocument returns the subdocument for this element.

func (*Value) MutableDocumentOK

func (v *Value) MutableDocumentOK() (*Document, bool)

MutableDocumentOK is the same as MutableDocument, except it returns a boolean instead of panicking.

func (*Value) MutableJavaScriptWithScope

func (v *Value) MutableJavaScriptWithScope() (code string, d *Document)

MutableJavaScriptWithScope returns the javascript code and the scope document for this element.

func (*Value) MutableJavaScriptWithScopeOK

func (v *Value) MutableJavaScriptWithScopeOK() (string, *Document, bool)

MutableJavaScriptWithScopeOK is the same as MutableJavascriptWithScope, except that it returns a boolean instead of panicking.

func (*Value) ObjectID

func (v *Value) ObjectID() types.ObjectID

ObjectID returns the BSON objectid value the Value represents. It panics if the value is a BSON type other than objectid.

func (*Value) ObjectIDOK

func (v *Value) ObjectIDOK() (types.ObjectID, bool)

ObjectIDOK is the same as ObjectID, except it returns a boolean instead of panicking.

func (*Value) Reader

func (v *Value) Reader() Reader

Reader returns a reader for the payload of the value regardless of type, panicing only if the value is not initialized or otherwise corrupt.

func (*Value) ReaderArray

func (v *Value) ReaderArray() Reader

ReaderArray returns the BSON document the Value represents as a bson.Reader. It panics if the value is a BSON type other than array.

func (*Value) ReaderArrayOK

func (v *Value) ReaderArrayOK() (Reader, bool)

ReaderArrayOK is the same as ReaderArray, except it returns a boolean instead of panicking.

func (*Value) ReaderDocument

func (v *Value) ReaderDocument() Reader

ReaderDocument returns the BSON document the Value represents as a bson.Reader. It panics if the value is a BSON type other than document.

func (*Value) ReaderDocumentOK

func (v *Value) ReaderDocumentOK() (Reader, bool)

ReaderDocumentOK is the same as ReaderDocument, except it returns a boolean instead of panicking.

func (*Value) ReaderJavaScriptWithScope

func (v *Value) ReaderJavaScriptWithScope() (string, Reader)

ReaderJavaScriptWithScope returns the BSON JavaScript code with scope the Value represents, with the scope being returned as a bson.Reader. It panics if the value is a BSON type other than JavaScript code with scope.

func (*Value) ReaderJavaScriptWithScopeOK

func (v *Value) ReaderJavaScriptWithScopeOK() (string, Reader, bool)

ReaderJavaScriptWithScopeOK is the same as ReaderJavaScriptWithScope, except that it returns a boolean instead of panicking.

func (*Value) Regex

func (v *Value) Regex() (pattern, options string)

Regex returns the BSON regex value the Value represents. It panics if the value is a BSON type other than regex.

func (*Value) Set

func (v *Value) Set(v2 *Value)

Set changes the internal representation of a value to have the internal representation of a second value

func (*Value) StringValue

func (v *Value) StringValue() string

StringValue returns the string balue for this element. It panics if e's BSON type is not StringValue ('\x02') or if e is uninitialized.

NOTE: This method is called StringValue to avoid it implementing the fmt.Stringer interface.

func (*Value) StringValueOK

func (v *Value) StringValueOK() (string, bool)

StringValueOK is the same as StringValue, but returns a boolean instead of panicking.

func (*Value) Symbol

func (v *Value) Symbol() string

Symbol returns the BSON symbol value the Value represents. It panics if the value is a BSON type other than symbol.

func (*Value) Time

func (v *Value) Time() time.Time

Time returns the BSON datetime value the Value represents. It panics if the value is a BSON type other than datetime.

func (*Value) TimeOK

func (v *Value) TimeOK() (time.Time, bool)

TimeOK is the same as Time, except it returns a boolean instead of panicking.

func (*Value) Timestamp

func (v *Value) Timestamp() (uint32, uint32)

Timestamp returns the BSON timestamp value the Value represents. It panics if the value is a BSON type other than timestamp.

func (*Value) TimestampOK

func (v *Value) TimestampOK() (uint32, uint32, bool)

TimestampOK is the same as Timestamp, except that it returns a boolean instead of panicking.

func (*Value) Type

func (v *Value) Type() bsontype.Type

Type returns the identifying element byte for this element. It panics if e is uninitialized.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(in []byte) error

func (*Value) Validate

func (v *Value) Validate() error

Validate validates the value.

type ValueConstructor

type ValueConstructor struct{}

ValueConstructor is used as a namespace for value constructor functions.

VC is a convenience variable provided for access to the ValueConstructor methods.

func (ValueConstructor) Array

func (ValueConstructor) Array(a *Array) *Value

Array creates an array value from the argument.

func (ValueConstructor) ArrayFromValues

func (ValueConstructor) ArrayFromValues(values ...*Value) *Value

ArrayFromValues creates an array element from the given the elements.

func (ValueConstructor) Binary

func (ValueConstructor) Binary(b []byte) *Value

Binary creates a binary value from the argument.

func (ValueConstructor) BinaryWithSubtype

func (ValueConstructor) BinaryWithSubtype(b []byte, btype byte) *Value

BinaryWithSubtype creates a new binary element with the given data and subtype.

func (ValueConstructor) Boolean

func (ValueConstructor) Boolean(b bool) *Value

Boolean creates a boolean value from the argument.

func (ValueConstructor) CodeWithScope

func (ValueConstructor) CodeWithScope(code string, scope *Document) *Value

CodeWithScope creates a JavaScript code with scope value from the arguments.

func (ValueConstructor) DBPointer

func (ValueConstructor) DBPointer(ns string, oid types.ObjectID) *Value

DBPointer creates a dbpointer value from the arguments.

func (ValueConstructor) DateTime

func (ValueConstructor) DateTime(dt int64) *Value

DateTime creates a datetime value from the argument.

func (ValueConstructor) Decimal128

func (ValueConstructor) Decimal128(d types.Decimal128) *Value

Decimal128 creates a decimal value from the argument.

func (ValueConstructor) Document

func (ValueConstructor) Document(d *Document) *Value

Document creates a subdocument value from the argument.

func (ValueConstructor) DocumentFromElements

func (ValueConstructor) DocumentFromElements(elems ...*Element) *Value

DocumentFromElements creates a subdocument element from the given elements.

func (ValueConstructor) DocumentFromReader

func (ValueConstructor) DocumentFromReader(r Reader) *Value

DocumentFromReader creates a subdocument element from the given value.

func (ValueConstructor) DocumentMarshaler

func (ValueConstructor) DocumentMarshaler(in DocumentMarshaler) *Value

func (ValueConstructor) Double

func (ValueConstructor) Double(f float64) *Value

Double creates a double element with the given value.

func (ValueConstructor) Duration

func (ValueConstructor) Duration(t time.Duration) *Value

func (ValueConstructor) Int

func (ValueConstructor) Int(in int) *Value

func (ValueConstructor) Int32

func (ValueConstructor) Int32(i int32) *Value

Int32 creates a int32 value from the argument.

func (ValueConstructor) Int64

func (ValueConstructor) Int64(i int64) *Value

Int64 creates a int64 value from the argument.

func (ValueConstructor) Interface

func (ValueConstructor) Interface(in any) *Value

func (ValueConstructor) JavaScript

func (ValueConstructor) JavaScript(code string) *Value

JavaScript creates a JavaScript code value from the argument.

func (ValueConstructor) MapInterface

func (ValueConstructor) MapInterface(in map[string]any) *Value

func (ValueConstructor) MapInterfaceInterface

func (ValueConstructor) MapInterfaceInterface(in map[any]any) *Value

func (ValueConstructor) MapString

func (ValueConstructor) MapString(in map[string]string) *Value

func (ValueConstructor) Marshaler

func (ValueConstructor) Marshaler(in Marshaler) *Value

func (ValueConstructor) MaxKey

func (ValueConstructor) MaxKey() *Value

MaxKey creates a maxkey value from the argument.

func (ValueConstructor) MinKey

func (ValueConstructor) MinKey() *Value

MinKey creates a minkey value from the argument.

func (ValueConstructor) Null

func (ValueConstructor) Null() *Value

Null creates a null value from the argument.

func (ValueConstructor) ObjectID

func (ValueConstructor) ObjectID(oid types.ObjectID) *Value

ObjectID creates a objectid value from the argument.

func (ValueConstructor) Regex

func (ValueConstructor) Regex(pattern, options string) *Value

Regex creates a regex value from the arguments.

func (ValueConstructor) SliceDuration

func (ValueConstructor) SliceDuration(in []time.Duration) *Value

func (ValueConstructor) SliceFloat32

func (ValueConstructor) SliceFloat32(in []float32) *Value

func (ValueConstructor) SliceFloat64

func (ValueConstructor) SliceFloat64(in []float64) *Value

func (ValueConstructor) SliceInt

func (ValueConstructor) SliceInt(in []int) *Value

func (ValueConstructor) SliceInt32

func (ValueConstructor) SliceInt32(in []int32) *Value

func (ValueConstructor) SliceInt64

func (ValueConstructor) SliceInt64(in []int64) *Value

func (ValueConstructor) SliceInterface

func (ValueConstructor) SliceInterface(in []any) *Value

func (ValueConstructor) SliceString

func (ValueConstructor) SliceString(in []string) *Value

func (ValueConstructor) SliceTime

func (ValueConstructor) SliceTime(in []time.Time) *Value

func (ValueConstructor) String

func (ValueConstructor) String(val string) *Value

String creates a string element with the given value.

func (ValueConstructor) Symbol

func (ValueConstructor) Symbol(symbol string) *Value

Symbol creates a symbol value from the argument.

func (ValueConstructor) Time

func (ValueConstructor) Time(t time.Time) *Value

Time creates a datetime value from the argument.

func (ValueConstructor) Timestamp

func (ValueConstructor) Timestamp(t uint32, i uint32) *Value

Timestamp creates a timestamp value from the arguments.

func (ValueConstructor) Undefined

func (ValueConstructor) Undefined() *Value

Undefined creates a undefined element.

type ValueConstructorError added in v0.2.0

type ValueConstructorError struct{}

func (ValueConstructorError) DocumentMarshaler added in v0.2.0

func (ValueConstructorError) DocumentMarshaler(in DocumentMarshaler) (*Value, error)

func (ValueConstructorError) Interface added in v0.2.0

func (ValueConstructorError) Interface(in any) (*Value, error)

func (ValueConstructorError) MapInterface added in v0.2.0

func (ValueConstructorError) MapInterface(in map[string]any) (*Value, error)

func (ValueConstructorError) Marshaler added in v0.2.0

func (ValueConstructorError) Marshaler(in Marshaler) (*Value, error)

func (ValueConstructorError) SliceInterface added in v0.2.0

func (ValueConstructorError) SliceInterface(in []any) (*Value, error)

Directories

Path Synopsis
Package bsontype is a utility package that contains types for each BSON type and the a stringifier for the Type to enable easier debugging when working with BSON.
Package bsontype is a utility package that contains types for each BSON type and the a stringifier for the Type to enable easier debugging when working with BSON.
Package elements holds the logic to encode and decode the BSON element types from native Go to BSON binary and vice versa.
Package elements holds the logic to encode and decode the BSON element types from native Go to BSON binary and vice versa.
x
ftdc Module
mrpc Module

Jump to

Keyboard shortcuts

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