/
contextWriter.go
65 lines (53 loc) · 1.45 KB
/
contextWriter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package udwJsonLib
import (
"github.com/tachyon-protocol/udw/udwStrings"
)
func writerReset(ctx *Context) {
ctx.writerPos = 0
}
func writerGetTmpString(ctx *Context) string {
return udwStrings.GetStringFromByteArrayNoAlloc(ctx.writerData[:ctx.writerPos])
}
func WriterWriteByte(ctx *Context, b byte) {
writerTryRealloc(ctx, 1)
ctx.writerData[ctx.writerPos] = b
ctx.writerPos++
}
func WriterWriteByteList(ctx *Context, s []byte) {
writerTryRealloc(ctx, len(s))
copy(ctx.writerData[ctx.writerPos:], s)
ctx.writerPos += len(s)
}
func WriterWriteString(ctx *Context, s string) {
writerTryRealloc(ctx, len(s))
copy(ctx.writerData[ctx.writerPos:], s)
ctx.writerPos += len(s)
}
func writerGetHeadBuffer(ctx *Context, size int) []byte {
writerTryRealloc(ctx, size)
return ctx.writerData[ctx.writerPos : ctx.writerPos+size]
}
func writerAddPos(ctx *Context, size int) {
ctx.writerPos += size
}
func writerTryRealloc(ctx *Context, toAddSize int) {
needSize := ctx.writerPos + toAddSize
if len(ctx.writerData) >= needSize {
return
}
needToAllocSize := len(ctx.writerData)*2 + toAddSize
allocSize := needToAllocSize
if allocSize <= 64 {
allocSize = 64
}
newBuf := make([]byte, allocSize)
copy(newBuf, ctx.writerData[:ctx.writerPos])
ctx.writerData = newBuf
return
}
func writerGetLastString(ctx *Context, size int) []byte {
if ctx.writerPos >= size {
return ctx.writerData[ctx.writerPos-size : ctx.writerPos]
}
return ctx.writerData[0:ctx.writerPos]
}