Skip to content

Commit 91b9075

Browse files
GODRIVER-3071 [master] Correct uint Encoding BSON Documentation (#1516)
Co-authored-by: Preston Vasquez <[email protected]>
1 parent 12a97f7 commit 91b9075

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
@@ -234,3 +234,33 @@ func ExampleEncoder_multipleExtendedJSONDocuments() {
234234
// {"x":{"$numberInt":"3"},"y":{"$numberInt":"4"}}
235235
// {"x":{"$numberInt":"4"},"y":{"$numberInt":"5"}}
236236
}
237+
238+
func ExampleEncoder_IntMinSize() {
239+
// Create an encoder that will marshal integers as the minimum BSON int size
240+
// (either 32 or 64 bits) that can represent the integer value.
241+
type foo struct {
242+
Bar uint32
243+
}
244+
245+
buf := new(bytes.Buffer)
246+
vw, err := bsonrw.NewBSONValueWriter(buf)
247+
if err != nil {
248+
panic(err)
249+
}
250+
251+
enc, err := bson.NewEncoder(vw)
252+
if err != nil {
253+
panic(err)
254+
}
255+
256+
enc.IntMinSize()
257+
258+
err = enc.Encode(foo{2})
259+
if err != nil {
260+
panic(err)
261+
}
262+
263+
fmt.Println(bson.Raw(buf.Bytes()).String())
264+
// Output:
265+
// {"bar": {"$numberInt":"2"}}
266+
}

0 commit comments

Comments
 (0)