amount.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. "math/big"
  16. "strconv"
  17. inf "gopkg.in/inf.v0"
  18. )
  19. // Scale is used for getting and setting the base-10 scaled value.
  20. // Base-2 scales are omitted for mathematical simplicity.
  21. // See Quantity.ScaledValue for more details.
  22. type Scale int32
  23. // infScale adapts a Scale value to an inf.Scale value.
  24. func (s Scale) infScale() inf.Scale {
  25. return inf.Scale(-s) // inf.Scale is upside-down
  26. }
  27. const (
  28. Nano Scale = -9
  29. Micro Scale = -6
  30. Milli Scale = -3
  31. Kilo Scale = 3
  32. Mega Scale = 6
  33. Giga Scale = 9
  34. Tera Scale = 12
  35. Peta Scale = 15
  36. Exa Scale = 18
  37. )
  38. var (
  39. Zero = int64Amount{}
  40. // Used by quantity strings - treat as read only
  41. zeroBytes = []byte("0")
  42. )
  43. // int64Amount represents a fixed precision numerator and arbitrary scale exponent. It is faster
  44. // than operations on inf.Dec for values that can be represented as int64.
  45. type int64Amount struct {
  46. value int64
  47. scale Scale
  48. }
  49. // Sign returns 0 if the value is zero, -1 if it is less than 0, or 1 if it is greater than 0.
  50. func (a int64Amount) Sign() int {
  51. switch {
  52. case a.value == 0:
  53. return 0
  54. case a.value > 0:
  55. return 1
  56. default:
  57. return -1
  58. }
  59. }
  60. // AsInt64 returns the current amount as an int64 at scale 0, or false if the value cannot be
  61. // represented in an int64 OR would result in a loss of precision. This method is intended as
  62. // an optimization to avoid calling AsDec.
  63. func (a int64Amount) AsInt64() (int64, bool) {
  64. if a.scale == 0 {
  65. return a.value, true
  66. }
  67. if a.scale < 0 {
  68. // TODO: attempt to reduce factors, although it is assumed that factors are reduced prior
  69. // to the int64Amount being created.
  70. return 0, false
  71. }
  72. return positiveScaleInt64(a.value, a.scale)
  73. }
  74. // AsScaledInt64 returns an int64 representing the value of this amount at the specified scale,
  75. // rounding up, or false if that would result in overflow. (1e20).AsScaledInt64(1) would result
  76. // in overflow because 1e19 is not representable as an int64. Note that setting a scale larger
  77. // than the current value may result in loss of precision - i.e. (1e-6).AsScaledInt64(0) would
  78. // return 1, because 0.000001 is rounded up to 1.
  79. func (a int64Amount) AsScaledInt64(scale Scale) (result int64, ok bool) {
  80. if a.scale < scale {
  81. result, _ = negativeScaleInt64(a.value, scale-a.scale)
  82. return result, true
  83. }
  84. return positiveScaleInt64(a.value, a.scale-scale)
  85. }
  86. // AsDec returns an inf.Dec representation of this value.
  87. func (a int64Amount) AsDec() *inf.Dec {
  88. var base inf.Dec
  89. base.SetUnscaled(a.value)
  90. base.SetScale(inf.Scale(-a.scale))
  91. return &base
  92. }
  93. // Cmp returns 0 if a and b are equal, 1 if a is greater than b, or -1 if a is less than b.
  94. func (a int64Amount) Cmp(b int64Amount) int {
  95. switch {
  96. case a.scale == b.scale:
  97. // compare only the unscaled portion
  98. case a.scale > b.scale:
  99. result, remainder, exact := divideByScaleInt64(b.value, a.scale-b.scale)
  100. if !exact {
  101. return a.AsDec().Cmp(b.AsDec())
  102. }
  103. if result == a.value {
  104. switch {
  105. case remainder == 0:
  106. return 0
  107. case remainder > 0:
  108. return -1
  109. default:
  110. return 1
  111. }
  112. }
  113. b.value = result
  114. default:
  115. result, remainder, exact := divideByScaleInt64(a.value, b.scale-a.scale)
  116. if !exact {
  117. return a.AsDec().Cmp(b.AsDec())
  118. }
  119. if result == b.value {
  120. switch {
  121. case remainder == 0:
  122. return 0
  123. case remainder > 0:
  124. return 1
  125. default:
  126. return -1
  127. }
  128. }
  129. a.value = result
  130. }
  131. switch {
  132. case a.value == b.value:
  133. return 0
  134. case a.value < b.value:
  135. return -1
  136. default:
  137. return 1
  138. }
  139. }
  140. // Add adds two int64Amounts together, matching scales. It will return false and not mutate
  141. // a if overflow or underflow would result.
  142. func (a *int64Amount) Add(b int64Amount) bool {
  143. switch {
  144. case b.value == 0:
  145. return true
  146. case a.value == 0:
  147. a.value = b.value
  148. a.scale = b.scale
  149. return true
  150. case a.scale == b.scale:
  151. c, ok := int64Add(a.value, b.value)
  152. if !ok {
  153. return false
  154. }
  155. a.value = c
  156. case a.scale > b.scale:
  157. c, ok := positiveScaleInt64(a.value, a.scale-b.scale)
  158. if !ok {
  159. return false
  160. }
  161. c, ok = int64Add(c, b.value)
  162. if !ok {
  163. return false
  164. }
  165. a.scale = b.scale
  166. a.value = c
  167. default:
  168. c, ok := positiveScaleInt64(b.value, b.scale-a.scale)
  169. if !ok {
  170. return false
  171. }
  172. c, ok = int64Add(a.value, c)
  173. if !ok {
  174. return false
  175. }
  176. a.value = c
  177. }
  178. return true
  179. }
  180. // Sub removes the value of b from the current amount, or returns false if underflow would result.
  181. func (a *int64Amount) Sub(b int64Amount) bool {
  182. return a.Add(int64Amount{value: -b.value, scale: b.scale})
  183. }
  184. // AsScale adjusts this amount to set a minimum scale, rounding up, and returns true iff no precision
  185. // was lost. (1.1e5).AsScale(5) would return 1.1e5, but (1.1e5).AsScale(6) would return 1e6.
  186. func (a int64Amount) AsScale(scale Scale) (int64Amount, bool) {
  187. if a.scale >= scale {
  188. return a, true
  189. }
  190. result, exact := negativeScaleInt64(a.value, scale-a.scale)
  191. return int64Amount{value: result, scale: scale}, exact
  192. }
  193. // AsCanonicalBytes accepts a buffer to write the base-10 string value of this field to, and returns
  194. // either that buffer or a larger buffer and the current exponent of the value. The value is adjusted
  195. // until the exponent is a multiple of 3 - i.e. 1.1e5 would return "110", 3.
  196. func (a int64Amount) AsCanonicalBytes(out []byte) (result []byte, exponent int32) {
  197. mantissa := a.value
  198. exponent = int32(a.scale)
  199. amount, times := removeInt64Factors(mantissa, 10)
  200. exponent += int32(times)
  201. // make sure exponent is a multiple of 3
  202. var ok bool
  203. switch exponent % 3 {
  204. case 1, -2:
  205. amount, ok = int64MultiplyScale10(amount)
  206. if !ok {
  207. return infDecAmount{a.AsDec()}.AsCanonicalBytes(out)
  208. }
  209. exponent = exponent - 1
  210. case 2, -1:
  211. amount, ok = int64MultiplyScale100(amount)
  212. if !ok {
  213. return infDecAmount{a.AsDec()}.AsCanonicalBytes(out)
  214. }
  215. exponent = exponent - 2
  216. }
  217. return strconv.AppendInt(out, amount, 10), exponent
  218. }
  219. // AsCanonicalBase1024Bytes accepts a buffer to write the base-1024 string value of this field to, and returns
  220. // either that buffer or a larger buffer and the current exponent of the value. 2048 is 2 * 1024 ^ 1 and would
  221. // return []byte("2048"), 1.
  222. func (a int64Amount) AsCanonicalBase1024Bytes(out []byte) (result []byte, exponent int32) {
  223. value, ok := a.AsScaledInt64(0)
  224. if !ok {
  225. return infDecAmount{a.AsDec()}.AsCanonicalBase1024Bytes(out)
  226. }
  227. amount, exponent := removeInt64Factors(value, 1024)
  228. return strconv.AppendInt(out, amount, 10), exponent
  229. }
  230. // infDecAmount implements common operations over an inf.Dec that are specific to the quantity
  231. // representation.
  232. type infDecAmount struct {
  233. *inf.Dec
  234. }
  235. // AsScale adjusts this amount to set a minimum scale, rounding up, and returns true iff no precision
  236. // was lost. (1.1e5).AsScale(5) would return 1.1e5, but (1.1e5).AsScale(6) would return 1e6.
  237. func (a infDecAmount) AsScale(scale Scale) (infDecAmount, bool) {
  238. tmp := &inf.Dec{}
  239. tmp.Round(a.Dec, scale.infScale(), inf.RoundUp)
  240. return infDecAmount{tmp}, tmp.Cmp(a.Dec) == 0
  241. }
  242. // AsCanonicalBytes accepts a buffer to write the base-10 string value of this field to, and returns
  243. // either that buffer or a larger buffer and the current exponent of the value. The value is adjusted
  244. // until the exponent is a multiple of 3 - i.e. 1.1e5 would return "110", 3.
  245. func (a infDecAmount) AsCanonicalBytes(out []byte) (result []byte, exponent int32) {
  246. mantissa := a.Dec.UnscaledBig()
  247. exponent = int32(-a.Dec.Scale())
  248. amount := big.NewInt(0).Set(mantissa)
  249. // move all factors of 10 into the exponent for easy reasoning
  250. amount, times := removeBigIntFactors(amount, bigTen)
  251. exponent += times
  252. // make sure exponent is a multiple of 3
  253. for exponent%3 != 0 {
  254. amount.Mul(amount, bigTen)
  255. exponent--
  256. }
  257. return append(out, amount.String()...), exponent
  258. }
  259. // AsCanonicalBase1024Bytes accepts a buffer to write the base-1024 string value of this field to, and returns
  260. // either that buffer or a larger buffer and the current exponent of the value. 2048 is 2 * 1024 ^ 1 and would
  261. // return []byte("2048"), 1.
  262. func (a infDecAmount) AsCanonicalBase1024Bytes(out []byte) (result []byte, exponent int32) {
  263. tmp := &inf.Dec{}
  264. tmp.Round(a.Dec, 0, inf.RoundUp)
  265. amount, exponent := removeBigIntFactors(tmp.UnscaledBig(), big1024)
  266. return append(out, amount.String()...), exponent
  267. }