summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/rs/zerolog/internal/cbor/string.go
blob: a33890a5dfe743ad2eac062d32d3d728f1367258 (plain) (blame)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package cbor

import "fmt"

// AppendStrings encodes and adds an array of strings to the dst byte array.
func (e Encoder) AppendStrings(dst []byte, vals []string) []byte {
	major := majorTypeArray
	l := len(vals)
	if l <= additionalMax {
		lb := byte(l)
		dst = append(dst, major|lb)
	} else {
		dst = appendCborTypePrefix(dst, major, uint64(l))
	}
	for _, v := range vals {
		dst = e.AppendString(dst, v)
	}
	return dst
}

// AppendString encodes and adds a string to the dst byte array.
func (Encoder) AppendString(dst []byte, s string) []byte {
	major := majorTypeUtf8String

	l := len(s)
	if l <= additionalMax {
		lb := byte(l)
		dst = append(dst, major|lb)
	} else {
		dst = appendCborTypePrefix(dst, majorTypeUtf8String, uint64(l))
	}
	return append(dst, s...)
}

// AppendStringers encodes and adds an array of Stringer values
// to the dst byte array.
func (e Encoder) AppendStringers(dst []byte, vals []fmt.Stringer) []byte {
	if len(vals) == 0 {
		return e.AppendArrayEnd(e.AppendArrayStart(dst))
	}
	dst = e.AppendArrayStart(dst)
	dst = e.AppendStringer(dst, vals[0])
	if len(vals) > 1 {
		for _, val := range vals[1:] {
			dst = e.AppendStringer(dst, val)
		}
	}
	return e.AppendArrayEnd(dst)
}

// AppendStringer encodes and adds the Stringer value to the dst
// byte array.
func (e Encoder) AppendStringer(dst []byte, val fmt.Stringer) []byte {
	if val == nil {
		return e.AppendNil(dst)
	}
	return e.AppendString(dst, val.String())
}

// AppendBytes encodes and adds an array of bytes to the dst byte array.
func (Encoder) AppendBytes(dst, s []byte) []byte {
	major := majorTypeByteString

	l := len(s)
	if l <= additionalMax {
		lb := byte(l)
		dst = append(dst, major|lb)
	} else {
		dst = appendCborTypePrefix(dst, major, uint64(l))
	}
	return append(dst, s...)
}

// AppendEmbeddedJSON adds a tag and embeds input JSON as such.
func AppendEmbeddedJSON(dst, s []byte) []byte {
	major := majorTypeTags
	minor := additionalTypeEmbeddedJSON

	// Append the TAG to indicate this is Embedded JSON.
	dst = append(dst, major|additionalTypeIntUint16)
	dst = append(dst, byte(minor>>8))
	dst = append(dst, byte(minor&0xff))

	// Append the JSON Object as Byte String.
	major = majorTypeByteString

	l := len(s)
	if l <= additionalMax {
		lb := byte(l)
		dst = append(dst, major|lb)
	} else {
		dst = appendCborTypePrefix(dst, major, uint64(l))
	}
	return append(dst, s...)
}