quantity.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package resource
  14. import (
  15. "bytes"
  16. "errors"
  17. "fmt"
  18. "math"
  19. "math/big"
  20. "strconv"
  21. "strings"
  22. inf "gopkg.in/inf.v0"
  23. )
  24. // Quantity is a fixed-point representation of a number.
  25. // It provides convenient marshaling/unmarshaling in JSON and YAML,
  26. // in addition to String() and AsInt64() accessors.
  27. //
  28. // The serialization format is:
  29. //
  30. // <quantity> ::= <signedNumber><suffix>
  31. // (Note that <suffix> may be empty, from the "" case in <decimalSI>.)
  32. // <digit> ::= 0 | 1 | ... | 9
  33. // <digits> ::= <digit> | <digit><digits>
  34. // <number> ::= <digits> | <digits>.<digits> | <digits>. | .<digits>
  35. // <sign> ::= "+" | "-"
  36. // <signedNumber> ::= <number> | <sign><number>
  37. // <suffix> ::= <binarySI> | <decimalExponent> | <decimalSI>
  38. // <binarySI> ::= Ki | Mi | Gi | Ti | Pi | Ei
  39. // (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)
  40. // <decimalSI> ::= m | "" | k | M | G | T | P | E
  41. // (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)
  42. // <decimalExponent> ::= "e" <signedNumber> | "E" <signedNumber>
  43. //
  44. // No matter which of the three exponent forms is used, no quantity may represent
  45. // a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal
  46. // places. Numbers larger or more precise will be capped or rounded up.
  47. // (E.g.: 0.1m will rounded up to 1m.)
  48. // This may be extended in the future if we require larger or smaller quantities.
  49. //
  50. // When a Quantity is parsed from a string, it will remember the type of suffix
  51. // it had, and will use the same type again when it is serialized.
  52. //
  53. // Before serializing, Quantity will be put in "canonical form".
  54. // This means that Exponent/suffix will be adjusted up or down (with a
  55. // corresponding increase or decrease in Mantissa) such that:
  56. // a. No precision is lost
  57. // b. No fractional digits will be emitted
  58. // c. The exponent (or suffix) is as large as possible.
  59. // The sign will be omitted unless the number is negative.
  60. //
  61. // Examples:
  62. // 1.5 will be serialized as "1500m"
  63. // 1.5Gi will be serialized as "1536Mi"
  64. //
  65. // Note that the quantity will NEVER be internally represented by a
  66. // floating point number. That is the whole point of this exercise.
  67. //
  68. // Non-canonical values will still parse as long as they are well formed,
  69. // but will be re-emitted in their canonical form. (So always use canonical
  70. // form, or don't diff.)
  71. //
  72. // This format is intended to make it difficult to use these numbers without
  73. // writing some sort of special handling code in the hopes that that will
  74. // cause implementors to also use a fixed point implementation.
  75. //
  76. // +protobuf=true
  77. // +protobuf.embed=string
  78. // +protobuf.options.marshal=false
  79. // +protobuf.options.(gogoproto.goproto_stringer)=false
  80. // +k8s:deepcopy-gen=true
  81. // +k8s:openapi-gen=true
  82. type Quantity struct {
  83. // i is the quantity in int64 scaled form, if d.Dec == nil
  84. i int64Amount
  85. // d is the quantity in inf.Dec form if d.Dec != nil
  86. d infDecAmount
  87. // s is the generated value of this quantity to avoid recalculation
  88. s string
  89. // Change Format at will. See the comment for Canonicalize for
  90. // more details.
  91. Format
  92. }
  93. // CanonicalValue allows a quantity amount to be converted to a string.
  94. type CanonicalValue interface {
  95. // AsCanonicalBytes returns a byte array representing the string representation
  96. // of the value mantissa and an int32 representing its exponent in base-10. Callers may
  97. // pass a byte slice to the method to avoid allocations.
  98. AsCanonicalBytes(out []byte) ([]byte, int32)
  99. // AsCanonicalBase1024Bytes returns a byte array representing the string representation
  100. // of the value mantissa and an int32 representing its exponent in base-1024. Callers
  101. // may pass a byte slice to the method to avoid allocations.
  102. AsCanonicalBase1024Bytes(out []byte) ([]byte, int32)
  103. }
  104. // Format lists the three possible formattings of a quantity.
  105. type Format string
  106. const (
  107. DecimalExponent = Format("DecimalExponent") // e.g., 12e6
  108. BinarySI = Format("BinarySI") // e.g., 12Mi (12 * 2^20)
  109. DecimalSI = Format("DecimalSI") // e.g., 12M (12 * 10^6)
  110. )
  111. // MustParse turns the given string into a quantity or panics; for tests
  112. // or other cases where you know the string is valid.
  113. func MustParse(str string) Quantity {
  114. q, err := ParseQuantity(str)
  115. if err != nil {
  116. panic(fmt.Errorf("cannot parse '%v': %v", str, err))
  117. }
  118. return q
  119. }
  120. const (
  121. // splitREString is used to separate a number from its suffix; as such,
  122. // this is overly permissive, but that's OK-- it will be checked later.
  123. splitREString = "^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$"
  124. )
  125. var (
  126. // Errors that could happen while parsing a string.
  127. ErrFormatWrong = errors.New("quantities must match the regular expression '" + splitREString + "'")
  128. ErrNumeric = errors.New("unable to parse numeric part of quantity")
  129. ErrSuffix = errors.New("unable to parse quantity's suffix")
  130. )
  131. // parseQuantityString is a fast scanner for quantity values.
  132. func parseQuantityString(str string) (positive bool, value, num, denom, suffix string, err error) {
  133. positive = true
  134. pos := 0
  135. end := len(str)
  136. // handle leading sign
  137. if pos < end {
  138. switch str[0] {
  139. case '-':
  140. positive = false
  141. pos++
  142. case '+':
  143. pos++
  144. }
  145. }
  146. // strip leading zeros
  147. Zeroes:
  148. for i := pos; ; i++ {
  149. if i >= end {
  150. num = "0"
  151. value = num
  152. return
  153. }
  154. switch str[i] {
  155. case '0':
  156. pos++
  157. default:
  158. break Zeroes
  159. }
  160. }
  161. // extract the numerator
  162. Num:
  163. for i := pos; ; i++ {
  164. if i >= end {
  165. num = str[pos:end]
  166. value = str[0:end]
  167. return
  168. }
  169. switch str[i] {
  170. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  171. default:
  172. num = str[pos:i]
  173. pos = i
  174. break Num
  175. }
  176. }
  177. // if we stripped all numerator positions, always return 0
  178. if len(num) == 0 {
  179. num = "0"
  180. }
  181. // handle a denominator
  182. if pos < end && str[pos] == '.' {
  183. pos++
  184. Denom:
  185. for i := pos; ; i++ {
  186. if i >= end {
  187. denom = str[pos:end]
  188. value = str[0:end]
  189. return
  190. }
  191. switch str[i] {
  192. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  193. default:
  194. denom = str[pos:i]
  195. pos = i
  196. break Denom
  197. }
  198. }
  199. // TODO: we currently allow 1.G, but we may not want to in the future.
  200. // if len(denom) == 0 {
  201. // err = ErrFormatWrong
  202. // return
  203. // }
  204. }
  205. value = str[0:pos]
  206. // grab the elements of the suffix
  207. suffixStart := pos
  208. for i := pos; ; i++ {
  209. if i >= end {
  210. suffix = str[suffixStart:end]
  211. return
  212. }
  213. if !strings.ContainsAny(str[i:i+1], "eEinumkKMGTP") {
  214. pos = i
  215. break
  216. }
  217. }
  218. if pos < end {
  219. switch str[pos] {
  220. case '-', '+':
  221. pos++
  222. }
  223. }
  224. Suffix:
  225. for i := pos; ; i++ {
  226. if i >= end {
  227. suffix = str[suffixStart:end]
  228. return
  229. }
  230. switch str[i] {
  231. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  232. default:
  233. break Suffix
  234. }
  235. }
  236. // we encountered a non decimal in the Suffix loop, but the last character
  237. // was not a valid exponent
  238. err = ErrFormatWrong
  239. return
  240. }
  241. // ParseQuantity turns str into a Quantity, or returns an error.
  242. func ParseQuantity(str string) (Quantity, error) {
  243. if len(str) == 0 {
  244. return Quantity{}, ErrFormatWrong
  245. }
  246. if str == "0" {
  247. return Quantity{Format: DecimalSI, s: str}, nil
  248. }
  249. positive, value, num, denom, suf, err := parseQuantityString(str)
  250. if err != nil {
  251. return Quantity{}, err
  252. }
  253. base, exponent, format, ok := quantitySuffixer.interpret(suffix(suf))
  254. if !ok {
  255. return Quantity{}, ErrSuffix
  256. }
  257. precision := int32(0)
  258. scale := int32(0)
  259. mantissa := int64(1)
  260. switch format {
  261. case DecimalExponent, DecimalSI:
  262. scale = exponent
  263. precision = maxInt64Factors - int32(len(num)+len(denom))
  264. case BinarySI:
  265. scale = 0
  266. switch {
  267. case exponent >= 0 && len(denom) == 0:
  268. // only handle positive binary numbers with the fast path
  269. mantissa = int64(int64(mantissa) << uint64(exponent))
  270. // 1Mi (2^20) has ~6 digits of decimal precision, so exponent*3/10 -1 is roughly the precision
  271. precision = 15 - int32(len(num)) - int32(float32(exponent)*3/10) - 1
  272. default:
  273. precision = -1
  274. }
  275. }
  276. if precision >= 0 {
  277. // if we have a denominator, shift the entire value to the left by the number of places in the
  278. // denominator
  279. scale -= int32(len(denom))
  280. if scale >= int32(Nano) {
  281. shifted := num + denom
  282. var value int64
  283. value, err := strconv.ParseInt(shifted, 10, 64)
  284. if err != nil {
  285. return Quantity{}, ErrNumeric
  286. }
  287. if result, ok := int64Multiply(value, int64(mantissa)); ok {
  288. if !positive {
  289. result = -result
  290. }
  291. // if the number is in canonical form, reuse the string
  292. switch format {
  293. case BinarySI:
  294. if exponent%10 == 0 && (value&0x07 != 0) {
  295. return Quantity{i: int64Amount{value: result, scale: Scale(scale)}, Format: format, s: str}, nil
  296. }
  297. default:
  298. if scale%3 == 0 && !strings.HasSuffix(shifted, "000") && shifted[0] != '0' {
  299. return Quantity{i: int64Amount{value: result, scale: Scale(scale)}, Format: format, s: str}, nil
  300. }
  301. }
  302. return Quantity{i: int64Amount{value: result, scale: Scale(scale)}, Format: format}, nil
  303. }
  304. }
  305. }
  306. amount := new(inf.Dec)
  307. if _, ok := amount.SetString(value); !ok {
  308. return Quantity{}, ErrNumeric
  309. }
  310. // So that no one but us has to think about suffixes, remove it.
  311. if base == 10 {
  312. amount.SetScale(amount.Scale() + Scale(exponent).infScale())
  313. } else if base == 2 {
  314. // numericSuffix = 2 ** exponent
  315. numericSuffix := big.NewInt(1).Lsh(bigOne, uint(exponent))
  316. ub := amount.UnscaledBig()
  317. amount.SetUnscaledBig(ub.Mul(ub, numericSuffix))
  318. }
  319. // Cap at min/max bounds.
  320. sign := amount.Sign()
  321. if sign == -1 {
  322. amount.Neg(amount)
  323. }
  324. // This rounds non-zero values up to the minimum representable value, under the theory that
  325. // if you want some resources, you should get some resources, even if you asked for way too small
  326. // of an amount. Arguably, this should be inf.RoundHalfUp (normal rounding), but that would have
  327. // the side effect of rounding values < .5n to zero.
  328. if v, ok := amount.Unscaled(); v != int64(0) || !ok {
  329. amount.Round(amount, Nano.infScale(), inf.RoundUp)
  330. }
  331. // The max is just a simple cap.
  332. // TODO: this prevents accumulating quantities greater than int64, for instance quota across a cluster
  333. if format == BinarySI && amount.Cmp(maxAllowed.Dec) > 0 {
  334. amount.Set(maxAllowed.Dec)
  335. }
  336. if format == BinarySI && amount.Cmp(decOne) < 0 && amount.Cmp(decZero) > 0 {
  337. // This avoids rounding and hopefully confusion, too.
  338. format = DecimalSI
  339. }
  340. if sign == -1 {
  341. amount.Neg(amount)
  342. }
  343. return Quantity{d: infDecAmount{amount}, Format: format}, nil
  344. }
  345. // DeepCopy returns a deep-copy of the Quantity value. Note that the method
  346. // receiver is a value, so we can mutate it in-place and return it.
  347. func (q Quantity) DeepCopy() Quantity {
  348. if q.d.Dec != nil {
  349. tmp := &inf.Dec{}
  350. q.d.Dec = tmp.Set(q.d.Dec)
  351. }
  352. return q
  353. }
  354. // OpenAPISchemaType is used by the kube-openapi generator when constructing
  355. // the OpenAPI spec of this type.
  356. //
  357. // See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators
  358. func (_ Quantity) OpenAPISchemaType() []string { return []string{"string"} }
  359. // OpenAPISchemaFormat is used by the kube-openapi generator when constructing
  360. // the OpenAPI spec of this type.
  361. func (_ Quantity) OpenAPISchemaFormat() string { return "" }
  362. // CanonicalizeBytes returns the canonical form of q and its suffix (see comment on Quantity).
  363. //
  364. // Note about BinarySI:
  365. // * If q.Format is set to BinarySI and q.Amount represents a non-zero value between
  366. // -1 and +1, it will be emitted as if q.Format were DecimalSI.
  367. // * Otherwise, if q.Format is set to BinarySI, fractional parts of q.Amount will be
  368. // rounded up. (1.1i becomes 2i.)
  369. func (q *Quantity) CanonicalizeBytes(out []byte) (result, suffix []byte) {
  370. if q.IsZero() {
  371. return zeroBytes, nil
  372. }
  373. var rounded CanonicalValue
  374. format := q.Format
  375. switch format {
  376. case DecimalExponent, DecimalSI:
  377. case BinarySI:
  378. if q.CmpInt64(-1024) > 0 && q.CmpInt64(1024) < 0 {
  379. // This avoids rounding and hopefully confusion, too.
  380. format = DecimalSI
  381. } else {
  382. var exact bool
  383. if rounded, exact = q.AsScale(0); !exact {
  384. // Don't lose precision-- show as DecimalSI
  385. format = DecimalSI
  386. }
  387. }
  388. default:
  389. format = DecimalExponent
  390. }
  391. // TODO: If BinarySI formatting is requested but would cause rounding, upgrade to
  392. // one of the other formats.
  393. switch format {
  394. case DecimalExponent, DecimalSI:
  395. number, exponent := q.AsCanonicalBytes(out)
  396. suffix, _ := quantitySuffixer.constructBytes(10, exponent, format)
  397. return number, suffix
  398. default:
  399. // format must be BinarySI
  400. number, exponent := rounded.AsCanonicalBase1024Bytes(out)
  401. suffix, _ := quantitySuffixer.constructBytes(2, exponent*10, format)
  402. return number, suffix
  403. }
  404. }
  405. // AsApproximateFloat64 returns a float64 representation of the quantity which may
  406. // lose precision. If the value of the quantity is outside the range of a float64
  407. // +Inf/-Inf will be returned.
  408. func (q *Quantity) AsApproximateFloat64() float64 {
  409. var base float64
  410. var exponent int
  411. if q.d.Dec != nil {
  412. base, _ = big.NewFloat(0).SetInt(q.d.Dec.UnscaledBig()).Float64()
  413. exponent = int(-q.d.Dec.Scale())
  414. } else {
  415. base = float64(q.i.value)
  416. exponent = int(q.i.scale)
  417. }
  418. if exponent == 0 {
  419. return base
  420. }
  421. // multiply by the appropriate exponential scale
  422. switch q.Format {
  423. case DecimalExponent, DecimalSI:
  424. return base * math.Pow10(exponent)
  425. default:
  426. // fast path for exponents that can fit in 64 bits
  427. if exponent > 0 && exponent < 7 {
  428. return base * float64(int64(1)<<(exponent*10))
  429. }
  430. return base * math.Pow(2, float64(exponent*10))
  431. }
  432. }
  433. // AsInt64 returns a representation of the current value as an int64 if a fast conversion
  434. // is possible. If false is returned, callers must use the inf.Dec form of this quantity.
  435. func (q *Quantity) AsInt64() (int64, bool) {
  436. if q.d.Dec != nil {
  437. return 0, false
  438. }
  439. return q.i.AsInt64()
  440. }
  441. // ToDec promotes the quantity in place to use an inf.Dec representation and returns itself.
  442. func (q *Quantity) ToDec() *Quantity {
  443. if q.d.Dec == nil {
  444. q.d.Dec = q.i.AsDec()
  445. q.i = int64Amount{}
  446. }
  447. return q
  448. }
  449. // AsDec returns the quantity as represented by a scaled inf.Dec.
  450. func (q *Quantity) AsDec() *inf.Dec {
  451. if q.d.Dec != nil {
  452. return q.d.Dec
  453. }
  454. q.d.Dec = q.i.AsDec()
  455. q.i = int64Amount{}
  456. return q.d.Dec
  457. }
  458. // AsCanonicalBytes returns the canonical byte representation of this quantity as a mantissa
  459. // and base 10 exponent. The out byte slice may be passed to the method to avoid an extra
  460. // allocation.
  461. func (q *Quantity) AsCanonicalBytes(out []byte) (result []byte, exponent int32) {
  462. if q.d.Dec != nil {
  463. return q.d.AsCanonicalBytes(out)
  464. }
  465. return q.i.AsCanonicalBytes(out)
  466. }
  467. // IsZero returns true if the quantity is equal to zero.
  468. func (q *Quantity) IsZero() bool {
  469. if q.d.Dec != nil {
  470. return q.d.Dec.Sign() == 0
  471. }
  472. return q.i.value == 0
  473. }
  474. // Sign returns 0 if the quantity is zero, -1 if the quantity is less than zero, or 1 if the
  475. // quantity is greater than zero.
  476. func (q *Quantity) Sign() int {
  477. if q.d.Dec != nil {
  478. return q.d.Dec.Sign()
  479. }
  480. return q.i.Sign()
  481. }
  482. // AsScale returns the current value, rounded up to the provided scale, and returns
  483. // false if the scale resulted in a loss of precision.
  484. func (q *Quantity) AsScale(scale Scale) (CanonicalValue, bool) {
  485. if q.d.Dec != nil {
  486. return q.d.AsScale(scale)
  487. }
  488. return q.i.AsScale(scale)
  489. }
  490. // RoundUp updates the quantity to the provided scale, ensuring that the value is at
  491. // least 1. False is returned if the rounding operation resulted in a loss of precision.
  492. // Negative numbers are rounded away from zero (-9 scale 1 rounds to -10).
  493. func (q *Quantity) RoundUp(scale Scale) bool {
  494. if q.d.Dec != nil {
  495. q.s = ""
  496. d, exact := q.d.AsScale(scale)
  497. q.d = d
  498. return exact
  499. }
  500. // avoid clearing the string value if we have already calculated it
  501. if q.i.scale >= scale {
  502. return true
  503. }
  504. q.s = ""
  505. i, exact := q.i.AsScale(scale)
  506. q.i = i
  507. return exact
  508. }
  509. // Add adds the provide y quantity to the current value. If the current value is zero,
  510. // the format of the quantity will be updated to the format of y.
  511. func (q *Quantity) Add(y Quantity) {
  512. q.s = ""
  513. if q.d.Dec == nil && y.d.Dec == nil {
  514. if q.i.value == 0 {
  515. q.Format = y.Format
  516. }
  517. if q.i.Add(y.i) {
  518. return
  519. }
  520. } else if q.IsZero() {
  521. q.Format = y.Format
  522. }
  523. q.ToDec().d.Dec.Add(q.d.Dec, y.AsDec())
  524. }
  525. // Sub subtracts the provided quantity from the current value in place. If the current
  526. // value is zero, the format of the quantity will be updated to the format of y.
  527. func (q *Quantity) Sub(y Quantity) {
  528. q.s = ""
  529. if q.IsZero() {
  530. q.Format = y.Format
  531. }
  532. if q.d.Dec == nil && y.d.Dec == nil && q.i.Sub(y.i) {
  533. return
  534. }
  535. q.ToDec().d.Dec.Sub(q.d.Dec, y.AsDec())
  536. }
  537. // Cmp returns 0 if the quantity is equal to y, -1 if the quantity is less than y, or 1 if the
  538. // quantity is greater than y.
  539. func (q *Quantity) Cmp(y Quantity) int {
  540. if q.d.Dec == nil && y.d.Dec == nil {
  541. return q.i.Cmp(y.i)
  542. }
  543. return q.AsDec().Cmp(y.AsDec())
  544. }
  545. // CmpInt64 returns 0 if the quantity is equal to y, -1 if the quantity is less than y, or 1 if the
  546. // quantity is greater than y.
  547. func (q *Quantity) CmpInt64(y int64) int {
  548. if q.d.Dec != nil {
  549. return q.d.Dec.Cmp(inf.NewDec(y, inf.Scale(0)))
  550. }
  551. return q.i.Cmp(int64Amount{value: y})
  552. }
  553. // Neg sets quantity to be the negative value of itself.
  554. func (q *Quantity) Neg() {
  555. q.s = ""
  556. if q.d.Dec == nil {
  557. q.i.value = -q.i.value
  558. return
  559. }
  560. q.d.Dec.Neg(q.d.Dec)
  561. }
  562. // Equal checks equality of two Quantities. This is useful for testing with
  563. // cmp.Equal.
  564. func (q Quantity) Equal(v Quantity) bool {
  565. return q.Cmp(v) == 0
  566. }
  567. // int64QuantityExpectedBytes is the expected width in bytes of the canonical string representation
  568. // of most Quantity values.
  569. const int64QuantityExpectedBytes = 18
  570. // String formats the Quantity as a string, caching the result if not calculated.
  571. // String is an expensive operation and caching this result significantly reduces the cost of
  572. // normal parse / marshal operations on Quantity.
  573. func (q *Quantity) String() string {
  574. if q == nil {
  575. return "<nil>"
  576. }
  577. if len(q.s) == 0 {
  578. result := make([]byte, 0, int64QuantityExpectedBytes)
  579. number, suffix := q.CanonicalizeBytes(result)
  580. number = append(number, suffix...)
  581. q.s = string(number)
  582. }
  583. return q.s
  584. }
  585. // MarshalJSON implements the json.Marshaller interface.
  586. func (q Quantity) MarshalJSON() ([]byte, error) {
  587. if len(q.s) > 0 {
  588. out := make([]byte, len(q.s)+2)
  589. out[0], out[len(out)-1] = '"', '"'
  590. copy(out[1:], q.s)
  591. return out, nil
  592. }
  593. result := make([]byte, int64QuantityExpectedBytes, int64QuantityExpectedBytes)
  594. result[0] = '"'
  595. number, suffix := q.CanonicalizeBytes(result[1:1])
  596. // if the same slice was returned to us that we passed in, avoid another allocation by copying number into
  597. // the source slice and returning that
  598. if len(number) > 0 && &number[0] == &result[1] && (len(number)+len(suffix)+2) <= int64QuantityExpectedBytes {
  599. number = append(number, suffix...)
  600. number = append(number, '"')
  601. return result[:1+len(number)], nil
  602. }
  603. // if CanonicalizeBytes needed more space than our slice provided, we may need to allocate again so use
  604. // append
  605. result = result[:1]
  606. result = append(result, number...)
  607. result = append(result, suffix...)
  608. result = append(result, '"')
  609. return result, nil
  610. }
  611. // ToUnstructured implements the value.UnstructuredConverter interface.
  612. func (q Quantity) ToUnstructured() interface{} {
  613. return q.String()
  614. }
  615. // UnmarshalJSON implements the json.Unmarshaller interface.
  616. // TODO: Remove support for leading/trailing whitespace
  617. func (q *Quantity) UnmarshalJSON(value []byte) error {
  618. l := len(value)
  619. if l == 4 && bytes.Equal(value, []byte("null")) {
  620. q.d.Dec = nil
  621. q.i = int64Amount{}
  622. return nil
  623. }
  624. if l >= 2 && value[0] == '"' && value[l-1] == '"' {
  625. value = value[1 : l-1]
  626. }
  627. parsed, err := ParseQuantity(strings.TrimSpace(string(value)))
  628. if err != nil {
  629. return err
  630. }
  631. // This copy is safe because parsed will not be referred to again.
  632. *q = parsed
  633. return nil
  634. }
  635. // NewQuantity returns a new Quantity representing the given
  636. // value in the given format.
  637. func NewQuantity(value int64, format Format) *Quantity {
  638. return &Quantity{
  639. i: int64Amount{value: value},
  640. Format: format,
  641. }
  642. }
  643. // NewMilliQuantity returns a new Quantity representing the given
  644. // value * 1/1000 in the given format. Note that BinarySI formatting
  645. // will round fractional values, and will be changed to DecimalSI for
  646. // values x where (-1 < x < 1) && (x != 0).
  647. func NewMilliQuantity(value int64, format Format) *Quantity {
  648. return &Quantity{
  649. i: int64Amount{value: value, scale: -3},
  650. Format: format,
  651. }
  652. }
  653. // NewScaledQuantity returns a new Quantity representing the given
  654. // value * 10^scale in DecimalSI format.
  655. func NewScaledQuantity(value int64, scale Scale) *Quantity {
  656. return &Quantity{
  657. i: int64Amount{value: value, scale: scale},
  658. Format: DecimalSI,
  659. }
  660. }
  661. // Value returns the unscaled value of q rounded up to the nearest integer away from 0.
  662. func (q *Quantity) Value() int64 {
  663. return q.ScaledValue(0)
  664. }
  665. // MilliValue returns the value of ceil(q * 1000); this could overflow an int64;
  666. // if that's a concern, call Value() first to verify the number is small enough.
  667. func (q *Quantity) MilliValue() int64 {
  668. return q.ScaledValue(Milli)
  669. }
  670. // ScaledValue returns the value of ceil(q / 10^scale).
  671. // For example, NewQuantity(1, DecimalSI).ScaledValue(Milli) returns 1000.
  672. // This could overflow an int64.
  673. // To detect overflow, call Value() first and verify the expected magnitude.
  674. func (q *Quantity) ScaledValue(scale Scale) int64 {
  675. if q.d.Dec == nil {
  676. i, _ := q.i.AsScaledInt64(scale)
  677. return i
  678. }
  679. dec := q.d.Dec
  680. return scaledValue(dec.UnscaledBig(), int(dec.Scale()), int(scale.infScale()))
  681. }
  682. // Set sets q's value to be value.
  683. func (q *Quantity) Set(value int64) {
  684. q.SetScaled(value, 0)
  685. }
  686. // SetMilli sets q's value to be value * 1/1000.
  687. func (q *Quantity) SetMilli(value int64) {
  688. q.SetScaled(value, Milli)
  689. }
  690. // SetScaled sets q's value to be value * 10^scale
  691. func (q *Quantity) SetScaled(value int64, scale Scale) {
  692. q.s = ""
  693. q.d.Dec = nil
  694. q.i = int64Amount{value: value, scale: scale}
  695. }