unmarshaler.go 19 KB

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