printers.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // MIT License
  2. //
  3. // Copyright (c) 2017 José Santos <henrique_1609@me.com>
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in all
  13. // copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. // SOFTWARE.
  22. package fastprinter
  23. import (
  24. "fmt"
  25. "io"
  26. "reflect"
  27. "sync"
  28. )
  29. const (
  30. stringBufferSize = 4096
  31. integerBufferSize = 20
  32. )
  33. var (
  34. _trueBytes = ([]byte)("true")
  35. _falseBytes = ([]byte)("false")
  36. pool_integerBuffer = newByteSliceBufferPool(integerBufferSize)
  37. pool_stringBuffer = newByteSliceBufferPool(stringBufferSize)
  38. errorType = reflect.TypeOf((*error)(nil)).Elem()
  39. fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
  40. )
  41. type byteSliceBuffer struct {
  42. bytes []byte
  43. }
  44. func newByteSliceBufferPool(size int) sync.Pool {
  45. return sync.Pool{
  46. New: func() interface{} {
  47. return &byteSliceBuffer{make([]byte, size, size)}
  48. },
  49. }
  50. }
  51. func Print(w io.Writer, i interface{}) (int, error) {
  52. return PrintValue(w, reflect.ValueOf(i))
  53. }
  54. func PrintPtr(w io.Writer, i interface{}) (int, error) {
  55. return PrintValue(w, reflect.ValueOf(i).Elem())
  56. }
  57. func PrintBool(w io.Writer, b bool) (int, error) {
  58. if b {
  59. return w.Write(_trueBytes)
  60. }
  61. return w.Write(_falseBytes)
  62. }
  63. func PrintString(ww io.Writer, st string) (c int, err error) {
  64. if st == "" {
  65. return 0, nil
  66. }
  67. numI := len(st) / stringBufferSize
  68. nextBucket := 0
  69. written := 0
  70. a := pool_stringBuffer.Get().(*byteSliceBuffer)
  71. for i := 0; i < numI; i++ {
  72. copy(a.bytes[:], st[nextBucket:nextBucket+stringBufferSize])
  73. nextBucket += stringBufferSize
  74. written, err = ww.Write(a.bytes[:])
  75. c += written
  76. if err != nil {
  77. return
  78. }
  79. }
  80. smallBucket := len(st) % stringBufferSize
  81. if smallBucket > 0 {
  82. copy(a.bytes[:], st[nextBucket:])
  83. written, err = ww.Write(a.bytes[:smallBucket])
  84. c += written
  85. }
  86. pool_stringBuffer.Put(a)
  87. return
  88. }
  89. func PrintUint(w io.Writer, i uint64) (int, error) {
  90. return formatBits(w, i, false)
  91. }
  92. func PrintInt(w io.Writer, i int64) (int, error) {
  93. return formatBits(w, uint64(i), i < 0)
  94. }
  95. // formatBits computes the string representation of u in the given base.
  96. // If neg is set, u is treated as negative int64 value.
  97. // Extracted from std package strconv
  98. func formatBits(dst io.Writer, u uint64, neg bool) (int, error) {
  99. var a = pool_integerBuffer.Get().(*byteSliceBuffer)
  100. i := integerBufferSize
  101. if neg {
  102. u = -u
  103. }
  104. // common case: use constants for / because
  105. // the compiler can optimize it into a multiply+shift
  106. if ^uintptr(0)>>32 == 0 {
  107. for u > uint64(^uintptr(0)) {
  108. q := u / 1e9
  109. us := uintptr(u - q*1e9) // us % 1e9 fits into a uintptr
  110. for j := 9; j > 0; j-- {
  111. i--
  112. qs := us / 10
  113. a.bytes[i] = byte(us - qs*10 + '0')
  114. us = qs
  115. }
  116. u = q
  117. }
  118. }
  119. // u guaranteed to fit into a uintptr
  120. us := uintptr(u)
  121. for us >= 10 {
  122. i--
  123. q := us / 10
  124. a.bytes[i] = byte(us - q*10 + '0')
  125. us = q
  126. }
  127. // u < 10
  128. i--
  129. a.bytes[i] = byte(us + '0')
  130. // add sign, if any
  131. if neg {
  132. i--
  133. a.bytes[i] = '-'
  134. }
  135. counter, err := dst.Write(a.bytes[i:])
  136. pool_integerBuffer.Put(a)
  137. return counter, err
  138. }
  139. // PrintValue prints a reflect.Value
  140. func PrintValue(w io.Writer, v reflect.Value) (int, error) {
  141. t := v.Type()
  142. k := t.Kind()
  143. if t.Implements(fmtStringerType) {
  144. return PrintString(w, v.Interface().(fmt.Stringer).String())
  145. }
  146. if t.Implements(errorType) {
  147. return PrintString(w, v.Interface().(error).Error())
  148. }
  149. if k == reflect.String {
  150. return PrintString(w, v.String())
  151. }
  152. if k >= reflect.Int && k <= reflect.Int64 {
  153. return PrintInt(w, v.Int())
  154. }
  155. if k >= reflect.Uint && k <= reflect.Uint64 {
  156. return PrintUint(w, v.Uint())
  157. }
  158. if k == reflect.Float64 || k == reflect.Float64 {
  159. return PrintFloat(w, v.Float())
  160. }
  161. if k == reflect.Bool {
  162. return PrintBool(w, v.Bool())
  163. }
  164. if k == reflect.Slice && t.Elem().Kind() == reflect.Uint8 {
  165. return w.Write(v.Bytes())
  166. }
  167. return fmt.Fprint(w, v.Interface())
  168. }