summaryrefslogtreecommitdiff
path: root/vendor/github.com/uptrace/bun/internal/hex.go
blob: 6fae2bb78b41b793a6cb4330db86e2b81a480a7c (plain)
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
package internal

import (
	fasthex "github.com/tmthrgd/go-hex"
)

type HexEncoder struct {
	b       []byte
	written bool
}

func NewHexEncoder(b []byte) *HexEncoder {
	return &HexEncoder{
		b: b,
	}
}

func (enc *HexEncoder) Bytes() []byte {
	return enc.b
}

func (enc *HexEncoder) Write(b []byte) (int, error) {
	if !enc.written {
		enc.b = append(enc.b, '\'')
		enc.b = append(enc.b, `\x`...)
		enc.written = true
	}

	i := len(enc.b)
	enc.b = append(enc.b, make([]byte, fasthex.EncodedLen(len(b)))...)
	fasthex.Encode(enc.b[i:], b)

	return len(b), nil
}

func (enc *HexEncoder) Close() error {
	if enc.written {
		enc.b = append(enc.b, '\'')
	} else {
		enc.b = append(enc.b, "NULL"...)
	}
	return nil
}