|
| 1 | +// Copyright (C) MongoDB, Inc. 2017-present. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | +// not use this file except in compliance with the License. You may obtain |
| 5 | +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + |
| 7 | +package bsoncodec |
| 8 | + |
| 9 | +import ( |
| 10 | + "fmt" |
| 11 | + "reflect" |
| 12 | + "strconv" |
| 13 | + |
| 14 | + "go.mongodb.org/mongo-driver/bson/bsonoptions" |
| 15 | + "go.mongodb.org/mongo-driver/bson/bsonrw" |
| 16 | + "go.mongodb.org/mongo-driver/bson/bsontype" |
| 17 | +) |
| 18 | + |
| 19 | +var defaultMapCodec = NewMapCodec() |
| 20 | + |
| 21 | +// MapCodec is the Codec used for map values. |
| 22 | +type MapCodec struct { |
| 23 | + DecodeZerosMap bool |
| 24 | +} |
| 25 | + |
| 26 | +var _ ValueCodec = &MapCodec{} |
| 27 | + |
| 28 | +// NewMapCodec returns a MapCodec with options opts. |
| 29 | +func NewMapCodec(opts ...*bsonoptions.MapCodecOptions) *MapCodec { |
| 30 | + mapOpt := bsonoptions.MergeMapCodecOptions(opts...) |
| 31 | + |
| 32 | + codec := MapCodec{} |
| 33 | + if mapOpt.DecodeZerosMap != nil { |
| 34 | + codec.DecodeZerosMap = *mapOpt.DecodeZerosMap |
| 35 | + } |
| 36 | + return &codec |
| 37 | +} |
| 38 | + |
| 39 | +// EncodeValue is the ValueEncoder for map[*]* types. |
| 40 | +func (mc *MapCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { |
| 41 | + if !val.IsValid() || val.Kind() != reflect.Map { |
| 42 | + return ValueEncoderError{Name: "MapEncodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} |
| 43 | + } |
| 44 | + |
| 45 | + if val.IsNil() { |
| 46 | + // If we have a nil map but we can't WriteNull, that means we're probably trying to encode |
| 47 | + // to a TopLevel document. We can't currently tell if this is what actually happened, but if |
| 48 | + // there's a deeper underlying problem, the error will also be returned from WriteDocument, |
| 49 | + // so just continue. The operations on a map reflection value are valid, so we can call |
| 50 | + // MapKeys within mapEncodeValue without a problem. |
| 51 | + err := vw.WriteNull() |
| 52 | + if err == nil { |
| 53 | + return nil |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + dw, err := vw.WriteDocument() |
| 58 | + if err != nil { |
| 59 | + return err |
| 60 | + } |
| 61 | + |
| 62 | + return mc.mapEncodeValue(ec, dw, val, nil) |
| 63 | +} |
| 64 | + |
| 65 | +// mapEncodeValue handles encoding of the values of a map. The collisionFn returns |
| 66 | +// true if the provided key exists, this is mainly used for inline maps in the |
| 67 | +// struct codec. |
| 68 | +func (mc *MapCodec) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, val reflect.Value, collisionFn func(string) bool) error { |
| 69 | + |
| 70 | + elemType := val.Type().Elem() |
| 71 | + encoder, err := ec.LookupEncoder(elemType) |
| 72 | + if err != nil && elemType.Kind() != reflect.Interface { |
| 73 | + return err |
| 74 | + } |
| 75 | + |
| 76 | + keys := val.MapKeys() |
| 77 | + for _, key := range keys { |
| 78 | + keyStr := fmt.Sprint(key) |
| 79 | + if collisionFn != nil && collisionFn(keyStr) { |
| 80 | + return fmt.Errorf("Key %s of inlined map conflicts with a struct field name", key) |
| 81 | + } |
| 82 | + |
| 83 | + currEncoder, currVal, lookupErr := defaultValueEncoders.lookupElementEncoder(ec, encoder, val.MapIndex(key)) |
| 84 | + if lookupErr != nil && lookupErr != errInvalidValue { |
| 85 | + return lookupErr |
| 86 | + } |
| 87 | + |
| 88 | + vw, err := dw.WriteDocumentElement(key.String()) |
| 89 | + if err != nil { |
| 90 | + return err |
| 91 | + } |
| 92 | + |
| 93 | + if lookupErr == errInvalidValue { |
| 94 | + err = vw.WriteNull() |
| 95 | + if err != nil { |
| 96 | + return err |
| 97 | + } |
| 98 | + continue |
| 99 | + } |
| 100 | + |
| 101 | + if enc, ok := currEncoder.(ValueEncoder); ok { |
| 102 | + err = enc.EncodeValue(ec, vw, currVal) |
| 103 | + if err != nil { |
| 104 | + return err |
| 105 | + } |
| 106 | + continue |
| 107 | + } |
| 108 | + err = encoder.EncodeValue(ec, vw, currVal) |
| 109 | + if err != nil { |
| 110 | + return err |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + return dw.WriteDocumentEnd() |
| 115 | +} |
| 116 | + |
| 117 | +// DecodeValue is the ValueDecoder for map[string/decimal]* types. |
| 118 | +func (mc *MapCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { |
| 119 | + if (!val.CanSet() && val.IsNil()) || val.Kind() != reflect.Map { |
| 120 | + return ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} |
| 121 | + } |
| 122 | + |
| 123 | + switch vr.Type() { |
| 124 | + case bsontype.Type(0), bsontype.EmbeddedDocument: |
| 125 | + case bsontype.Null: |
| 126 | + val.Set(reflect.Zero(val.Type())) |
| 127 | + return vr.ReadNull() |
| 128 | + default: |
| 129 | + return fmt.Errorf("cannot decode %v into a %s", vr.Type(), val.Type()) |
| 130 | + } |
| 131 | + |
| 132 | + dr, err := vr.ReadDocument() |
| 133 | + if err != nil { |
| 134 | + return err |
| 135 | + } |
| 136 | + |
| 137 | + if val.IsNil() { |
| 138 | + val.Set(reflect.MakeMap(val.Type())) |
| 139 | + } |
| 140 | + |
| 141 | + if val.Len() > 0 && mc.DecodeZerosMap { |
| 142 | + clearMap(val) |
| 143 | + } |
| 144 | + |
| 145 | + eType := val.Type().Elem() |
| 146 | + decoder, err := dc.LookupDecoder(eType) |
| 147 | + if err != nil { |
| 148 | + return err |
| 149 | + } |
| 150 | + |
| 151 | + if eType == tEmpty { |
| 152 | + dc.Ancestor = val.Type() |
| 153 | + } |
| 154 | + |
| 155 | + keyType := val.Type().Key() |
| 156 | + keyKind := keyType.Kind() |
| 157 | + |
| 158 | + for { |
| 159 | + key, vr, err := dr.ReadElement() |
| 160 | + if err == bsonrw.ErrEOD { |
| 161 | + break |
| 162 | + } |
| 163 | + if err != nil { |
| 164 | + return err |
| 165 | + } |
| 166 | + |
| 167 | + elem := reflect.New(eType).Elem() |
| 168 | + |
| 169 | + err = decoder.DecodeValue(dc, vr, elem) |
| 170 | + if err != nil { |
| 171 | + return err |
| 172 | + } |
| 173 | + |
| 174 | + k := reflect.ValueOf(key) |
| 175 | + if keyType != tString { |
| 176 | + switch keyKind { |
| 177 | + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, |
| 178 | + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, |
| 179 | + reflect.Float32, reflect.Float64: |
| 180 | + parsed, err := strconv.ParseFloat(k.String(), 64) |
| 181 | + if err != nil { |
| 182 | + return fmt.Errorf("Map key is defined to be a decimal type (%v) but got error %v", keyKind, err) |
| 183 | + } |
| 184 | + k = reflect.ValueOf(parsed) |
| 185 | + case reflect.String: // if keyType wraps string |
| 186 | + default: |
| 187 | + return fmt.Errorf("BSON map must have string or decimal keys. Got:%v", val) |
| 188 | + } |
| 189 | + |
| 190 | + k = k.Convert(keyType) |
| 191 | + } |
| 192 | + |
| 193 | + val.SetMapIndex(k, elem) |
| 194 | + } |
| 195 | + return nil |
| 196 | +} |
| 197 | + |
| 198 | +func clearMap(m reflect.Value) { |
| 199 | + var none reflect.Value |
| 200 | + for _, k := range m.MapKeys() { |
| 201 | + m.SetMapIndex(k, none) |
| 202 | + } |
| 203 | +} |
0 commit comments