-
Notifications
You must be signed in to change notification settings - Fork 12
/
text_handler.go
113 lines (107 loc) · 2.58 KB
/
text_handler.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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Copyright 2023 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package slog
import (
"encoding"
"encoding/json"
"fmt"
"log/slog"
"reflect"
"strconv"
"unicode"
"unicode/utf8"
"github.com/searKing/golang/go/unsafe"
)
func appendTextValue(s *handleState, v slog.Value) error {
switch v.Kind() {
case slog.KindString:
s.appendStringMayQuote(v.String())
case slog.KindTime:
s.appendTime(v.Time())
case slog.KindAny:
a := v.Any()
if tm, ok := a.(encoding.TextMarshaler); ok {
data, err := tm.MarshalText()
if err != nil {
return err
}
s.appendBytesMayQuote(data)
return nil
}
if err, ok := a.(error); ok && err != nil {
s.appendStringMayQuote(err.Error())
return nil
}
if tm, ok := a.(fmt.Stringer); ok {
s.appendStringMayQuote(tm.String())
return nil
}
if tm, ok := a.(json.Marshaler); ok {
data, err := tm.MarshalJSON()
if err != nil {
return err
}
s.appendBytesMayQuote(data)
return nil
}
if bs, ok := byteSlice(a); ok {
// As of Go 1.19, this only allocates for strings longer than 32 bytes.
s.buf.WriteString(strconv.Quote(unsafe.BytesToString(bs)))
return nil
}
s.appendStringMayQuote(fmt.Sprintf("%+v", v.Any()))
default:
s.appendStringMayQuote(v.String())
}
return nil
}
// byteSlice returns its argument as a []byte if the argument's
// underlying type is []byte, along with a second return value of true.
// Otherwise it returns nil, false.
func byteSlice(a any) ([]byte, bool) {
if bs, ok := a.([]byte); ok {
return bs, true
}
// Like Printf's %s, we allow both the slice type and the byte element type to be named.
t := reflect.TypeOf(a)
if t != nil && t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 {
return reflect.ValueOf(a).Bytes(), true
}
return nil, false
}
func needsQuoting(s string, unprintableOnly bool) bool {
if len(s) == 0 {
return true
}
for i := 0; i < len(s); {
b := s[i]
if b < utf8.RuneSelf {
// Quote anything except a backslash that would need quoting in a
// JSON string, as well as space and '='
if unprintableOnly {
if !safeSet[b] {
return true
}
} else {
if b != '\\' && (b == ' ' || b == '=' || !safeSet[b]) {
return true
}
}
i++
continue
}
r, size := utf8.DecodeRuneInString(s[i:])
if unprintableOnly {
if r == utf8.RuneError || !unicode.IsPrint(r) {
return true
}
} else {
if r == utf8.RuneError || unicode.IsSpace(r) || !unicode.IsPrint(r) {
return true
}
}
i += size
}
return false
}