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, _, bad, ok := readFloat(b, fi32)
  88. if bad {
  89. return 0, parseFloatErr(b)
  90. }
  91. // defer parseFloatDebug(b, 32, &trunc, exp, trunc, ok)
  92. if ok {
  93. f = float32(mantissa)
  94. if neg {
  95. f = -f
  96. }
  97. if exp != 0 {
  98. indx := fExpIndx(exp)
  99. if exp < 0 { // int / 10^k
  100. f /= float32pow10[indx]
  101. } else { // exp > 0
  102. if exp > fi32.exactPow10 {
  103. f *= float32pow10[exp-fi32.exactPow10]
  104. if f < -fMax32 || f > fMax32 { // exponent too large - outside range
  105. goto FALLBACK
  106. }
  107. indx = uint8(fi32.exactPow10)
  108. }
  109. f *= float32pow10[indx]
  110. }
  111. }
  112. return
  113. }
  114. FALLBACK:
  115. return parseFloat32_strconv(b)
  116. }
  117. func parseFloat64_custom(b []byte) (f float64, err error) {
  118. mantissa, exp, neg, _, bad, ok := readFloat(b, fi64)
  119. if bad {
  120. return 0, parseFloatErr(b)
  121. }
  122. if ok {
  123. f = float64(mantissa)
  124. if neg {
  125. f = -f
  126. }
  127. if exp != 0 {
  128. indx := fExpIndx(exp)
  129. if exp < 0 { // int / 10^k
  130. f /= float64pow10[indx]
  131. } else { // exp > 0
  132. if exp > fi64.exactPow10 {
  133. f *= float64pow10[exp-fi64.exactPow10]
  134. if f < -fMax64 || f > fMax64 { // exponent too large - outside range
  135. goto FALLBACK
  136. }
  137. indx = uint8(fi64.exactPow10)
  138. }
  139. f *= float64pow10[indx]
  140. }
  141. }
  142. return
  143. }
  144. FALLBACK:
  145. return parseFloat64_strconv(b)
  146. }
  147. func fExpIndx(v int8) uint8 {
  148. if v < 0 {
  149. return uint8(-v)
  150. }
  151. return uint8(v)
  152. }
  153. func readFloat(s []byte, y floatinfo) (mantissa uint64, exp int8, neg, trunc, bad, ok bool) {
  154. var i uint // make it uint, so that we eliminate bounds checking
  155. var slen = uint(len(s))
  156. if slen == 0 {
  157. bad = true
  158. return
  159. }
  160. switch s[0] {
  161. case '+':
  162. i++
  163. case '-':
  164. neg = true
  165. i++
  166. }
  167. // we considered punting early if string has length > maxMantDigits, but this doesn't account
  168. // for trailing 0's e.g. 700000000000000000000 can be encoded exactly as it is 7e20
  169. // var sawdot, sawdigits, sawexp bool
  170. var sawdot, sawexp bool
  171. var nd, ndMant, dp int8
  172. L:
  173. for ; i < slen; i++ {
  174. switch s[i] {
  175. case '.':
  176. if sawdot {
  177. bad = true
  178. return
  179. }
  180. sawdot = true
  181. dp = nd
  182. case '0':
  183. if nd == 0 { // ignore leading zeros
  184. dp--
  185. continue
  186. }
  187. nd++
  188. if ndMant < y.maxMantDigits {
  189. // mantissa = (mantissa << 1) + (mantissa << 3)
  190. mantissa *= fBase
  191. ndMant++
  192. }
  193. case '1', '2', '3', '4', '5', '6', '7', '8', '9':
  194. // sawdigits = true
  195. nd++
  196. if ndMant < y.maxMantDigits {
  197. // mantissa = (mantissa << 1) + (mantissa << 3) + uint64(s[i]-'0')
  198. mantissa = mantissa*fBase + uint64(s[i]-'0')
  199. // mantissa *= fBase
  200. // mantissa += uint64(s[i] - '0')
  201. ndMant++
  202. } else {
  203. trunc = true
  204. return // break L
  205. }
  206. case 'e', 'E':
  207. sawexp = true
  208. break L
  209. default:
  210. bad = true
  211. return
  212. }
  213. }
  214. // if !sawdigits {
  215. // bad = true
  216. // return
  217. // }
  218. if !sawdot {
  219. dp = nd
  220. }
  221. if sawexp {
  222. i++
  223. if i < slen {
  224. var eneg bool
  225. if s[i] == '+' {
  226. i++
  227. } else if s[i] == '-' {
  228. i++
  229. eneg = true
  230. }
  231. if i < slen {
  232. // for exact match, exponent is 1 or 2 digits (float64: -22 to 37, float32: -1 to 17).
  233. // exit quick if exponent is more than 2 digits.
  234. if i+2 < slen {
  235. return
  236. }
  237. var e int8
  238. if s[i] < '0' || s[i] > '9' {
  239. bad = true
  240. return
  241. }
  242. e = e*fBase + int8(s[i]-'0') // (e << 1) + (e << 3) + int8(s[i]-'0')
  243. i++
  244. if i < slen {
  245. if s[i] < '0' || s[i] > '9' {
  246. bad = true
  247. return
  248. }
  249. e = e*fBase + int8(s[i]-'0') // (e << 1) + (e << 3) + int8(s[i]-'0')
  250. i++
  251. }
  252. if eneg {
  253. dp -= e
  254. } else {
  255. dp += e
  256. }
  257. }
  258. }
  259. }
  260. if mantissa != 0 {
  261. if mantissa>>y.mantbits != 0 {
  262. return
  263. }
  264. exp = dp - ndMant
  265. if exp < -y.exactPow10 || exp > y.exactInts+y.exactPow10 { // cannot handle it
  266. return
  267. }
  268. }
  269. ok = true // && !trunc // if trunc=true, we return early (so here trunc=false)
  270. return
  271. }
  272. // fMul10ShiftU64
  273. // func parseFloatDebug(b []byte, bitsize int, strconv *bool, exp int16, trunc, ok bool) {
  274. // if false && bitsize == 64 {
  275. // return
  276. // }
  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. // }