number.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. package msgp
  2. import (
  3. "math"
  4. "math/bits"
  5. "strconv"
  6. )
  7. // The portable parts of the Number implementation
  8. // Number can be
  9. // an int64, uint64, float32,
  10. // or float64 internally.
  11. // It can decode itself
  12. // from any of the native
  13. // messagepack number types.
  14. // The zero-value of Number
  15. // is Int(0). Using the equality
  16. // operator with Number compares
  17. // both the type and the value
  18. // of the number.
  19. type Number struct {
  20. // internally, this
  21. // is just a tagged union.
  22. // the raw bits of the number
  23. // are stored the same way regardless.
  24. bits uint64
  25. typ Type
  26. }
  27. // AsInt sets the number to an int64.
  28. func (n *Number) AsInt(i int64) {
  29. // we always store int(0)
  30. // as {0, InvalidType} in
  31. // order to preserve
  32. // the behavior of the == operator
  33. if i == 0 {
  34. n.typ = InvalidType
  35. n.bits = 0
  36. return
  37. }
  38. n.typ = IntType
  39. n.bits = uint64(i)
  40. }
  41. // AsUint sets the number to a uint64.
  42. func (n *Number) AsUint(u uint64) {
  43. n.typ = UintType
  44. n.bits = u
  45. }
  46. // AsFloat32 sets the value of the number
  47. // to a float32.
  48. func (n *Number) AsFloat32(f float32) {
  49. n.typ = Float32Type
  50. n.bits = uint64(math.Float32bits(f))
  51. }
  52. // AsFloat64 sets the value of the
  53. // number to a float64.
  54. func (n *Number) AsFloat64(f float64) {
  55. n.typ = Float64Type
  56. n.bits = math.Float64bits(f)
  57. }
  58. // Int casts the number as an int64, and
  59. // returns whether or not that was the
  60. // underlying type.
  61. func (n *Number) Int() (int64, bool) {
  62. return int64(n.bits), n.typ == IntType || n.typ == InvalidType
  63. }
  64. // Uint casts the number as a uint64, and returns
  65. // whether or not that was the underlying type.
  66. func (n *Number) Uint() (uint64, bool) {
  67. return n.bits, n.typ == UintType
  68. }
  69. // Float casts the number to a float64, and
  70. // returns whether that was the underlying
  71. // type (either a float64 or a float32).
  72. func (n *Number) Float() (float64, bool) {
  73. switch n.typ {
  74. case Float32Type:
  75. return float64(math.Float32frombits(uint32(n.bits))), true
  76. case Float64Type:
  77. return math.Float64frombits(n.bits), true
  78. default:
  79. return 0.0, false
  80. }
  81. }
  82. // Type will return one of:
  83. // Float64Type, Float32Type, UintType, or IntType.
  84. func (n *Number) Type() Type {
  85. if n.typ == InvalidType {
  86. return IntType
  87. }
  88. return n.typ
  89. }
  90. // DecodeMsg implements msgp.Decodable
  91. func (n *Number) DecodeMsg(r *Reader) error {
  92. typ, err := r.NextType()
  93. if err != nil {
  94. return err
  95. }
  96. switch typ {
  97. case Float32Type:
  98. f, err := r.ReadFloat32()
  99. if err != nil {
  100. return err
  101. }
  102. n.AsFloat32(f)
  103. return nil
  104. case Float64Type:
  105. f, err := r.ReadFloat64()
  106. if err != nil {
  107. return err
  108. }
  109. n.AsFloat64(f)
  110. return nil
  111. case IntType:
  112. i, err := r.ReadInt64()
  113. if err != nil {
  114. return err
  115. }
  116. n.AsInt(i)
  117. return nil
  118. case UintType:
  119. u, err := r.ReadUint64()
  120. if err != nil {
  121. return err
  122. }
  123. n.AsUint(u)
  124. return nil
  125. default:
  126. return TypeError{Encoded: typ, Method: IntType}
  127. }
  128. }
  129. // UnmarshalMsg implements msgp.Unmarshaler
  130. func (n *Number) UnmarshalMsg(b []byte) ([]byte, error) {
  131. typ := NextType(b)
  132. switch typ {
  133. case IntType:
  134. i, o, err := ReadInt64Bytes(b)
  135. if err != nil {
  136. return b, err
  137. }
  138. n.AsInt(i)
  139. return o, nil
  140. case UintType:
  141. u, o, err := ReadUint64Bytes(b)
  142. if err != nil {
  143. return b, err
  144. }
  145. n.AsUint(u)
  146. return o, nil
  147. case Float64Type:
  148. f, o, err := ReadFloat64Bytes(b)
  149. if err != nil {
  150. return b, err
  151. }
  152. n.AsFloat64(f)
  153. return o, nil
  154. case Float32Type:
  155. f, o, err := ReadFloat32Bytes(b)
  156. if err != nil {
  157. return b, err
  158. }
  159. n.AsFloat32(f)
  160. return o, nil
  161. default:
  162. return b, TypeError{Method: IntType, Encoded: typ}
  163. }
  164. }
  165. // MarshalMsg implements msgp.Marshaler
  166. func (n *Number) MarshalMsg(b []byte) ([]byte, error) {
  167. switch n.typ {
  168. case IntType:
  169. return AppendInt64(b, int64(n.bits)), nil
  170. case UintType:
  171. return AppendUint64(b, n.bits), nil
  172. case Float64Type:
  173. return AppendFloat64(b, math.Float64frombits(n.bits)), nil
  174. case Float32Type:
  175. return AppendFloat32(b, math.Float32frombits(uint32(n.bits))), nil
  176. default:
  177. return AppendInt64(b, 0), nil
  178. }
  179. }
  180. // EncodeMsg implements msgp.Encodable
  181. func (n *Number) EncodeMsg(w *Writer) error {
  182. switch n.typ {
  183. case IntType:
  184. return w.WriteInt64(int64(n.bits))
  185. case UintType:
  186. return w.WriteUint64(n.bits)
  187. case Float64Type:
  188. return w.WriteFloat64(math.Float64frombits(n.bits))
  189. case Float32Type:
  190. return w.WriteFloat32(math.Float32frombits(uint32(n.bits)))
  191. default:
  192. return w.WriteInt64(0)
  193. }
  194. }
  195. // CoerceInt attempts to coerce the value of
  196. // the number into a signed integer and returns
  197. // whether it was successful.
  198. // "Success" implies that no precision in the value of
  199. // the number was lost, which means that the number was an integer or
  200. // a floating point that mapped exactly to an integer without rounding.
  201. func (n *Number) CoerceInt() (int64, bool) {
  202. switch n.typ {
  203. case InvalidType, IntType:
  204. // InvalidType just means un-initialized.
  205. return int64(n.bits), true
  206. case UintType:
  207. return int64(n.bits), n.bits <= math.MaxInt64
  208. case Float32Type:
  209. f := math.Float32frombits(uint32(n.bits))
  210. if n.isExactInt() && f <= math.MaxInt64 && f >= math.MinInt64 {
  211. return int64(f), true
  212. }
  213. if n.bits == 0 || n.bits == 1<<31 {
  214. return 0, true
  215. }
  216. case Float64Type:
  217. f := math.Float64frombits(n.bits)
  218. if n.isExactInt() && f <= math.MaxInt64 && f >= math.MinInt64 {
  219. return int64(f), true
  220. }
  221. return 0, n.bits == 0 || n.bits == 1<<63
  222. }
  223. return 0, false
  224. }
  225. // CoerceUInt attempts to coerce the value of
  226. // the number into an unsigned integer and returns
  227. // whether it was successful.
  228. // "Success" implies that no precision in the value of
  229. // the number was lost, which means that the number was an integer or
  230. // a floating point that mapped exactly to an integer without rounding.
  231. func (n *Number) CoerceUInt() (uint64, bool) {
  232. switch n.typ {
  233. case InvalidType, IntType:
  234. // InvalidType just means un-initialized.
  235. if int64(n.bits) >= 0 {
  236. return n.bits, true
  237. }
  238. case UintType:
  239. return n.bits, true
  240. case Float32Type:
  241. f := math.Float32frombits(uint32(n.bits))
  242. if f >= 0 && f <= math.MaxUint64 && n.isExactInt() {
  243. return uint64(f), true
  244. }
  245. if n.bits == 0 || n.bits == 1<<31 {
  246. return 0, true
  247. }
  248. case Float64Type:
  249. f := math.Float64frombits(n.bits)
  250. if f >= 0 && f <= math.MaxUint64 && n.isExactInt() {
  251. return uint64(f), true
  252. }
  253. return 0, n.bits == 0 || n.bits == 1<<63
  254. }
  255. return 0, false
  256. }
  257. // isExactInt will return true if the number represents an integer value.
  258. // NaN, Inf returns false.
  259. func (n *Number) isExactInt() bool {
  260. var eBits int // Exponent bits
  261. var mBits int // Mantissa bits
  262. switch n.typ {
  263. case InvalidType, IntType, UintType:
  264. return true
  265. case Float32Type:
  266. eBits = 8
  267. mBits = 23
  268. case Float64Type:
  269. eBits = 11
  270. mBits = 52
  271. default:
  272. return false
  273. }
  274. // Calculate float parts
  275. exp := int(n.bits>>mBits) & ((1 << eBits) - 1)
  276. mant := n.bits & ((1 << mBits) - 1)
  277. if exp == 0 && mant == 0 {
  278. // Handle zero value.
  279. return true
  280. }
  281. exp -= (1 << (eBits - 1)) - 1
  282. if exp < 0 || exp == 1<<(eBits-1) {
  283. // Negative exponent is never integer (except zero handled above)
  284. // Handles NaN (exp all 1s)
  285. return false
  286. }
  287. if exp >= mBits {
  288. // If we have more exponent than mantissa bits it is always an integer.
  289. return true
  290. }
  291. // Check if all bits below the exponent are zero.
  292. return bits.TrailingZeros64(mant) >= mBits-exp
  293. }
  294. // CoerceFloat returns the number as a float64.
  295. // If the number is an integer, it will be
  296. // converted to a float64 with the closest representation.
  297. func (n *Number) CoerceFloat() float64 {
  298. switch n.typ {
  299. case IntType:
  300. return float64(int64(n.bits))
  301. case UintType:
  302. return float64(n.bits)
  303. case Float32Type:
  304. return float64(math.Float32frombits(uint32(n.bits)))
  305. case Float64Type:
  306. return math.Float64frombits(n.bits)
  307. default:
  308. return 0.0
  309. }
  310. }
  311. // Msgsize implements msgp.Sizer
  312. func (n *Number) Msgsize() int {
  313. switch n.typ {
  314. case Float32Type:
  315. return Float32Size
  316. case Float64Type:
  317. return Float64Size
  318. case IntType:
  319. return Int64Size
  320. case UintType:
  321. return Uint64Size
  322. default:
  323. return 1 // fixint(0)
  324. }
  325. }
  326. // MarshalJSON implements json.Marshaler
  327. func (n *Number) MarshalJSON() ([]byte, error) {
  328. t := n.Type()
  329. if t == InvalidType {
  330. return []byte{'0'}, nil
  331. }
  332. out := make([]byte, 0, 32)
  333. switch t {
  334. case Float32Type, Float64Type:
  335. f, _ := n.Float()
  336. return strconv.AppendFloat(out, f, 'f', -1, 64), nil
  337. case IntType:
  338. i, _ := n.Int()
  339. return strconv.AppendInt(out, i, 10), nil
  340. case UintType:
  341. u, _ := n.Uint()
  342. return strconv.AppendUint(out, u, 10), nil
  343. default:
  344. panic("(*Number).typ is invalid")
  345. }
  346. }
  347. // String implements fmt.Stringer
  348. func (n *Number) String() string {
  349. switch n.typ {
  350. case InvalidType:
  351. return "0"
  352. case Float32Type, Float64Type:
  353. f, _ := n.Float()
  354. return strconv.FormatFloat(f, 'f', -1, 64)
  355. case IntType:
  356. i, _ := n.Int()
  357. return strconv.FormatInt(i, 10)
  358. case UintType:
  359. u, _ := n.Uint()
  360. return strconv.FormatUint(u, 10)
  361. default:
  362. panic("(*Number).typ is invalid")
  363. }
  364. }