| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
} |