Skip to content

Commit

Permalink
Rename module and add MarshalTo (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg authored Aug 16, 2023
1 parent d2eda37 commit 287874b
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 4 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 11 additions & 1 deletion bson.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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.
//
Expand Down
37 changes: 36 additions & 1 deletion example_test.go
Original file line number Diff line number Diff line change
@@ -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}
Expand All @@ -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
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module bson
module github.com/cristalhq/bson

go 1.18

0 comments on commit 287874b

Please sign in to comment.