amount.go 8.6 KB

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