quantity.go 23 KB

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