key.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. // Copyright 2014 Unknwon
  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
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package ini
  15. import (
  16. "bytes"
  17. "errors"
  18. "fmt"
  19. "strconv"
  20. "strings"
  21. "time"
  22. )
  23. // Key represents a key under a section.
  24. type Key struct {
  25. s *Section
  26. Comment string
  27. name string
  28. value string
  29. isAutoIncrement bool
  30. isBooleanType bool
  31. isShadow bool
  32. shadows []*Key
  33. nestedValues []string
  34. }
  35. // newKey simply return a key object with given values.
  36. func newKey(s *Section, name, val string) *Key {
  37. return &Key{
  38. s: s,
  39. name: name,
  40. value: val,
  41. }
  42. }
  43. func (k *Key) addShadow(val string) error {
  44. if k.isShadow {
  45. return errors.New("cannot add shadow to another shadow key")
  46. } else if k.isAutoIncrement || k.isBooleanType {
  47. return errors.New("cannot add shadow to auto-increment or boolean key")
  48. }
  49. // Deduplicate shadows based on their values.
  50. if k.value == val {
  51. return nil
  52. }
  53. for i := range k.shadows {
  54. if k.shadows[i].value == val {
  55. return nil
  56. }
  57. }
  58. shadow := newKey(k.s, k.name, val)
  59. shadow.isShadow = true
  60. k.shadows = append(k.shadows, shadow)
  61. return nil
  62. }
  63. // AddShadow adds a new shadow key to itself.
  64. func (k *Key) AddShadow(val string) error {
  65. if !k.s.f.options.AllowShadows {
  66. return errors.New("shadow key is not allowed")
  67. }
  68. return k.addShadow(val)
  69. }
  70. func (k *Key) addNestedValue(val string) error {
  71. if k.isAutoIncrement || k.isBooleanType {
  72. return errors.New("cannot add nested value to auto-increment or boolean key")
  73. }
  74. k.nestedValues = append(k.nestedValues, val)
  75. return nil
  76. }
  77. // AddNestedValue adds a nested value to the key.
  78. func (k *Key) AddNestedValue(val string) error {
  79. if !k.s.f.options.AllowNestedValues {
  80. return errors.New("nested value is not allowed")
  81. }
  82. return k.addNestedValue(val)
  83. }
  84. // ValueMapper represents a mapping function for values, e.g. os.ExpandEnv
  85. type ValueMapper func(string) string
  86. // Name returns name of key.
  87. func (k *Key) Name() string {
  88. return k.name
  89. }
  90. // Value returns raw value of key for performance purpose.
  91. func (k *Key) Value() string {
  92. return k.value
  93. }
  94. // ValueWithShadows returns raw values of key and its shadows if any.
  95. func (k *Key) ValueWithShadows() []string {
  96. if len(k.shadows) == 0 {
  97. return []string{k.value}
  98. }
  99. vals := make([]string, len(k.shadows)+1)
  100. vals[0] = k.value
  101. for i := range k.shadows {
  102. vals[i+1] = k.shadows[i].value
  103. }
  104. return vals
  105. }
  106. // NestedValues returns nested values stored in the key.
  107. // It is possible returned value is nil if no nested values stored in the key.
  108. func (k *Key) NestedValues() []string {
  109. return k.nestedValues
  110. }
  111. // transformValue takes a raw value and transforms to its final string.
  112. func (k *Key) transformValue(val string) string {
  113. if k.s.f.ValueMapper != nil {
  114. val = k.s.f.ValueMapper(val)
  115. }
  116. // Fail-fast if no indicate char found for recursive value
  117. if !strings.Contains(val, "%") {
  118. return val
  119. }
  120. for i := 0; i < depthValues; i++ {
  121. vr := varPattern.FindString(val)
  122. if len(vr) == 0 {
  123. break
  124. }
  125. // Take off leading '%(' and trailing ')s'.
  126. noption := vr[2 : len(vr)-2]
  127. // Search in the same section.
  128. // If not found or found the key itself, then search again in default section.
  129. nk, err := k.s.GetKey(noption)
  130. if err != nil || k == nk {
  131. nk, _ = k.s.f.Section("").GetKey(noption)
  132. if nk == nil {
  133. // Stop when no results found in the default section,
  134. // and returns the value as-is.
  135. break
  136. }
  137. }
  138. // Substitute by new value and take off leading '%(' and trailing ')s'.
  139. val = strings.Replace(val, vr, nk.value, -1)
  140. }
  141. return val
  142. }
  143. // String returns string representation of value.
  144. func (k *Key) String() string {
  145. return k.transformValue(k.value)
  146. }
  147. // Validate accepts a validate function which can
  148. // return modifed result as key value.
  149. func (k *Key) Validate(fn func(string) string) string {
  150. return fn(k.String())
  151. }
  152. // parseBool returns the boolean value represented by the string.
  153. //
  154. // It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On,
  155. // 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off.
  156. // Any other value returns an error.
  157. func parseBool(str string) (value bool, err error) {
  158. switch str {
  159. case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On":
  160. return true, nil
  161. case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off":
  162. return false, nil
  163. }
  164. return false, fmt.Errorf("parsing \"%s\": invalid syntax", str)
  165. }
  166. // Bool returns bool type value.
  167. func (k *Key) Bool() (bool, error) {
  168. return parseBool(k.String())
  169. }
  170. // Float64 returns float64 type value.
  171. func (k *Key) Float64() (float64, error) {
  172. return strconv.ParseFloat(k.String(), 64)
  173. }
  174. // Int returns int type value.
  175. func (k *Key) Int() (int, error) {
  176. v, err := strconv.ParseInt(k.String(), 0, 64)
  177. return int(v), err
  178. }
  179. // Int64 returns int64 type value.
  180. func (k *Key) Int64() (int64, error) {
  181. return strconv.ParseInt(k.String(), 0, 64)
  182. }
  183. // Uint returns uint type valued.
  184. func (k *Key) Uint() (uint, error) {
  185. u, e := strconv.ParseUint(k.String(), 0, 64)
  186. return uint(u), e
  187. }
  188. // Uint64 returns uint64 type value.
  189. func (k *Key) Uint64() (uint64, error) {
  190. return strconv.ParseUint(k.String(), 0, 64)
  191. }
  192. // Duration returns time.Duration type value.
  193. func (k *Key) Duration() (time.Duration, error) {
  194. return time.ParseDuration(k.String())
  195. }
  196. // TimeFormat parses with given format and returns time.Time type value.
  197. func (k *Key) TimeFormat(format string) (time.Time, error) {
  198. return time.Parse(format, k.String())
  199. }
  200. // Time parses with RFC3339 format and returns time.Time type value.
  201. func (k *Key) Time() (time.Time, error) {
  202. return k.TimeFormat(time.RFC3339)
  203. }
  204. // MustString returns default value if key value is empty.
  205. func (k *Key) MustString(defaultVal string) string {
  206. val := k.String()
  207. if len(val) == 0 {
  208. k.value = defaultVal
  209. return defaultVal
  210. }
  211. return val
  212. }
  213. // MustBool always returns value without error,
  214. // it returns false if error occurs.
  215. func (k *Key) MustBool(defaultVal ...bool) bool {
  216. val, err := k.Bool()
  217. if len(defaultVal) > 0 && err != nil {
  218. k.value = strconv.FormatBool(defaultVal[0])
  219. return defaultVal[0]
  220. }
  221. return val
  222. }
  223. // MustFloat64 always returns value without error,
  224. // it returns 0.0 if error occurs.
  225. func (k *Key) MustFloat64(defaultVal ...float64) float64 {
  226. val, err := k.Float64()
  227. if len(defaultVal) > 0 && err != nil {
  228. k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64)
  229. return defaultVal[0]
  230. }
  231. return val
  232. }
  233. // MustInt always returns value without error,
  234. // it returns 0 if error occurs.
  235. func (k *Key) MustInt(defaultVal ...int) int {
  236. val, err := k.Int()
  237. if len(defaultVal) > 0 && err != nil {
  238. k.value = strconv.FormatInt(int64(defaultVal[0]), 10)
  239. return defaultVal[0]
  240. }
  241. return val
  242. }
  243. // MustInt64 always returns value without error,
  244. // it returns 0 if error occurs.
  245. func (k *Key) MustInt64(defaultVal ...int64) int64 {
  246. val, err := k.Int64()
  247. if len(defaultVal) > 0 && err != nil {
  248. k.value = strconv.FormatInt(defaultVal[0], 10)
  249. return defaultVal[0]
  250. }
  251. return val
  252. }
  253. // MustUint always returns value without error,
  254. // it returns 0 if error occurs.
  255. func (k *Key) MustUint(defaultVal ...uint) uint {
  256. val, err := k.Uint()
  257. if len(defaultVal) > 0 && err != nil {
  258. k.value = strconv.FormatUint(uint64(defaultVal[0]), 10)
  259. return defaultVal[0]
  260. }
  261. return val
  262. }
  263. // MustUint64 always returns value without error,
  264. // it returns 0 if error occurs.
  265. func (k *Key) MustUint64(defaultVal ...uint64) uint64 {
  266. val, err := k.Uint64()
  267. if len(defaultVal) > 0 && err != nil {
  268. k.value = strconv.FormatUint(defaultVal[0], 10)
  269. return defaultVal[0]
  270. }
  271. return val
  272. }
  273. // MustDuration always returns value without error,
  274. // it returns zero value if error occurs.
  275. func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration {
  276. val, err := k.Duration()
  277. if len(defaultVal) > 0 && err != nil {
  278. k.value = defaultVal[0].String()
  279. return defaultVal[0]
  280. }
  281. return val
  282. }
  283. // MustTimeFormat always parses with given format and returns value without error,
  284. // it returns zero value if error occurs.
  285. func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time {
  286. val, err := k.TimeFormat(format)
  287. if len(defaultVal) > 0 && err != nil {
  288. k.value = defaultVal[0].Format(format)
  289. return defaultVal[0]
  290. }
  291. return val
  292. }
  293. // MustTime always parses with RFC3339 format and returns value without error,
  294. // it returns zero value if error occurs.
  295. func (k *Key) MustTime(defaultVal ...time.Time) time.Time {
  296. return k.MustTimeFormat(time.RFC3339, defaultVal...)
  297. }
  298. // In always returns value without error,
  299. // it returns default value if error occurs or doesn't fit into candidates.
  300. func (k *Key) In(defaultVal string, candidates []string) string {
  301. val := k.String()
  302. for _, cand := range candidates {
  303. if val == cand {
  304. return val
  305. }
  306. }
  307. return defaultVal
  308. }
  309. // InFloat64 always returns value without error,
  310. // it returns default value if error occurs or doesn't fit into candidates.
  311. func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 {
  312. val := k.MustFloat64()
  313. for _, cand := range candidates {
  314. if val == cand {
  315. return val
  316. }
  317. }
  318. return defaultVal
  319. }
  320. // InInt always returns value without error,
  321. // it returns default value if error occurs or doesn't fit into candidates.
  322. func (k *Key) InInt(defaultVal int, candidates []int) int {
  323. val := k.MustInt()
  324. for _, cand := range candidates {
  325. if val == cand {
  326. return val
  327. }
  328. }
  329. return defaultVal
  330. }
  331. // InInt64 always returns value without error,
  332. // it returns default value if error occurs or doesn't fit into candidates.
  333. func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 {
  334. val := k.MustInt64()
  335. for _, cand := range candidates {
  336. if val == cand {
  337. return val
  338. }
  339. }
  340. return defaultVal
  341. }
  342. // InUint always returns value without error,
  343. // it returns default value if error occurs or doesn't fit into candidates.
  344. func (k *Key) InUint(defaultVal uint, candidates []uint) uint {
  345. val := k.MustUint()
  346. for _, cand := range candidates {
  347. if val == cand {
  348. return val
  349. }
  350. }
  351. return defaultVal
  352. }
  353. // InUint64 always returns value without error,
  354. // it returns default value if error occurs or doesn't fit into candidates.
  355. func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 {
  356. val := k.MustUint64()
  357. for _, cand := range candidates {
  358. if val == cand {
  359. return val
  360. }
  361. }
  362. return defaultVal
  363. }
  364. // InTimeFormat always parses with given format and returns value without error,
  365. // it returns default value if error occurs or doesn't fit into candidates.
  366. func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time {
  367. val := k.MustTimeFormat(format)
  368. for _, cand := range candidates {
  369. if val == cand {
  370. return val
  371. }
  372. }
  373. return defaultVal
  374. }
  375. // InTime always parses with RFC3339 format and returns value without error,
  376. // it returns default value if error occurs or doesn't fit into candidates.
  377. func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time {
  378. return k.InTimeFormat(time.RFC3339, defaultVal, candidates)
  379. }
  380. // RangeFloat64 checks if value is in given range inclusively,
  381. // and returns default value if it's not.
  382. func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 {
  383. val := k.MustFloat64()
  384. if val < min || val > max {
  385. return defaultVal
  386. }
  387. return val
  388. }
  389. // RangeInt checks if value is in given range inclusively,
  390. // and returns default value if it's not.
  391. func (k *Key) RangeInt(defaultVal, min, max int) int {
  392. val := k.MustInt()
  393. if val < min || val > max {
  394. return defaultVal
  395. }
  396. return val
  397. }
  398. // RangeInt64 checks if value is in given range inclusively,
  399. // and returns default value if it's not.
  400. func (k *Key) RangeInt64(defaultVal, min, max int64) int64 {
  401. val := k.MustInt64()
  402. if val < min || val > max {
  403. return defaultVal
  404. }
  405. return val
  406. }
  407. // RangeTimeFormat checks if value with given format is in given range inclusively,
  408. // and returns default value if it's not.
  409. func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time {
  410. val := k.MustTimeFormat(format)
  411. if val.Unix() < min.Unix() || val.Unix() > max.Unix() {
  412. return defaultVal
  413. }
  414. return val
  415. }
  416. // RangeTime checks if value with RFC3339 format is in given range inclusively,
  417. // and returns default value if it's not.
  418. func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time {
  419. return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max)
  420. }
  421. // Strings returns list of string divided by given delimiter.
  422. func (k *Key) Strings(delim string) []string {
  423. str := k.String()
  424. if len(str) == 0 {
  425. return []string{}
  426. }
  427. runes := []rune(str)
  428. vals := make([]string, 0, 2)
  429. var buf bytes.Buffer
  430. escape := false
  431. idx := 0
  432. for {
  433. if escape {
  434. escape = false
  435. if runes[idx] != '\\' && !strings.HasPrefix(string(runes[idx:]), delim) {
  436. buf.WriteRune('\\')
  437. }
  438. buf.WriteRune(runes[idx])
  439. } else {
  440. if runes[idx] == '\\' {
  441. escape = true
  442. } else if strings.HasPrefix(string(runes[idx:]), delim) {
  443. idx += len(delim) - 1
  444. vals = append(vals, strings.TrimSpace(buf.String()))
  445. buf.Reset()
  446. } else {
  447. buf.WriteRune(runes[idx])
  448. }
  449. }
  450. idx++
  451. if idx == len(runes) {
  452. break
  453. }
  454. }
  455. if buf.Len() > 0 {
  456. vals = append(vals, strings.TrimSpace(buf.String()))
  457. }
  458. return vals
  459. }
  460. // StringsWithShadows returns list of string divided by given delimiter.
  461. // Shadows will also be appended if any.
  462. func (k *Key) StringsWithShadows(delim string) []string {
  463. vals := k.ValueWithShadows()
  464. results := make([]string, 0, len(vals)*2)
  465. for i := range vals {
  466. if len(vals) == 0 {
  467. continue
  468. }
  469. results = append(results, strings.Split(vals[i], delim)...)
  470. }
  471. for i := range results {
  472. results[i] = k.transformValue(strings.TrimSpace(results[i]))
  473. }
  474. return results
  475. }
  476. // Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value.
  477. func (k *Key) Float64s(delim string) []float64 {
  478. vals, _ := k.parseFloat64s(k.Strings(delim), true, false)
  479. return vals
  480. }
  481. // Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value.
  482. func (k *Key) Ints(delim string) []int {
  483. vals, _ := k.parseInts(k.Strings(delim), true, false)
  484. return vals
  485. }
  486. // Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value.
  487. func (k *Key) Int64s(delim string) []int64 {
  488. vals, _ := k.parseInt64s(k.Strings(delim), true, false)
  489. return vals
  490. }
  491. // Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value.
  492. func (k *Key) Uints(delim string) []uint {
  493. vals, _ := k.parseUints(k.Strings(delim), true, false)
  494. return vals
  495. }
  496. // Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value.
  497. func (k *Key) Uint64s(delim string) []uint64 {
  498. vals, _ := k.parseUint64s(k.Strings(delim), true, false)
  499. return vals
  500. }
  501. // Bools returns list of bool divided by given delimiter. Any invalid input will be treated as zero value.
  502. func (k *Key) Bools(delim string) []bool {
  503. vals, _ := k.parseBools(k.Strings(delim), true, false)
  504. return vals
  505. }
  506. // TimesFormat parses with given format and returns list of time.Time divided by given delimiter.
  507. // Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
  508. func (k *Key) TimesFormat(format, delim string) []time.Time {
  509. vals, _ := k.parseTimesFormat(format, k.Strings(delim), true, false)
  510. return vals
  511. }
  512. // Times parses with RFC3339 format and returns list of time.Time divided by given delimiter.
  513. // Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
  514. func (k *Key) Times(delim string) []time.Time {
  515. return k.TimesFormat(time.RFC3339, delim)
  516. }
  517. // ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then
  518. // it will not be included to result list.
  519. func (k *Key) ValidFloat64s(delim string) []float64 {
  520. vals, _ := k.parseFloat64s(k.Strings(delim), false, false)
  521. return vals
  522. }
  523. // ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will
  524. // not be included to result list.
  525. func (k *Key) ValidInts(delim string) []int {
  526. vals, _ := k.parseInts(k.Strings(delim), false, false)
  527. return vals
  528. }
  529. // ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer,
  530. // then it will not be included to result list.
  531. func (k *Key) ValidInt64s(delim string) []int64 {
  532. vals, _ := k.parseInt64s(k.Strings(delim), false, false)
  533. return vals
  534. }
  535. // ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer,
  536. // then it will not be included to result list.
  537. func (k *Key) ValidUints(delim string) []uint {
  538. vals, _ := k.parseUints(k.Strings(delim), false, false)
  539. return vals
  540. }
  541. // ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned
  542. // integer, then it will not be included to result list.
  543. func (k *Key) ValidUint64s(delim string) []uint64 {
  544. vals, _ := k.parseUint64s(k.Strings(delim), false, false)
  545. return vals
  546. }
  547. // ValidBools returns list of bool divided by given delimiter. If some value is not 64-bit unsigned
  548. // integer, then it will not be included to result list.
  549. func (k *Key) ValidBools(delim string) []bool {
  550. vals, _ := k.parseBools(k.Strings(delim), false, false)
  551. return vals
  552. }
  553. // ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter.
  554. func (k *Key) ValidTimesFormat(format, delim string) []time.Time {
  555. vals, _ := k.parseTimesFormat(format, k.Strings(delim), false, false)
  556. return vals
  557. }
  558. // ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter.
  559. func (k *Key) ValidTimes(delim string) []time.Time {
  560. return k.ValidTimesFormat(time.RFC3339, delim)
  561. }
  562. // StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input.
  563. func (k *Key) StrictFloat64s(delim string) ([]float64, error) {
  564. return k.parseFloat64s(k.Strings(delim), false, true)
  565. }
  566. // StrictInts returns list of int divided by given delimiter or error on first invalid input.
  567. func (k *Key) StrictInts(delim string) ([]int, error) {
  568. return k.parseInts(k.Strings(delim), false, true)
  569. }
  570. // StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input.
  571. func (k *Key) StrictInt64s(delim string) ([]int64, error) {
  572. return k.parseInt64s(k.Strings(delim), false, true)
  573. }
  574. // StrictUints returns list of uint divided by given delimiter or error on first invalid input.
  575. func (k *Key) StrictUints(delim string) ([]uint, error) {
  576. return k.parseUints(k.Strings(delim), false, true)
  577. }
  578. // StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input.
  579. func (k *Key) StrictUint64s(delim string) ([]uint64, error) {
  580. return k.parseUint64s(k.Strings(delim), false, true)
  581. }
  582. // StrictBools returns list of bool divided by given delimiter or error on first invalid input.
  583. func (k *Key) StrictBools(delim string) ([]bool, error) {
  584. return k.parseBools(k.Strings(delim), false, true)
  585. }
  586. // StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter
  587. // or error on first invalid input.
  588. func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) {
  589. return k.parseTimesFormat(format, k.Strings(delim), false, true)
  590. }
  591. // StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter
  592. // or error on first invalid input.
  593. func (k *Key) StrictTimes(delim string) ([]time.Time, error) {
  594. return k.StrictTimesFormat(time.RFC3339, delim)
  595. }
  596. // parseBools transforms strings to bools.
  597. func (k *Key) parseBools(strs []string, addInvalid, returnOnInvalid bool) ([]bool, error) {
  598. vals := make([]bool, 0, len(strs))
  599. parser := func(str string) (interface{}, error) {
  600. val, err := parseBool(str)
  601. return val, err
  602. }
  603. rawVals, err := k.doParse(strs, addInvalid, returnOnInvalid, parser)
  604. if err == nil {
  605. for _, val := range rawVals {
  606. vals = append(vals, val.(bool))
  607. }
  608. }
  609. return vals, err
  610. }
  611. // parseFloat64s transforms strings to float64s.
  612. func (k *Key) parseFloat64s(strs []string, addInvalid, returnOnInvalid bool) ([]float64, error) {
  613. vals := make([]float64, 0, len(strs))
  614. parser := func(str string) (interface{}, error) {
  615. val, err := strconv.ParseFloat(str, 64)
  616. return val, err
  617. }
  618. rawVals, err := k.doParse(strs, addInvalid, returnOnInvalid, parser)
  619. if err == nil {
  620. for _, val := range rawVals {
  621. vals = append(vals, val.(float64))
  622. }
  623. }
  624. return vals, err
  625. }
  626. // parseInts transforms strings to ints.
  627. func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) {
  628. vals := make([]int, 0, len(strs))
  629. parser := func(str string) (interface{}, error) {
  630. val, err := strconv.ParseInt(str, 0, 64)
  631. return val, err
  632. }
  633. rawVals, err := k.doParse(strs, addInvalid, returnOnInvalid, parser)
  634. if err == nil {
  635. for _, val := range rawVals {
  636. vals = append(vals, int(val.(int64)))
  637. }
  638. }
  639. return vals, err
  640. }
  641. // parseInt64s transforms strings to int64s.
  642. func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) {
  643. vals := make([]int64, 0, len(strs))
  644. parser := func(str string) (interface{}, error) {
  645. val, err := strconv.ParseInt(str, 0, 64)
  646. return val, err
  647. }
  648. rawVals, err := k.doParse(strs, addInvalid, returnOnInvalid, parser)
  649. if err == nil {
  650. for _, val := range rawVals {
  651. vals = append(vals, val.(int64))
  652. }
  653. }
  654. return vals, err
  655. }
  656. // parseUints transforms strings to uints.
  657. func (k *Key) parseUints(strs []string, addInvalid, returnOnInvalid bool) ([]uint, error) {
  658. vals := make([]uint, 0, len(strs))
  659. parser := func(str string) (interface{}, error) {
  660. val, err := strconv.ParseUint(str, 0, 64)
  661. return val, err
  662. }
  663. rawVals, err := k.doParse(strs, addInvalid, returnOnInvalid, parser)
  664. if err == nil {
  665. for _, val := range rawVals {
  666. vals = append(vals, uint(val.(uint64)))
  667. }
  668. }
  669. return vals, err
  670. }
  671. // parseUint64s transforms strings to uint64s.
  672. func (k *Key) parseUint64s(strs []string, addInvalid, returnOnInvalid bool) ([]uint64, error) {
  673. vals := make([]uint64, 0, len(strs))
  674. parser := func(str string) (interface{}, error) {
  675. val, err := strconv.ParseUint(str, 0, 64)
  676. return val, err
  677. }
  678. rawVals, err := k.doParse(strs, addInvalid, returnOnInvalid, parser)
  679. if err == nil {
  680. for _, val := range rawVals {
  681. vals = append(vals, val.(uint64))
  682. }
  683. }
  684. return vals, err
  685. }
  686. type Parser func(str string) (interface{}, error)
  687. // parseTimesFormat transforms strings to times in given format.
  688. func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnOnInvalid bool) ([]time.Time, error) {
  689. vals := make([]time.Time, 0, len(strs))
  690. parser := func(str string) (interface{}, error) {
  691. val, err := time.Parse(format, str)
  692. return val, err
  693. }
  694. rawVals, err := k.doParse(strs, addInvalid, returnOnInvalid, parser)
  695. if err == nil {
  696. for _, val := range rawVals {
  697. vals = append(vals, val.(time.Time))
  698. }
  699. }
  700. return vals, err
  701. }
  702. // doParse transforms strings to different types
  703. func (k *Key) doParse(strs []string, addInvalid, returnOnInvalid bool, parser Parser) ([]interface{}, error) {
  704. vals := make([]interface{}, 0, len(strs))
  705. for _, str := range strs {
  706. val, err := parser(str)
  707. if err != nil && returnOnInvalid {
  708. return nil, err
  709. }
  710. if err == nil || addInvalid {
  711. vals = append(vals, val)
  712. }
  713. }
  714. return vals, nil
  715. }
  716. // SetValue changes key value.
  717. func (k *Key) SetValue(v string) {
  718. if k.s.f.BlockMode {
  719. k.s.f.lock.Lock()
  720. defer k.s.f.lock.Unlock()
  721. }
  722. k.value = v
  723. k.s.keysHash[k.name] = v
  724. }