Debian Codegraph @

slicebuffer.go

raw symbols SCIP
1 package mlog
2
3 import (
4 "io"
5 "sync"
6 )
7
8 var bufPool = newSliceBufferPool()
9
10 type sliceBufferPool struct {
11 *sync.Pool
12 }
13
14 func newSliceBufferPool() *sliceBufferPool {
15 return &sliceBufferPool{
16 &sync.Pool{New: func() interface{} {
17 return &sliceBuffer{make([]byte, 0, 1024)}
18 }},
19 }
20 }
21
22 func (sp *sliceBufferPool) Get() *sliceBuffer {
23 return (sp.Pool.Get()).(*sliceBuffer)
24 }
25
26 func (sp *sliceBufferPool) Put(c *sliceBuffer) {
27 c.Truncate(0)
28 sp.Pool.Put(c)
29 }
30
31 type byteSliceWriter interface {
32 Write([]byte) (int, error)
33 WriteByte(byte) error
34 WriteString(string) (int, error)
35 Truncate(int)
36 }
37
38 type intSliceWriter interface {
39 byteSliceWriter
40 AppendIntWidth(int, int)
41 AppendIntWidthHex(int64, int)
42 }
43
44 type sliceBuffer struct {
45 data []byte
46 }
47
48 func (sb *sliceBuffer) AppendIntWidth(i int, wid int) {
49 digits := 0
50 // write digits backwards (easier/faster)
51 for i >= 10 {
52 q := i / 10
53 sb.data = append(sb.data, byte('0'+i-q*10))
54 i = q
55 digits++
56 }
57 sb.data = append(sb.data, byte('0'+i))
58 digits++
59
60 for j := wid - digits; j > 0; j-- {
61 sb.data = append(sb.data, '0')
62 digits++
63 }
64
65 // reverse to proper order
66 sblen := len(sb.data)
67 for i, j := sblen-digits, sblen-1; i < j; i, j = i+1, j-1 {
68 sb.data[i], sb.data[j] = sb.data[j], sb.data[i]
69 }
70 }
71
72 const hexdigits = "0123456789abcdefghijklmnopqrstuvwxyz"
73
74 func (sb *sliceBuffer) AppendIntWidthHex(i int64, wid int) {
75 u := uint64(i)
76
77 digits := 0
78 b := uint64(16)
79 m := uintptr(b) - 1
80 for u >= b {
81 sb.data = append(sb.data, hexdigits[uintptr(u)&m])
82 u >>= 4
83 digits++
84 }
85 sb.data = append(sb.data, hexdigits[uintptr(u)])
86 digits++
87
88 for j := wid - digits; j > 0; j-- {
89 sb.data = append(sb.data, '0')
90 digits++
91 }
92
93 // reverse to proper order
94 sblen := len(sb.data)
95 for i, j := sblen-digits, sblen-1; i < j; i, j = i+1, j-1 {
96 sb.data[i], sb.data[j] = sb.data[j], sb.data[i]
97 }
98 }
99
100 func (sb *sliceBuffer) Write(b []byte) (int, error) {
101 sb.data = append(sb.data, b...)
102 return len(b), nil
103 }
104
105 func (sb *sliceBuffer) WriteByte(c byte) error {
106 sb.data = append(sb.data, c)
107 return nil
108 }
109
110 func (sb *sliceBuffer) WriteString(s string) (int, error) {
111 sb.data = append(sb.data, s...)
112 return len(s), nil
113 }
114
115 func (sb *sliceBuffer) WriteTo(w io.Writer) (int64, error) {
116 n, err := w.Write(sb.data)
117 return int64(n), err
118 }
119
120 func (sb *sliceBuffer) Bytes() []byte {
121 return sb.data
122 }
123
124 func (sb *sliceBuffer) String() string {
125 return string(sb.data)
126 }
127
128 func (sb *sliceBuffer) Len() int {
129 return len(sb.data)
130 }
131
132 func (sb *sliceBuffer) Reset() {
133 sb.Truncate(0)
134 }
135
136 func (sb *sliceBuffer) Truncate(i int) {
137 sb.data = sb.data[:i]
138 }