diff --git a/bson/doc.go b/bson/doc.go index 048b5eb998..05e33a4412 100644 --- a/bson/doc.go +++ b/bson/doc.go @@ -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.). // diff --git a/bson/encoder_example_test.go b/bson/encoder_example_test.go index b52e999d45..057011548b 100644 --- a/bson/encoder_example_test.go +++ b/bson/encoder_example_test.go @@ -252,3 +252,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"}} +}