unmarshaler.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. package mapping
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "strings"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "github.com/tal-tech/go-zero/core/jsonx"
  12. "github.com/tal-tech/go-zero/core/lang"
  13. "github.com/tal-tech/go-zero/core/stringx"
  14. )
  15. const (
  16. defaultKeyName = "key"
  17. delimiter = '.'
  18. )
  19. var (
  20. errTypeMismatch = errors.New("type mismatch")
  21. errValueNotSettable = errors.New("value is not settable")
  22. errValueNotStruct = errors.New("value type is not struct")
  23. keyUnmarshaler = NewUnmarshaler(defaultKeyName)
  24. cacheKeys atomic.Value
  25. cacheKeysLock sync.Mutex
  26. durationType = reflect.TypeOf(time.Duration(0))
  27. emptyMap = map[string]interface{}{}
  28. emptyValue = reflect.ValueOf(lang.Placeholder)
  29. )
  30. type (
  31. Unmarshaler struct {
  32. key string
  33. opts unmarshalOptions
  34. }
  35. unmarshalOptions struct {
  36. fromString bool
  37. }
  38. keyCache map[string][]string
  39. UnmarshalOption func(*unmarshalOptions)
  40. )
  41. func init() {
  42. cacheKeys.Store(make(keyCache))
  43. }
  44. func NewUnmarshaler(key string, opts ...UnmarshalOption) *Unmarshaler {
  45. unmarshaler := Unmarshaler{
  46. key: key,
  47. }
  48. for _, opt := range opts {
  49. opt(&unmarshaler.opts)
  50. }
  51. return &unmarshaler
  52. }
  53. func UnmarshalKey(m map[string]interface{}, v interface{}) error {
  54. return keyUnmarshaler.Unmarshal(m, v)
  55. }
  56. func (u *Unmarshaler) Unmarshal(m map[string]interface{}, v interface{}) error {
  57. return u.UnmarshalValuer(MapValuer(m), v)
  58. }
  59. func (u *Unmarshaler) UnmarshalValuer(m Valuer, v interface{}) error {
  60. return u.unmarshalWithFullName(m, v, "")
  61. }
  62. func (u *Unmarshaler) unmarshalWithFullName(m Valuer, v interface{}, fullName string) error {
  63. rv := reflect.ValueOf(v)
  64. if err := ValidatePtr(&rv); err != nil {
  65. return err
  66. }
  67. rte := reflect.TypeOf(v).Elem()
  68. if rte.Kind() != reflect.Struct {
  69. return errValueNotStruct
  70. }
  71. rve := rv.Elem()
  72. numFields := rte.NumField()
  73. for i := 0; i < numFields; i++ {
  74. field := rte.Field(i)
  75. if usingDifferentKeys(u.key, field) {
  76. continue
  77. }
  78. if err := u.processField(field, rve.Field(i), m, fullName); err != nil {
  79. return err
  80. }
  81. }
  82. return nil
  83. }
  84. func (u *Unmarshaler) processAnonymousField(field reflect.StructField, value reflect.Value,
  85. m Valuer, fullName string) error {
  86. key, options, err := u.parseOptionsWithContext(field, m, fullName)
  87. if err != nil {
  88. return err
  89. }
  90. if _, hasValue := getValue(m, key); hasValue {
  91. return fmt.Errorf("fields of %s can't be wrapped inside, because it's anonymous", key)
  92. }
  93. if options.optional() {
  94. return u.processAnonymousFieldOptional(field, value, key, m, fullName)
  95. }
  96. return u.processAnonymousFieldRequired(field, value, m, fullName)
  97. }
  98. func (u *Unmarshaler) processAnonymousFieldOptional(field reflect.StructField, value reflect.Value,
  99. key string, m Valuer, fullName string) error {
  100. var filled bool
  101. var required int
  102. var requiredFilled int
  103. var indirectValue reflect.Value
  104. fieldType := Deref(field.Type)
  105. for i := 0; i < fieldType.NumField(); i++ {
  106. subField := fieldType.Field(i)
  107. fieldKey, fieldOpts, err := u.parseOptionsWithContext(subField, m, fullName)
  108. if err != nil {
  109. return err
  110. }
  111. _, hasValue := getValue(m, fieldKey)
  112. if hasValue {
  113. if !filled {
  114. filled = true
  115. maybeNewValue(field, value)
  116. indirectValue = reflect.Indirect(value)
  117. }
  118. if err = u.processField(subField, indirectValue.Field(i), m, fullName); err != nil {
  119. return err
  120. }
  121. }
  122. if !fieldOpts.optional() {
  123. required++
  124. if hasValue {
  125. requiredFilled++
  126. }
  127. }
  128. }
  129. if filled && required != requiredFilled {
  130. return fmt.Errorf("%s is not fully set", key)
  131. }
  132. return nil
  133. }
  134. func (u *Unmarshaler) processAnonymousFieldRequired(field reflect.StructField, value reflect.Value,
  135. m Valuer, fullName string) error {
  136. maybeNewValue(field, value)
  137. fieldType := Deref(field.Type)
  138. indirectValue := reflect.Indirect(value)
  139. for i := 0; i < fieldType.NumField(); i++ {
  140. if err := u.processField(fieldType.Field(i), indirectValue.Field(i), m, fullName); err != nil {
  141. return err
  142. }
  143. }
  144. return nil
  145. }
  146. func (u *Unmarshaler) processField(field reflect.StructField, value reflect.Value, m Valuer,
  147. fullName string) error {
  148. if usingDifferentKeys(u.key, field) {
  149. return nil
  150. }
  151. if field.Anonymous {
  152. return u.processAnonymousField(field, value, m, fullName)
  153. }
  154. return u.processNamedField(field, value, m, fullName)
  155. }
  156. func (u *Unmarshaler) processFieldNotFromString(field reflect.StructField, value reflect.Value,
  157. mapValue interface{}, opts *fieldOptionsWithContext, fullName string) error {
  158. fieldType := field.Type
  159. derefedFieldType := Deref(fieldType)
  160. typeKind := derefedFieldType.Kind()
  161. valueKind := reflect.TypeOf(mapValue).Kind()
  162. switch {
  163. case valueKind == reflect.Map && typeKind == reflect.Struct:
  164. return u.processFieldStruct(field, value, mapValue, fullName)
  165. case valueKind == reflect.String && typeKind == reflect.Slice:
  166. return u.fillSliceFromString(fieldType, value, mapValue)
  167. case valueKind == reflect.String && derefedFieldType == durationType:
  168. return fillDurationValue(fieldType.Kind(), value, mapValue.(string))
  169. default:
  170. return u.processFieldPrimitive(field, value, mapValue, opts, fullName)
  171. }
  172. }
  173. func (u *Unmarshaler) processFieldPrimitive(field reflect.StructField, value reflect.Value,
  174. mapValue interface{}, opts *fieldOptionsWithContext, fullName string) error {
  175. fieldType := field.Type
  176. typeKind := Deref(fieldType).Kind()
  177. valueKind := reflect.TypeOf(mapValue).Kind()
  178. switch {
  179. case typeKind == reflect.Slice && valueKind == reflect.Slice:
  180. return u.fillSlice(fieldType, value, mapValue)
  181. case typeKind == reflect.Map && valueKind == reflect.Map:
  182. return u.fillMap(field, value, mapValue)
  183. default:
  184. switch v := mapValue.(type) {
  185. case json.Number:
  186. return u.processFieldPrimitiveWithJsonNumber(field, value, v, opts, fullName)
  187. default:
  188. if typeKind == valueKind {
  189. if err := validateValueInOptions(opts.options(), mapValue); err != nil {
  190. return err
  191. }
  192. return fillWithSameType(field, value, mapValue, opts)
  193. }
  194. }
  195. }
  196. return newTypeMismatchError(fullName)
  197. }
  198. func (u *Unmarshaler) processFieldPrimitiveWithJsonNumber(field reflect.StructField, value reflect.Value,
  199. v json.Number, opts *fieldOptionsWithContext, fullName string) error {
  200. fieldType := field.Type
  201. fieldKind := fieldType.Kind()
  202. typeKind := Deref(fieldType).Kind()
  203. if err := validateJsonNumberRange(v, opts); err != nil {
  204. return err
  205. }
  206. if fieldKind == reflect.Ptr {
  207. value = value.Elem()
  208. }
  209. switch typeKind {
  210. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  211. iValue, err := v.Int64()
  212. if err != nil {
  213. return err
  214. }
  215. value.SetInt(iValue)
  216. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  217. iValue, err := v.Int64()
  218. if err != nil {
  219. return err
  220. }
  221. value.SetUint(uint64(iValue))
  222. case reflect.Float32, reflect.Float64:
  223. fValue, err := v.Float64()
  224. if err != nil {
  225. return err
  226. }
  227. value.SetFloat(fValue)
  228. default:
  229. return newTypeMismatchError(fullName)
  230. }
  231. return nil
  232. }
  233. func (u *Unmarshaler) processFieldStruct(field reflect.StructField, value reflect.Value,
  234. mapValue interface{}, fullName string) error {
  235. convertedValue, ok := mapValue.(map[string]interface{})
  236. if !ok {
  237. valueKind := reflect.TypeOf(mapValue).Kind()
  238. return fmt.Errorf("error: field: %s, expect map[string]interface{}, actual %v", fullName, valueKind)
  239. }
  240. return u.processFieldStructWithMap(field, value, MapValuer(convertedValue), fullName)
  241. }
  242. func (u *Unmarshaler) processFieldStructWithMap(field reflect.StructField, value reflect.Value,
  243. m Valuer, fullName string) error {
  244. if field.Type.Kind() == reflect.Ptr {
  245. baseType := Deref(field.Type)
  246. target := reflect.New(baseType).Elem()
  247. if err := u.unmarshalWithFullName(m, target.Addr().Interface(), fullName); err != nil {
  248. return err
  249. }
  250. value.Set(target.Addr())
  251. } else if err := u.unmarshalWithFullName(m, value.Addr().Interface(), fullName); err != nil {
  252. return err
  253. }
  254. return nil
  255. }
  256. func (u *Unmarshaler) processNamedField(field reflect.StructField, value reflect.Value,
  257. m Valuer, fullName string) error {
  258. key, opts, err := u.parseOptionsWithContext(field, m, fullName)
  259. if err != nil {
  260. return err
  261. }
  262. fullName = join(fullName, key)
  263. mapValue, hasValue := getValue(m, key)
  264. if hasValue {
  265. return u.processNamedFieldWithValue(field, value, mapValue, key, opts, fullName)
  266. }
  267. return u.processNamedFieldWithoutValue(field, value, opts, fullName)
  268. }
  269. func (u *Unmarshaler) processNamedFieldWithValue(field reflect.StructField, value reflect.Value,
  270. mapValue interface{}, key string, opts *fieldOptionsWithContext, fullName string) error {
  271. if mapValue == nil {
  272. if opts.optional() {
  273. return nil
  274. }
  275. return fmt.Errorf("field %s mustn't be nil", key)
  276. }
  277. maybeNewValue(field, value)
  278. fieldKind := Deref(field.Type).Kind()
  279. switch fieldKind {
  280. case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct:
  281. return u.processFieldNotFromString(field, value, mapValue, opts, fullName)
  282. default:
  283. if u.opts.fromString || opts.fromString() {
  284. valueKind := reflect.TypeOf(mapValue).Kind()
  285. if valueKind != reflect.String {
  286. return fmt.Errorf("error: the value in map is not string, but %s", valueKind)
  287. }
  288. options := opts.options()
  289. if len(options) > 0 {
  290. if !stringx.Contains(options, mapValue.(string)) {
  291. return fmt.Errorf(`error: value "%s" for field "%s" is not defined in options "%v"`,
  292. mapValue, key, options)
  293. }
  294. }
  295. return fillPrimitive(field.Type, value, mapValue, opts, fullName)
  296. }
  297. return u.processFieldNotFromString(field, value, mapValue, opts, fullName)
  298. }
  299. }
  300. func (u *Unmarshaler) processNamedFieldWithoutValue(field reflect.StructField, value reflect.Value,
  301. opts *fieldOptionsWithContext, fullName string) error {
  302. derefedType := Deref(field.Type)
  303. fieldKind := derefedType.Kind()
  304. if defaultValue, ok := opts.getDefault(); ok {
  305. if field.Type.Kind() == reflect.Ptr {
  306. maybeNewValue(field, value)
  307. value = value.Elem()
  308. }
  309. if derefedType == durationType {
  310. return fillDurationValue(fieldKind, value, defaultValue)
  311. }
  312. return setValue(fieldKind, value, defaultValue)
  313. }
  314. switch fieldKind {
  315. case reflect.Array, reflect.Map, reflect.Slice:
  316. if !opts.optional() {
  317. return u.processFieldNotFromString(field, value, emptyMap, opts, fullName)
  318. }
  319. case reflect.Struct:
  320. if !opts.optional() {
  321. required, err := structValueRequired(u.key, derefedType)
  322. if err != nil {
  323. return err
  324. }
  325. if required {
  326. return fmt.Errorf("%q is not set", fullName)
  327. }
  328. return u.processFieldNotFromString(field, value, emptyMap, opts, fullName)
  329. }
  330. default:
  331. if !opts.optional() {
  332. return newInitError(fullName)
  333. }
  334. }
  335. return nil
  336. }
  337. func (u *Unmarshaler) fillMap(field reflect.StructField, value reflect.Value, mapValue interface{}) error {
  338. if !value.CanSet() {
  339. return errValueNotSettable
  340. }
  341. fieldKeyType := field.Type.Key()
  342. fieldElemType := field.Type.Elem()
  343. targetValue, err := u.generateMap(fieldKeyType, fieldElemType, mapValue)
  344. if err != nil {
  345. return err
  346. }
  347. value.Set(targetValue)
  348. return nil
  349. }
  350. func (u *Unmarshaler) fillSlice(fieldType reflect.Type, value reflect.Value, mapValue interface{}) error {
  351. if !value.CanSet() {
  352. return errValueNotSettable
  353. }
  354. baseType := fieldType.Elem()
  355. baseKind := baseType.Kind()
  356. dereffedBaseType := Deref(baseType)
  357. dereffedBaseKind := dereffedBaseType.Kind()
  358. refValue := reflect.ValueOf(mapValue)
  359. conv := reflect.MakeSlice(reflect.SliceOf(baseType), refValue.Len(), refValue.Cap())
  360. var valid bool
  361. for i := 0; i < refValue.Len(); i++ {
  362. ithValue := refValue.Index(i).Interface()
  363. if ithValue == nil {
  364. continue
  365. }
  366. valid = true
  367. switch dereffedBaseKind {
  368. case reflect.Struct:
  369. target := reflect.New(dereffedBaseType)
  370. if err := u.Unmarshal(ithValue.(map[string]interface{}), target.Interface()); err != nil {
  371. return err
  372. }
  373. if baseKind == reflect.Ptr {
  374. conv.Index(i).Set(target)
  375. } else {
  376. conv.Index(i).Set(target.Elem())
  377. }
  378. default:
  379. if err := u.fillSliceValue(conv, i, dereffedBaseKind, ithValue); err != nil {
  380. return err
  381. }
  382. }
  383. }
  384. if valid {
  385. value.Set(conv)
  386. }
  387. return nil
  388. }
  389. func (u *Unmarshaler) fillSliceFromString(fieldType reflect.Type, value reflect.Value, mapValue interface{}) error {
  390. var slice []interface{}
  391. if err := jsonx.UnmarshalFromString(mapValue.(string), &slice); err != nil {
  392. return err
  393. }
  394. baseFieldType := Deref(fieldType.Elem())
  395. baseFieldKind := baseFieldType.Kind()
  396. conv := reflect.MakeSlice(reflect.SliceOf(baseFieldType), len(slice), cap(slice))
  397. for i := 0; i < len(slice); i++ {
  398. if err := u.fillSliceValue(conv, i, baseFieldKind, slice[i]); err != nil {
  399. return err
  400. }
  401. }
  402. value.Set(conv)
  403. return nil
  404. }
  405. func (u *Unmarshaler) fillSliceValue(slice reflect.Value, index int, baseKind reflect.Kind, value interface{}) error {
  406. switch v := value.(type) {
  407. case json.Number:
  408. return setValue(baseKind, slice.Index(index), v.String())
  409. default:
  410. // don't need to consider the difference between int, int8, int16, int32, int64,
  411. // uint, uint8, uint16, uint32, uint64, because they're handled as json.Number.
  412. if slice.Index(index).Kind() != reflect.TypeOf(value).Kind() {
  413. return errTypeMismatch
  414. }
  415. slice.Index(index).Set(reflect.ValueOf(value))
  416. return nil
  417. }
  418. }
  419. func (u *Unmarshaler) generateMap(keyType, elemType reflect.Type, mapValue interface{}) (reflect.Value, error) {
  420. mapType := reflect.MapOf(keyType, elemType)
  421. valueType := reflect.TypeOf(mapValue)
  422. if mapType == valueType {
  423. return reflect.ValueOf(mapValue), nil
  424. }
  425. refValue := reflect.ValueOf(mapValue)
  426. targetValue := reflect.MakeMapWithSize(mapType, refValue.Len())
  427. fieldElemKind := elemType.Kind()
  428. dereffedElemType := Deref(elemType)
  429. dereffedElemKind := dereffedElemType.Kind()
  430. for _, key := range refValue.MapKeys() {
  431. keythValue := refValue.MapIndex(key)
  432. keythData := keythValue.Interface()
  433. switch dereffedElemKind {
  434. case reflect.Slice:
  435. target := reflect.New(dereffedElemType)
  436. if err := u.fillSlice(elemType, target.Elem(), keythData); err != nil {
  437. return emptyValue, err
  438. }
  439. targetValue.SetMapIndex(key, target.Elem())
  440. case reflect.Struct:
  441. keythMap, ok := keythData.(map[string]interface{})
  442. if !ok {
  443. return emptyValue, errTypeMismatch
  444. }
  445. target := reflect.New(dereffedElemType)
  446. if err := u.Unmarshal(keythMap, target.Interface()); err != nil {
  447. return emptyValue, err
  448. }
  449. if fieldElemKind == reflect.Ptr {
  450. targetValue.SetMapIndex(key, target)
  451. } else {
  452. targetValue.SetMapIndex(key, target.Elem())
  453. }
  454. case reflect.Map:
  455. keythMap, ok := keythData.(map[string]interface{})
  456. if !ok {
  457. return emptyValue, errTypeMismatch
  458. }
  459. innerValue, err := u.generateMap(elemType.Key(), elemType.Elem(), keythMap)
  460. if err != nil {
  461. return emptyValue, err
  462. }
  463. targetValue.SetMapIndex(key, innerValue)
  464. default:
  465. switch v := keythData.(type) {
  466. case string:
  467. targetValue.SetMapIndex(key, reflect.ValueOf(v))
  468. case json.Number:
  469. target := reflect.New(dereffedElemType)
  470. if err := setValue(dereffedElemKind, target.Elem(), v.String()); err != nil {
  471. return emptyValue, err
  472. }
  473. targetValue.SetMapIndex(key, target.Elem())
  474. default:
  475. targetValue.SetMapIndex(key, keythValue)
  476. }
  477. }
  478. }
  479. return targetValue, nil
  480. }
  481. func (u *Unmarshaler) parseOptionsWithContext(field reflect.StructField, m Valuer, fullName string) (
  482. string, *fieldOptionsWithContext, error) {
  483. key, options, err := parseKeyAndOptions(u.key, field)
  484. if err != nil {
  485. return "", nil, err
  486. } else if options == nil {
  487. return key, nil, nil
  488. }
  489. optsWithContext, err := options.toOptionsWithContext(key, m, fullName)
  490. if err != nil {
  491. return "", nil, err
  492. }
  493. return key, optsWithContext, nil
  494. }
  495. func WithStringValues() UnmarshalOption {
  496. return func(opt *unmarshalOptions) {
  497. opt.fromString = true
  498. }
  499. }
  500. func fillDurationValue(fieldKind reflect.Kind, value reflect.Value, dur string) error {
  501. d, err := time.ParseDuration(dur)
  502. if err != nil {
  503. return err
  504. }
  505. if fieldKind == reflect.Ptr {
  506. value.Elem().Set(reflect.ValueOf(d))
  507. } else {
  508. value.Set(reflect.ValueOf(d))
  509. }
  510. return nil
  511. }
  512. func fillPrimitive(fieldType reflect.Type, value reflect.Value, mapValue interface{},
  513. opts *fieldOptionsWithContext, fullName string) error {
  514. if !value.CanSet() {
  515. return errValueNotSettable
  516. }
  517. baseType := Deref(fieldType)
  518. if fieldType.Kind() == reflect.Ptr {
  519. target := reflect.New(baseType).Elem()
  520. switch mapValue.(type) {
  521. case string, json.Number:
  522. value.Set(target.Addr())
  523. value = target
  524. }
  525. }
  526. switch v := mapValue.(type) {
  527. case string:
  528. return validateAndSetValue(baseType.Kind(), value, v, opts)
  529. case json.Number:
  530. if err := validateJsonNumberRange(v, opts); err != nil {
  531. return err
  532. }
  533. return setValue(baseType.Kind(), value, v.String())
  534. default:
  535. return newTypeMismatchError(fullName)
  536. }
  537. }
  538. func fillWithSameType(field reflect.StructField, value reflect.Value, mapValue interface{},
  539. opts *fieldOptionsWithContext) error {
  540. if !value.CanSet() {
  541. return errValueNotSettable
  542. }
  543. if err := validateValueRange(mapValue, opts); err != nil {
  544. return err
  545. }
  546. if field.Type.Kind() == reflect.Ptr {
  547. baseType := Deref(field.Type)
  548. target := reflect.New(baseType).Elem()
  549. target.Set(reflect.ValueOf(mapValue))
  550. value.Set(target.Addr())
  551. } else {
  552. value.Set(reflect.ValueOf(mapValue))
  553. }
  554. return nil
  555. }
  556. // getValue gets the value for the specific key, the key can be in the format of parentKey.childKey
  557. func getValue(m Valuer, key string) (interface{}, bool) {
  558. keys := readKeys(key)
  559. return getValueWithChainedKeys(m, keys)
  560. }
  561. func getValueWithChainedKeys(m Valuer, keys []string) (interface{}, bool) {
  562. if len(keys) == 1 {
  563. v, ok := m.Value(keys[0])
  564. return v, ok
  565. } else if len(keys) > 1 {
  566. if v, ok := m.Value(keys[0]); ok {
  567. if nextm, ok := v.(map[string]interface{}); ok {
  568. return getValueWithChainedKeys(MapValuer(nextm), keys[1:])
  569. }
  570. }
  571. }
  572. return nil, false
  573. }
  574. func insertKeys(key string, cache []string) {
  575. cacheKeysLock.Lock()
  576. defer cacheKeysLock.Unlock()
  577. keys := cacheKeys.Load().(keyCache)
  578. // copy the contents into the new map, to guarantee the old map is immutable
  579. newKeys := make(keyCache)
  580. for k, v := range keys {
  581. newKeys[k] = v
  582. }
  583. newKeys[key] = cache
  584. cacheKeys.Store(newKeys)
  585. }
  586. func join(elem ...string) string {
  587. var builder strings.Builder
  588. var fillSep bool
  589. for _, e := range elem {
  590. if len(e) == 0 {
  591. continue
  592. }
  593. if fillSep {
  594. builder.WriteByte(delimiter)
  595. } else {
  596. fillSep = true
  597. }
  598. builder.WriteString(e)
  599. }
  600. return builder.String()
  601. }
  602. func newInitError(name string) error {
  603. return fmt.Errorf("field %s is not set", name)
  604. }
  605. func newTypeMismatchError(name string) error {
  606. return fmt.Errorf("error: type mismatch for field %s", name)
  607. }
  608. func readKeys(key string) []string {
  609. cache := cacheKeys.Load().(keyCache)
  610. if keys, ok := cache[key]; ok {
  611. return keys
  612. }
  613. keys := strings.FieldsFunc(key, func(c rune) bool {
  614. return c == delimiter
  615. })
  616. insertKeys(key, keys)
  617. return keys
  618. }