diff --git a/README.md b/README.md index bd7104c..63c3268 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,13 @@ [![pkg-img]][pkg-url] [![version-img]][version-url] -BSON for Go. +Package implements BSON encoding and decoding in Go. See https://bsonspec.org/spec.html ## Features * Simple API. * Dependency-free. +* Optimized for speed. * Clean and tested code. See [docs][pkg-url] for more details. diff --git a/bson.go b/bson.go index 4ebc23f..9aacd66 100644 --- a/bson.go +++ b/bson.go @@ -11,7 +11,7 @@ type Marshaler interface { MarshalBSON() ([]byte, error) } -// Marshal returns bencode encoding of v. +// Marshal returns BSON encoding of v. func Marshal(v any) ([]byte, error) { buf := &bytes.Buffer{} if err := NewEncoder(buf).Encode(v); err != nil { @@ -20,6 +20,16 @@ func Marshal(v any) ([]byte, error) { return buf.Bytes(), nil } +// MarshalTo returns BSON encoding of v written to dst. +func MarshalTo(dst []byte, v interface{}) ([]byte, error) { + buf := bytes.NewBuffer(dst) + enc := &Encoder{buf: buf} + if err := enc.marshal(v); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + // Unmarshaler is the interface implemented by types that // can unmarshal a BSON representation of themselves. // diff --git a/example_test.go b/example_test.go index e5c75c2..abe4f1d 100644 --- a/example_test.go +++ b/example_test.go @@ -1,6 +1,11 @@ package bson_test -import "bson" +import ( + "encoding/hex" + "fmt" + + "github.com/cristalhq/bson" +) func Example_types() { arr := bson.A{"a", "b", "c", 12345} @@ -11,3 +16,33 @@ func Example_types() { // Output: } + +func ExampleMarshal() { + arr := bson.A{"a", "b", "c"} + + b, err := bson.Marshal(arr) + if err != nil { + panic(err) + } + + fmt.Println(hex.EncodeToString(b)) + + // Output: + // 2000000002300002000000610002310002000000620002320002000000630000 +} + +func ExampleMarshalTo() { + arr := bson.A{"a", "b", "c"} + + buf := make([]byte, 0, 128) + + buf, err := bson.MarshalTo(buf, arr) + if err != nil { + panic(err) + } + + fmt.Println(hex.EncodeToString(buf)) + + // Output: + // 2000000002300002000000610002310002000000620002320002000000630000 +} diff --git a/go.mod b/go.mod index 1aa38a8..712a449 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module bson +module github.com/cristalhq/bson go 1.18