quantity.go 21 KB

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