float.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. import "strconv"
  5. // func parseFloat(b []byte, bitsize int) (f float64, err error) {
  6. // if bitsize == 32 {
  7. // return parseFloat32(b)
  8. // } else {
  9. // return parseFloat64(b)
  10. // }
  11. // }
  12. func parseFloat32(b []byte) (f float32, err error) {
  13. return parseFloat32_custom(b)
  14. // return parseFloat32_strconv(b)
  15. }
  16. func parseFloat64(b []byte) (f float64, err error) {
  17. return parseFloat64_custom(b)
  18. // return parseFloat64_strconv(b)
  19. }
  20. func parseFloat32_strconv(b []byte) (f float32, err error) {
  21. f64, err := strconv.ParseFloat(stringView(b), 32)
  22. f = float32(f64)
  23. return
  24. }
  25. func parseFloat64_strconv(b []byte) (f float64, err error) {
  26. return strconv.ParseFloat(stringView(b), 64)
  27. }
  28. // ------ parseFloat custom below --------
  29. // We assume that a lot of floating point numbers in json files will be
  30. // those that are handwritten, and with defined precision (in terms of number
  31. // of digits after decimal point), etc.
  32. //
  33. // We further assume that this ones can be written in exact format.
  34. //
  35. // strconv.ParseFloat has some unnecessary overhead which we can do without
  36. // for the common case:
  37. //
  38. // - expensive char-by-char check to see if underscores are in right place
  39. // - testing for and skipping underscores
  40. // - check if the string matches ignorecase +/- inf, +/- infinity, nan
  41. // - support for base 16 (0xFFFF...)
  42. //
  43. // The functions below will try a fast-path for floats which can be decoded
  44. // without any loss of precision, meaning they:
  45. //
  46. // - fits within the significand bits of the 32-bits or 64-bits
  47. // - exponent fits within the exponent value
  48. // - there is no truncation (any extra numbers are all trailing zeros)
  49. //
  50. // To figure out what the values are for maxMantDigits, use this idea below:
  51. //
  52. // 2^23 = 838 8608 (between 10^ 6 and 10^ 7) (significand bits of uint32)
  53. // 2^32 = 42 9496 7296 (between 10^ 9 and 10^10) (full uint32)
  54. // 2^52 = 4503 5996 2737 0496 (between 10^15 and 10^16) (significand bits of uint64)
  55. // 2^64 = 1844 6744 0737 0955 1616 (between 10^19 and 10^20) (full uint64)
  56. //
  57. // Since we only allow for up to what can comfortably fit into the significand
  58. // ignoring the exponent, and we only try to parse iff significand fits into the
  59. // Exact powers of 10.
  60. var float64pow10 = [...]float64{
  61. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  62. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  63. 1e20, 1e21, 1e22,
  64. }
  65. var float32pow10 = [...]float32{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10}
  66. type floatinfo struct {
  67. mantbits uint8
  68. expbits uint8
  69. bias int16
  70. exactPow10 int8 // Exact powers of ten are <= 10^N (32: 10, 64: 22)
  71. exactInts int8 // Exact integers are <= 10^N
  72. maxMantDigits int8 // 10^19 fits in uint64, while 10^9 fits in uint32
  73. }
  74. var fi32 = floatinfo{23, 8, -127, 10, 7, 9} // maxMantDigits = 9
  75. var fi64 = floatinfo{52, 11, -1023, 22, 15, 19} // maxMantDigits = 19
  76. const fMax64 = 1e15
  77. const fMax32 = 1e7
  78. const fBase = 10
  79. func parseFloatErr(b []byte) error {
  80. return &strconv.NumError{
  81. Func: "ParseFloat",
  82. Err: strconv.ErrSyntax,
  83. Num: string(b),
  84. }
  85. }
  86. func parseFloat32_custom(b []byte) (f float32, err error) {
  87. mantissa, exp, neg, trunc, bad, ok := readFloat(b, fi32)
  88. _ = trunc
  89. if bad {
  90. return 0, parseFloatErr(b)
  91. }
  92. if ok {
  93. // parseFloatDebug(b, 32, false, exp, trunc, ok)
  94. f = float32(mantissa)
  95. if neg {
  96. f = -f
  97. }
  98. if exp != 0 {
  99. indx := fExpIndx(exp)
  100. if exp < 0 { // int / 10^k
  101. f /= float32pow10[indx]
  102. } else { // exp > 0
  103. if exp > fi32.exactPow10 {
  104. f *= float32pow10[exp-fi32.exactPow10]
  105. if f < -fMax32 || f > fMax32 { // exponent too large - outside range
  106. goto FALLBACK
  107. }
  108. indx = uint8(fi32.exactPow10)
  109. }
  110. f *= float32pow10[indx]
  111. }
  112. }
  113. return
  114. }
  115. FALLBACK:
  116. // parseFloatDebug(b, 32, true, exp, trunc, ok)
  117. return parseFloat32_strconv(b)
  118. }
  119. func parseFloat64_custom(b []byte) (f float64, err error) {
  120. mantissa, exp, neg, trunc, bad, ok := readFloat(b, fi64)
  121. _ = trunc
  122. if bad {
  123. return 0, parseFloatErr(b)
  124. }
  125. if ok {
  126. f = float64(mantissa)
  127. if neg {
  128. f = -f
  129. }
  130. if exp != 0 {
  131. indx := fExpIndx(exp)
  132. if exp < 0 { // int / 10^k
  133. f /= float64pow10[indx]
  134. } else { // exp > 0
  135. if exp > fi64.exactPow10 {
  136. f *= float64pow10[exp-fi64.exactPow10]
  137. if f < -fMax64 || f > fMax64 { // exponent too large - outside range
  138. goto FALLBACK
  139. }
  140. indx = uint8(fi64.exactPow10)
  141. }
  142. f *= float64pow10[indx]
  143. }
  144. }
  145. return
  146. }
  147. FALLBACK:
  148. return parseFloat64_strconv(b)
  149. }
  150. func fExpIndx(v int8) uint8 {
  151. if v < 0 {
  152. return uint8(-v)
  153. }
  154. return uint8(v)
  155. }
  156. func readFloat(s []byte, y floatinfo) (mantissa uint64, exp int8, neg, trunc, bad, ok bool) {
  157. var i uint // make it uint, so that we eliminate bounds checking
  158. var slen = uint(len(s))
  159. if slen == 0 {
  160. bad = true
  161. return
  162. }
  163. switch s[0] {
  164. case '+':
  165. i++
  166. case '-':
  167. neg = true
  168. i++
  169. }
  170. // we considered punting early if string has length > maxMantDigits, but this doesn't account
  171. // for trailing 0's e.g. 700000000000000000000 can be encoded exactly as it is 7e20
  172. // var sawdot, sawdigits, sawexp bool
  173. var sawdot, sawexp bool
  174. var nd, ndMant, dp int8
  175. L:
  176. for ; i < slen; i++ {
  177. switch s[i] {
  178. case '.':
  179. if sawdot {
  180. bad = true
  181. return
  182. }
  183. sawdot = true
  184. dp = nd
  185. case '0':
  186. if nd == 0 { // ignore leading zeros
  187. dp--
  188. continue
  189. }
  190. nd++
  191. if ndMant < y.maxMantDigits {
  192. // mantissa = (mantissa << 1) + (mantissa << 3)
  193. mantissa *= fBase
  194. ndMant++
  195. }
  196. case '1', '2', '3', '4', '5', '6', '7', '8', '9':
  197. // sawdigits = true
  198. nd++
  199. if ndMant < y.maxMantDigits {
  200. // mantissa = (mantissa << 1) + (mantissa << 3) + uint64(s[i]-'0')
  201. mantissa = mantissa*fBase + uint64(s[i]-'0')
  202. // mantissa *= fBase
  203. // mantissa += uint64(s[i] - '0')
  204. ndMant++
  205. } else {
  206. trunc = true
  207. return // break L
  208. }
  209. case 'e', 'E':
  210. sawexp = true
  211. break L
  212. default:
  213. bad = true
  214. return
  215. }
  216. }
  217. // if !sawdigits {
  218. // bad = true
  219. // return
  220. // }
  221. if !sawdot {
  222. dp = nd
  223. }
  224. if sawexp {
  225. i++
  226. if i < slen {
  227. var eneg bool
  228. if s[i] == '+' {
  229. i++
  230. } else if s[i] == '-' {
  231. i++
  232. eneg = true
  233. }
  234. if i < slen {
  235. // for exact match, exponent is 1 or 2 digits (float64: -22 to 37, float32: -1 to 17).
  236. // exit quick if exponent is more than 2 digits.
  237. if i+2 < slen {
  238. return
  239. }
  240. var e int8
  241. if s[i] < '0' || s[i] > '9' {
  242. bad = true
  243. return
  244. }
  245. e = e*fBase + int8(s[i]-'0') // (e << 1) + (e << 3) + int8(s[i]-'0')
  246. i++
  247. if i < slen {
  248. if s[i] < '0' || s[i] > '9' {
  249. bad = true
  250. return
  251. }
  252. e = e*fBase + int8(s[i]-'0') // (e << 1) + (e << 3) + int8(s[i]-'0')
  253. i++
  254. }
  255. if eneg {
  256. dp -= e
  257. } else {
  258. dp += e
  259. }
  260. }
  261. }
  262. }
  263. if mantissa != 0 {
  264. if mantissa>>y.mantbits != 0 {
  265. return
  266. }
  267. exp = dp - ndMant
  268. if exp < -y.exactPow10 || exp > y.exactInts+y.exactPow10 { // cannot handle it
  269. return
  270. }
  271. }
  272. ok = true // && !trunc // if trunc=true, we return early (so here trunc=false)
  273. return
  274. }
  275. // fMul10ShiftU64
  276. func parseFloatDebug(b []byte, bitsize int, strconv bool, exp int8, trunc, ok bool) {
  277. if strconv {
  278. xdebugf("parseFloat%d: delegating: %s, exp: %d, trunc: %v, ok: %v", bitsize, b, exp, trunc, ok)
  279. } else {
  280. xdebug2f("parseFloat%d: attempting: %s, exp: %d, trunc: %v, ok: %v", bitsize, b, exp, trunc, ok)
  281. }
  282. }