Skip to content

Commit

Permalink
GODRIVER-3071 Correct uint Encoding BSON Documentation (#1500)
Browse files Browse the repository at this point in the history
Co-authored-by: Matt Dale <[email protected]>
  • Loading branch information
2 people authored and qingyang-hu committed Feb 12, 2024
1 parent 452780c commit d35e8de
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
5 changes: 2 additions & 3 deletions bson/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,9 @@
// 2. int8, int16, and int32 marshal to a BSON int32.
// 3. int marshals to a BSON int32 if the value is between math.MinInt32 and math.MaxInt32, inclusive, and a BSON int64
// otherwise.
// 4. int64 marshals to BSON int64.
// 4. int64 marshals to BSON int64 (unless [Encoder.IntMinSize] is set).
// 5. uint8 and uint16 marshal to a BSON int32.
// 6. uint, uint32, and uint64 marshal to a BSON int32 if the value is between math.MinInt32 and math.MaxInt32,
// inclusive, and BSON int64 otherwise.
// 6. uint, uint32, and uint64 marshal to a BSON int64 (unless [Encoder.IntMinSize] is set).
// 7. BSON null and undefined values will unmarshal into the zero value of a field (e.g. unmarshalling a BSON null or
// undefined value into a string will yield the empty string.).
//
Expand Down
30 changes: 30 additions & 0 deletions bson/encoder_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,33 @@ func ExampleEncoder_multipleExtendedJSONDocuments() {
// {"x":{"$numberInt":"3"},"y":{"$numberInt":"4"}}
// {"x":{"$numberInt":"4"},"y":{"$numberInt":"5"}}
}

func ExampleEncoder_IntMinSize() {
// Create an encoder that will marshal integers as the minimum BSON int size
// (either 32 or 64 bits) that can represent the integer value.
type foo struct {
Bar uint32
}

buf := new(bytes.Buffer)
vw, err := bsonrw.NewBSONValueWriter(buf)
if err != nil {
panic(err)
}

enc, err := bson.NewEncoder(vw)
if err != nil {
panic(err)
}

enc.IntMinSize()

err = enc.Encode(foo{2})
if err != nil {
panic(err)
}

fmt.Println(bson.Raw(buf.Bytes()).String())
// Output:
// {"bar": {"$numberInt":"2"}}
}

0 comments on commit d35e8de

Please sign in to comment.