Debian Codegraph @

logattr.go

raw symbols SCIP
1 // Copyright (c) 2012-2023 Eli Janssen
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package mlog
6
7 import "fmt"
8
9 type Attr struct {
10 Key string
11 Value interface{}
12 }
13
14 func A(key string, value interface{}) *Attr {
15 return &Attr{key, value}
16 }
17
18 func (attr *Attr) writeBuf(w byteSliceWriter) {
19 if attr == nil {
20 return
21 }
22
23 // scratch buffer for intermediate writes
24 buf := bufPool.Get()
25 defer bufPool.Put(buf)
26
27 w.WriteString(attr.Key)
28 w.WriteString(`="`)
29 fmt.Fprint(buf, attr.Value)
30
31 // pull out byte slice from buff
32 b := buf.Bytes()
33 blen := buf.Len()
34 p := 0
35 for i := 0; i < blen; i++ {
36 switch b[i] {
37 case '"':
38 w.Write(b[p:i])
39 w.WriteString(`\"`)
40 p = i + 1
41 case '\t':
42 w.Write(b[p:i])
43 w.WriteString(`\t`)
44 p = i + 1
45 case '\r':
46 w.Write(b[p:i])
47 w.WriteString(`\r`)
48 p = i + 1
49 case '\n':
50 w.Write(b[p:i])
51 w.WriteString(`\n`)
52 p = i + 1
53 }
54 }
55 if p < blen {
56 w.Write(b[p:blen])
57 }
58
59 w.WriteByte('"')
60 // truncate intermediate buf so it is clean for next loop
61 buf.Truncate(0)
62 }
63
64 func (attr *Attr) String() string {
65 buf := bufPool.Get()
66 defer bufPool.Put(buf)
67 attr.writeBuf(buf)
68 return buf.String()
69 }
70
71 func attrsWriteBuf(w byteSliceWriter, attrs []*Attr) {
72 attrsLen := len(attrs)
73 for i, attr := range filterAttrs(attrs) {
74 attr.writeBuf(w)
75 if i != attrsLen-1 {
76 w.WriteByte(' ')
77 }
78 }
79 }
80
81 func filterAttrs(attrs []*Attr) []*Attr {
82 hasNil := false
83 for _, attr := range attrs {
84 if attr == nil {
85 hasNil = true
86 break
87 }
88 }
89 if !hasNil {
90 return attrs
91 }
92
93 filteredAttrs := make([]*Attr, 0, len(attrs))
94 for _, attr := range attrs {
95 if attr != nil {
96 filteredAttrs = append(filteredAttrs, attr)
97 }
98 }
99 return filteredAttrs
100 }