Skip to content

Commit d35e8de

Browse files
prestonvasquezmatthewdale
authored andcommitted
GODRIVER-3071 Correct uint Encoding BSON Documentation (#1500)
Co-authored-by: Matt Dale <[email protected]>
1 parent 452780c commit d35e8de

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

bson/doc.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,9 @@
6868
// 2. int8, int16, and int32 marshal to a BSON int32.
6969
// 3. int marshals to a BSON int32 if the value is between math.MinInt32 and math.MaxInt32, inclusive, and a BSON int64
7070
// otherwise.
71-
// 4. int64 marshals to BSON int64.
71+
// 4. int64 marshals to BSON int64 (unless [Encoder.IntMinSize] is set).
7272
// 5. uint8 and uint16 marshal to a BSON int32.
73-
// 6. uint, uint32, and uint64 marshal to a BSON int32 if the value is between math.MinInt32 and math.MaxInt32,
74-
// inclusive, and BSON int64 otherwise.
73+
// 6. uint, uint32, and uint64 marshal to a BSON int64 (unless [Encoder.IntMinSize] is set).
7574
// 7. BSON null and undefined values will unmarshal into the zero value of a field (e.g. unmarshalling a BSON null or
7675
// undefined value into a string will yield the empty string.).
7776
//

bson/encoder_example_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,3 +251,33 @@ func ExampleEncoder_multipleExtendedJSONDocuments() {
251251
// {"x":{"$numberInt":"3"},"y":{"$numberInt":"4"}}
252252
// {"x":{"$numberInt":"4"},"y":{"$numberInt":"5"}}
253253
}
254+
255+
func ExampleEncoder_IntMinSize() {
256+
// Create an encoder that will marshal integers as the minimum BSON int size
257+
// (either 32 or 64 bits) that can represent the integer value.
258+
type foo struct {
259+
Bar uint32
260+
}
261+
262+
buf := new(bytes.Buffer)
263+
vw, err := bsonrw.NewBSONValueWriter(buf)
264+
if err != nil {
265+
panic(err)
266+
}
267+
268+
enc, err := bson.NewEncoder(vw)
269+
if err != nil {
270+
panic(err)
271+
}
272+
273+
enc.IntMinSize()
274+
275+
err = enc.Encode(foo{2})
276+
if err != nil {
277+
panic(err)
278+
}
279+
280+
fmt.Println(bson.Raw(buf.Bytes()).String())
281+
// Output:
282+
// {"bar": {"$numberInt":"2"}}
283+
}

0 commit comments

Comments
 (0)