http urls monitor.

stream_float.go 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package jsoniter
  2. import (
  3. "math"
  4. "strconv"
  5. )
  6. var pow10 []uint64
  7. func init() {
  8. pow10 = []uint64{1, 10, 100, 1000, 10000, 100000, 1000000}
  9. }
  10. // WriteFloat32 write float32 to stream
  11. func (stream *Stream) WriteFloat32(val float32) {
  12. abs := math.Abs(float64(val))
  13. fmt := byte('f')
  14. // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
  15. if abs != 0 {
  16. if float32(abs) < 1e-6 || float32(abs) >= 1e21 {
  17. fmt = 'e'
  18. }
  19. }
  20. stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 32)
  21. }
  22. // WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster
  23. func (stream *Stream) WriteFloat32Lossy(val float32) {
  24. if val < 0 {
  25. stream.writeByte('-')
  26. val = -val
  27. }
  28. if val > 0x4ffffff {
  29. stream.WriteFloat32(val)
  30. return
  31. }
  32. precision := 6
  33. exp := uint64(1000000) // 6
  34. lval := uint64(float64(val)*float64(exp) + 0.5)
  35. stream.WriteUint64(lval / exp)
  36. fval := lval % exp
  37. if fval == 0 {
  38. return
  39. }
  40. stream.writeByte('.')
  41. for p := precision - 1; p > 0 && fval < pow10[p]; p-- {
  42. stream.writeByte('0')
  43. }
  44. stream.WriteUint64(fval)
  45. for stream.buf[len(stream.buf)-1] == '0' {
  46. stream.buf = stream.buf[:len(stream.buf)-1]
  47. }
  48. }
  49. // WriteFloat64 write float64 to stream
  50. func (stream *Stream) WriteFloat64(val float64) {
  51. abs := math.Abs(val)
  52. fmt := byte('f')
  53. // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
  54. if abs != 0 {
  55. if abs < 1e-6 || abs >= 1e21 {
  56. fmt = 'e'
  57. }
  58. }
  59. stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 64)
  60. }
  61. // WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster
  62. func (stream *Stream) WriteFloat64Lossy(val float64) {
  63. if val < 0 {
  64. stream.writeByte('-')
  65. val = -val
  66. }
  67. if val > 0x4ffffff {
  68. stream.WriteFloat64(val)
  69. return
  70. }
  71. precision := 6
  72. exp := uint64(1000000) // 6
  73. lval := uint64(val*float64(exp) + 0.5)
  74. stream.WriteUint64(lval / exp)
  75. fval := lval % exp
  76. if fval == 0 {
  77. return
  78. }
  79. stream.writeByte('.')
  80. for p := precision - 1; p > 0 && fval < pow10[p]; p-- {
  81. stream.writeByte('0')
  82. }
  83. stream.WriteUint64(fval)
  84. for stream.buf[len(stream.buf)-1] == '0' {
  85. stream.buf = stream.buf[:len(stream.buf)-1]
  86. }
  87. }