Skip to content

Commit 6740ce0

Browse files
GODRIVER-3071 Correct uint Encoding BSON Documentation (#1500)
Co-authored-by: Matt Dale <[email protected]>
1 parent c1b1a4f commit 6740ce0

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

0 commit comments

Comments
 (0)