quantity.go 22 KB

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