11package mbson
22
33import (
4- "fmt"
5-
64 "github.com/pkg/errors"
7- "github.com/samber/lo"
85 "go.mongodb.org/mongo-driver/bson"
9- "go.mongodb.org/mongo-driver/bson/bsontype"
106 "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
117)
128
13- // DefaultShortLogLength is a useful default value to pass to ShortenForLogging.
14- const DefaultShortLogLength = 256
15-
169// RawLookup combines bson.Raw’s LookupErr method with an additional
1710// unmarshal step. The result is a convenient way to extract values from
1811// bson.Raw. The returned boolean indicates whether the value was found.
@@ -34,45 +27,3 @@ func RawContains(doc bson.Raw, keys ...string) (bool, error) {
3427 val := any (nil )
3528 return RawLookup (doc , & val , keys ... )
3629}
37-
38- // GetTypes returns the types of bson.RawValues.
39- func GetTypes (vals []bson.RawValue ) []bsontype.Type {
40- return lo .Map (
41- vals ,
42- func (v bson.RawValue , _ int ) bsontype.Type {
43- return v .Type
44- },
45- )
46- }
47-
48- // ShortenForLogging is meant for use where we need to log the raw BSON
49- // bytes for debugging, but don't want to spew enormous amounts of binary data
50- // to logs. It returns a byte slice of at most maxLength bytes. Note that this might
51- // not return valid BSON!
52- func ShortenForLogging (raw bson.Raw , maxLength int ) []byte {
53- toLog := make ([]byte , maxLength )
54- n := copy (toLog , raw )
55- return toLog [0 :n ]
56- }
57-
58- // ConvertToRawValue converts the specified argument to a bson.RawValue. It panics if it can't be marshaled.
59- func ConvertToRawValue (thing any ) bson.RawValue {
60- t , val , err := bson .MarshalValue (thing )
61- if err != nil {
62- panic (err )
63- }
64- return bson.RawValue {
65- Type : t ,
66- Value : val ,
67- }
68- }
69-
70- // MustMarshal marshals the given value to BSON.
71- // It panics if the marshaling fails.
72- func MustMarshal (val any ) bson.Raw {
73- raw , err := bson .Marshal (val )
74- if err != nil {
75- panic (fmt .Sprintf ("failed to marshal %T (%v) to BSON: %v" , val , val , err ))
76- }
77- return raw
78- }
0 commit comments