Debian Codegraph @

fmt.go

raw
1 package tblfmt
2
3 import (
4 "bytes"
5 "database/sql"
6 "database/sql/driver"
7 "encoding/json/jsontext"
8 json "encoding/json/v2"
9 "fmt"
10 "math"
11 "reflect"
12 "strconv"
13 "strings"
14 "time"
15 "unicode"
16 "unicode/utf8"
17
18 runewidth "github.com/mattn/go-runewidth"
19 "golang.org/x/text/language"
20 "golang.org/x/text/message"
21 "golang.org/x/text/number"
22 )
23
24 // Formatter is the common interface for formatting values.
25 type Formatter interface {
26 // Header returns a slice of formatted values for the provided headers.
27 Header([]string) ([]*Value, error)
28 // Format returns a slice of formatted value the provided row values.
29 Format([]any) ([]*Value, error)
30 }
31
32 // EscapeFormatter is an escaping formatter, that handles formatting the
33 // standard Go types.
34 //
35 // When the encoder is not nil, then it will be passed any
36 // map[string]interface{} and []interface{} values encountered, otherwise the
37 // stdlib's [encoding/json/v2] will be used.
38 type EscapeFormatter struct {
39 // mask is used to format header values when the formatted value (after
40 // trimming spaces) is the empty string.
41 //
42 // Note: will have %d replaced with the column number (starting at 1).
43 mask string
44 // timeFormat is the format to use for time values.
45 timeFormat string
46 // timeLocation is the location to use for time values.
47 timeLocation *time.Location
48 // encoder will be used to encode map[string]interface{} and []interface{}
49 // types.
50 //
51 // If nil, the standard [encoding/json/v2] will be used instead.
52 encoder func(any) ([]byte, error)
53 // prefix is indent prefix used by the JSON encoder when encoder is nil.
54 prefix string
55 // indent is the indent used by the JSON encoder when encoder is nil.
56 indent string
57 // isJSON sets escaping JSON characters.
58 isJSON bool
59 // escapeHTML sets the JSON encoder used when encoder is nil to escape HTML
60 // characters.
61 escapeHTML bool
62 // isRaw sets raw escaping.
63 isRaw bool
64 // sep is the separator to use for raw (csv) encoding.
65 sep rune
66 // quote is the quote to use for raw (csv) encoding.
67 quote rune
68 // invalid is the value used for invalid utf8 runes when escaping.
69 invalid []byte
70 // invalidWidth is the rune width of the invalid value
71 invalidWidth int
72 // headerAlign is the default header values alignment
73 headerAlign Align
74 // align is the forced alignment value.
75 align Align
76 // numericLocalePrinter is the numeric locale printer.
77 numericLocalePrinter *message.Printer
78 }
79
80 // NewEscapeFormatter creates a escape formatter to handle basic Go values,
81 // such as []byte, string, time.Time, sql.Null*, and any
82 // [database/sql/driver.Valuer]. Formatting for
83 // map[string]interface{} and []interface{} will be passed to a marshaler
84 // provided by [WithEncoder], otherwise the standard [encoding/json/v2] will
85 // be used to marshal those values.
86 func NewEscapeFormatter(opts ...EscapeFormatterOption) *EscapeFormatter {
87 f := &EscapeFormatter{
88 mask: "%d",
89 timeFormat: time.RFC3339Nano,
90 indent: " ",
91 align: -1,
92 }
93 for _, o := range opts {
94 o(f)
95 }
96 return f
97 }
98
99 // Header satisfies the Formatter interface.
100 func (f *EscapeFormatter) Header(headers []string) ([]*Value, error) {
101 n := len(headers)
102 res := make([]*Value, n)
103 for i := range n {
104 s := strings.TrimSpace(headers[i])
105 switch {
106 case s == "" && strings.ContainsRune(f.mask, '%'):
107 s = fmt.Sprintf(f.mask, i+1)
108 case s == "":
109 s = f.mask
110 }
111 res[i] = FormatBytes([]byte(s), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote)
112 res[i].Align = f.headerAlign
113 }
114 return res, nil
115 }
116
117 // Format satisfies the Formatter interface.
118 func (f *EscapeFormatter) Format(vals []any) ([]*Value, error) {
119 n := len(vals)
120 res := make([]*Value, n)
121 left, right := AlignLeft, AlignRight
122 if f.align != -1 {
123 left, right = f.align, f.align
124 }
125 for i := range n {
126 v, err := f.format(deref(vals[i]), left, right, 0)
127 if err != nil {
128 return nil, err
129 }
130 res[i] = v
131 }
132 return res, nil
133 }
134
135 // maxValuerDepth is the maximum number of times [EscapeFormatter.format] will
136 // unwrap a [database/sql/driver.Valuer] before giving up and encoding the
137 // value, bounding recursion for a value that wraps itself.
138 const maxValuerDepth = 10
139
140 // format formats a single value, returning nil for a null value. depth is the
141 // number of [database/sql/driver.Valuer] values already unwrapped.
142 func (f *EscapeFormatter) format(val any, left, right Align, depth int) (*Value, error) {
143 // TODO: change time to v.AppendFormat() + pool
144 // TODO: use strconv.Format* for numeric times
145 // TODO: use pool
146 // TODO: allow configurable runes that can be escaped
147 switch v := val.(type) {
148 case nil:
149 return nil, nil
150 case bool:
151 return newValue(strconv.FormatBool(v), left, true), nil
152 case int, int8, int16, int32, int64,
153 uint, uint8, uint16, uint32, uint64:
154 var s string
155 if f.useNumericLocale() {
156 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v))
157 } else {
158 s = fmt.Sprintf("%d", v)
159 }
160 return f.number(s, right, unsignedInt64(v)), nil
161 case float32:
162 s, notNumber := floatString(float64(v))
163 switch {
164 case notNumber:
165 case f.useNumericLocale():
166 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v, number.MinFractionDigits(1)))
167 default:
168 s = strconv.FormatFloat(float64(v), 'g', -1, 32)
169 }
170 return f.number(s, right, notNumber), nil
171 case float64:
172 s, notNumber := floatString(v)
173 switch {
174 case notNumber:
175 case f.useNumericLocale():
176 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v, number.MinFractionDigits(1)))
177 default:
178 s = strconv.FormatFloat(v, 'g', -1, 64)
179 }
180 return f.number(s, right, notNumber), nil
181 case uintptr:
182 return newValue(fmt.Sprintf("(0x%x)", v), right, false), nil
183 case complex64:
184 return newValue(fmt.Sprintf("%g", v), right, false), nil
185 case complex128:
186 return newValue(fmt.Sprintf("%g", v), right, false), nil
187 case []byte:
188 return FormatBytes(v, f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote), nil
189 case string:
190 return FormatBytes([]byte(v), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote), nil
191 case time.Time:
192 t := v
193 if f.timeLocation != nil {
194 t = t.In(f.timeLocation)
195 }
196 return newValue(t.Format(f.timeFormat), left, false), nil
197 case sql.NullBool:
198 if v.Valid {
199 return newValue(strconv.FormatBool(v.Bool), left, true), nil
200 }
201 return nil, nil
202 case sql.NullByte:
203 if v.Valid {
204 var s string
205 if f.useNumericLocale() {
206 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Byte))
207 } else {
208 s = strconv.FormatUint(uint64(v.Byte), 10)
209 }
210 return f.number(s, right, false), nil
211 }
212 return nil, nil
213 case sql.NullFloat64:
214 if v.Valid {
215 s, notNumber := floatString(v.Float64)
216 switch {
217 case notNumber:
218 case f.useNumericLocale():
219 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Float64))
220 default:
221 s = strconv.FormatFloat(v.Float64, 'g', -1, 64)
222 }
223 return f.number(s, right, notNumber), nil
224 }
225 return nil, nil
226 case sql.NullInt16:
227 if v.Valid {
228 var s string
229 if f.useNumericLocale() {
230 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Int16))
231 } else {
232 s = strconv.FormatInt(int64(v.Int16), 10)
233 }
234 return f.number(s, right, false), nil
235 }
236 return nil, nil
237 case sql.NullInt32:
238 if v.Valid {
239 var s string
240 if f.useNumericLocale() {
241 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Int32))
242 } else {
243 s = strconv.FormatInt(int64(v.Int32), 10)
244 }
245 return f.number(s, right, false), nil
246 }
247 return nil, nil
248 case sql.NullInt64:
249 if v.Valid {
250 var s string
251 if f.useNumericLocale() {
252 s = f.numericLocalePrinter.Sprintf("%v", number.Decimal(v.Int64))
253 } else {
254 s = strconv.FormatInt(v.Int64, 10)
255 }
256 return f.number(s, right, false), nil
257 }
258 return nil, nil
259 case sql.NullString:
260 if v.Valid {
261 return FormatBytes([]byte(v.String), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote), nil
262 }
263 return nil, nil
264 case sql.NullTime:
265 if v.Valid {
266 t := v.Time
267 if f.timeLocation != nil {
268 t = t.In(f.timeLocation)
269 }
270 return newValue(t.Format(f.timeFormat), left, false), nil
271 }
272 return nil, nil
273 case sql.RawBytes:
274 return FormatBytes(v, f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote), nil
275 case fmt.Stringer:
276 return FormatBytes([]byte(v.String()), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote), nil
277 case driver.Valuer:
278 if z, ok := unwrapNull(v); ok {
279 if depth < maxValuerDepth {
280 return f.format(deref(z), left, right, depth+1)
281 }
282 break
283 }
284 // note: a Valuer returning an error is encoded below, as encoding the
285 // value is more useful to the reader than failing the entire result
286 // set.
287 if z, err := v.Value(); err == nil && depth < maxValuerDepth {
288 return f.format(deref(z), left, right, depth+1)
289 }
290 }
291 return f.encode(val)
292 }
293
294 // encode encodes a value not otherwise handled by [EscapeFormatter.format]
295 // using the configured encoder, or the standard [encoding/json/v2] when no
296 // encoder was configured.
297 func (f *EscapeFormatter) encode(val any) (*Value, error) {
298 // TODO: pool
299 if f.encoder != nil {
300 buf, err := f.encoder(val)
301 if err != nil {
302 return nil, err
303 }
304 return &Value{
305 Buf: buf,
306 Raw: true,
307 }, nil
308 }
309 // json encode
310 buf, err := json.Marshal(val, f.jsonOptions()...)
311 if err != nil {
312 return nil, err
313 }
314 buf = bytes.TrimSpace(buf)
315 if f.isJSON {
316 return &Value{
317 Buf: buf,
318 Raw: true,
319 }, nil
320 }
321 v := FormatBytes(buf, f.invalid, f.invalidWidth, false, f.isRaw, f.sep, f.quote)
322 v.Raw = true
323 return v, nil
324 }
325
326 // jsonOptions returns the [encoding/json/v2] options used to marshal a value.
327 //
328 // Note: the first four restore what the v1 encoding/json encoder did, as the
329 // v2 defaults differ -- v2 leaves map keys in map order, rejects invalid
330 // UTF-8, and writes a nil map or slice as {} or [] rather than null.
331 func (f *EscapeFormatter) jsonOptions() []json.Options {
332 opts := []json.Options{
333 json.Deterministic(true),
334 jsontext.AllowInvalidUTF8(true),
335 json.FormatNilMapAsNull(true),
336 json.FormatNilSliceAsNull(true),
337 jsontext.EscapeForHTML(f.escapeHTML),
338 }
339 // note: jsontext panics when the prefix or indent is anything but spaces
340 // and tabs, where the v1 encoder accepted any string, so both are dropped
341 // when not usable. An empty indent indents by nothing rather than
342 // producing compact output, so as with the v1 encoder the output is
343 // compact only when the prefix and indent are both empty.
344 prefix, indent := f.prefix, f.indent
345 if !isSpaceOrTab(prefix) {
346 prefix = ""
347 }
348 if !isSpaceOrTab(indent) {
349 indent = ""
350 }
351 if prefix != "" || indent != "" {
352 opts = append(opts, jsontext.WithIndent(indent))
353 if prefix != "" {
354 opts = append(opts, jsontext.WithIndentPrefix(prefix))
355 }
356 }
357 return opts
358 }
359
360 // isSpaceOrTab reports whether s contains only spaces and tabs.
361 func isSpaceOrTab(s string) bool {
362 return !strings.ContainsFunc(s, func(r rune) bool {
363 return r != ' ' && r != '\t'
364 })
365 }
366
367 // nullPkgPath is the package path of the generic [database/sql.Null] type.
368 var nullPkgPath = reflect.TypeOf(sql.Null[bool]{}).PkgPath()
369
370 // unwrapNull returns the value contained in a generic [database/sql.Null]
371 // value, and whether v is such a value. A nil value is returned for a null
372 // (invalid) value.
373 //
374 // The generic Null's own Value method cannot be used for this: it passes the
375 // contained value through [database/sql/driver.DefaultParameterConverter],
376 // which converts every unsigned integer to an int64 and rejects outright a
377 // uint64 with its high bit set, such as MySQL's max BIGINT UNSIGNED.
378 func unwrapNull(v any) (any, bool) {
379 typ := reflect.TypeOf(v)
380 if typ == nil {
381 return nil, false
382 }
383 // note: deref unwraps only one level, so a Null reached through a *any
384 // destination arrives here as a pointer.
385 val := reflect.ValueOf(v)
386 if typ.Kind() == reflect.Pointer {
387 typ, val = typ.Elem(), val.Elem()
388 }
389 if typ.Kind() != reflect.Struct || typ.PkgPath() != nullPkgPath ||
390 typ.NumField() != 2 ||
391 typ.Field(0).Name != "V" ||
392 typ.Field(1).Name != "Valid" || typ.Field(1).Type.Kind() != reflect.Bool {
393 return nil, false
394 }
395 // note: val is invalid for a nil pointer, whose Value method would panic.
396 if !val.IsValid() || !val.Field(1).Bool() {
397 return nil, true
398 }
399 return val.Field(0).Interface(), true
400 }
401
402 // useNumericLocale reports whether numbers are formatted for a locale.
403 //
404 // Note: never for JSON, which has a number type but no syntax for a grouping
405 // separator. Honoring it there would mean writing a number as a string, so
406 // that a column's JSON type would follow a display option; ignoring it keeps
407 // the type stable. csv, which has no types at all, applies it as psql does.
408 func (f *EscapeFormatter) useNumericLocale() bool {
409 return f.numericLocalePrinter != nil && !f.isJSON
410 }
411
412 // number returns a value for a formatted number. asString marks one that JSON
413 // writes as a string rather than as a number.
414 //
415 // A number formatted for a locale is escaped as any other value would be, as
416 // its grouping separator would otherwise be read as a csv field separator,
417 // leaving a bare 1,234,567 to be read as three fields.
418 func (f *EscapeFormatter) number(s string, align Align, asString bool) *Value {
419 switch {
420 case f.isJSON && asString:
421 // note: written as a JSON string of the same text the other formats
422 // show, never locale formatted, which JSON ignores anyway.
423 return newValue(s, align, false)
424 case !f.useNumericLocale():
425 return newValue(s, align, true)
426 }
427 v := FormatBytes([]byte(s), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote)
428 v.Align = align
429 return v
430 }
431
432 // floatString returns the text of a float that is not a finite number, and
433 // whether it is one.
434 //
435 // Note: the spellings are PostgreSQL's, which are what psql displays. JSON has
436 // no NaN or infinity at all, so these are written there as strings, as
437 // PostgreSQL's own to_jsonb does.
438 func floatString(f float64) (string, bool) {
439 switch {
440 case math.IsNaN(f):
441 return "NaN", true
442 case math.IsInf(f, 1):
443 return "Infinity", true
444 case math.IsInf(f, -1):
445 return "-Infinity", true
446 }
447 return "", false
448 }
449
450 // unsignedInt64 reports whether v is an unsigned 64 bit integer, such as
451 // MySQL's BIGINT UNSIGNED, which is written as a JSON string of its exact
452 // digits so that it survives a consumer reading a JSON number as an int64 or
453 // a float64.
454 //
455 // Note: by type and not by value, so that a column is one JSON type for every
456 // one of its rows. Deciding by value would write {"n":42} for one row and
457 // {"n":"18446744073709551615"} for the next, leaving a consumer unable to type
458 // the column without reading every value. uint is included whatever its width,
459 // so that the output does not differ between platforms.
460 func unsignedInt64(v any) bool {
461 switch v.(type) {
462 case uint, uint64:
463 return true
464 }
465 return false
466 }
467
468 // valueFromBuffer returns a value from a buffer known not to contain
469 // characters to escape.
470 func newValue(str string, align Align, raw bool) *Value {
471 v := &Value{Buf: []byte(str), Align: align, Raw: raw}
472 v.Width = len(v.Buf)
473 return v
474 }
475
476 // lowerhex is the set of lower hex characters.
477 const lowerhex = "0123456789abcdef"
478
479 // FormatBytes parses src, saving escaped (encoded) and unescaped runes to a
480 // Value, along with tab and newline positions in the generated buf.
481 func FormatBytes(src []byte, invalid []byte, invalidWidth int, isJSON, isRaw bool, sep, quote rune) *Value {
482 res := &Value{
483 Tabs: make([][][2]int, 1),
484 }
485 var tmp [4]byte
486 var r rune
487 var l, w int
488 for ; len(src) > 0; src = src[w:] {
489 r, w = rune(src[0]), 1
490 // lazy decode
491 if r >= utf8.RuneSelf {
492 r, w = utf8.DecodeRune(src)
493 }
494 // invalid rune decoded
495 if w == 1 && r == utf8.RuneError {
496 // replace with invalid (if set), otherwise hex encode
497 switch {
498 case invalid != nil:
499 res.Buf = append(res.Buf, invalid...)
500 res.Width += invalidWidth
501 res.Quoted = true
502 case isJSON:
503 res.Buf = append(res.Buf, '\\', 'u')
504 for s := 12; s >= 0; s -= 4 {
505 res.Buf = append(res.Buf, lowerhex[r>>uint(s)&0xf])
506 }
507 default:
508 res.Buf = append(res.Buf, '\\', 'x', lowerhex[src[0]>>4], lowerhex[src[0]&0xf])
509 res.Width += 4
510 res.Quoted = true
511 }
512 continue
513 }
514 // handle json encoding
515 if isJSON {
516 switch r {
517 case '\a':
518 res.Buf = append(res.Buf, '\\', 'u', '0', '0', '0', '7')
519 res.Width += 6
520 continue
521 case '\b':
522 res.Buf = append(res.Buf, '\\', 'b')
523 res.Width += 2
524 continue
525 case '\f':
526 res.Buf = append(res.Buf, '\\', 'f')
527 res.Width += 2
528 continue
529 case '\n':
530 res.Buf = append(res.Buf, '\\', 'n')
531 res.Width += 2
532 continue
533 case '\r':
534 res.Buf = append(res.Buf, '\\', 'r')
535 res.Width += 2
536 continue
537 case '\t':
538 res.Buf = append(res.Buf, '\\', 't')
539 res.Width += 2
540 continue
541 case '"':
542 res.Buf = append(res.Buf, '\\', '"')
543 res.Width += 2
544 continue
545 case '\\':
546 res.Buf = append(res.Buf, '\\', '\\')
547 res.Width += 2
548 continue
549 }
550 }
551 // handle raw encoding
552 if isRaw {
553 n := utf8.EncodeRune(tmp[:], r)
554 res.Buf = append(res.Buf, tmp[:n]...)
555 res.Width += runewidth.RuneWidth(r)
556 switch {
557 case r == sep:
558 res.Quoted = true
559 case r == quote && quote != 0:
560 res.Buf = append(res.Buf, tmp[:n]...)
561 res.Width += runewidth.RuneWidth(r)
562 res.Quoted = true
563 default:
564 res.Quoted = res.Quoted || unicode.IsSpace(r)
565 }
566 continue
567 }
568 // printable character
569 if strconv.IsGraphic(r) {
570 n := utf8.EncodeRune(tmp[:], r)
571 res.Buf = append(res.Buf, tmp[:n]...)
572 res.Width += runewidth.RuneWidth(r)
573 continue
574 }
575 switch r {
576 // escape \a \b \f \r \v (Go special characters)
577 case '\a':
578 res.Buf = append(res.Buf, '\\', 'a')
579 res.Width += 2
580 case '\b':
581 res.Buf = append(res.Buf, '\\', 'b')
582 res.Width += 2
583 case '\f':
584 res.Buf = append(res.Buf, '\\', 'f')
585 res.Width += 2
586 case '\r':
587 res.Buf = append(res.Buf, '\\', 'r')
588 res.Width += 2
589 case '\v':
590 res.Buf = append(res.Buf, '\\', 'v')
591 res.Width += 2
592 case '\t':
593 // save position
594 res.Tabs[l] = append(res.Tabs[l], [2]int{len(res.Buf), res.Width})
595 res.Buf = append(res.Buf, '\t')
596 res.Width = 0
597 case '\n':
598 // save position
599 res.Newlines = append(res.Newlines, [2]int{len(res.Buf), res.Width})
600 res.Buf = append(res.Buf, '\n')
601 res.Width = 0
602 // increase line count
603 res.Tabs = append(res.Tabs, nil)
604 l++
605 default:
606 switch {
607 // escape as \x00
608 case r < ' ' && !isJSON:
609 res.Buf = append(res.Buf, '\\', 'x', lowerhex[byte(r)>>4], lowerhex[byte(r)&0xf])
610 res.Width += 4
611 // escape as \u0000
612 case r > utf8.MaxRune:
613 r = 0xfffd
614 fallthrough
615 case r < 0x10000:
616 res.Buf = append(res.Buf, '\\', 'u')
617 for s := 12; s >= 0; s -= 4 {
618 res.Buf = append(res.Buf, lowerhex[r>>uint(s)&0xf])
619 }
620 res.Width += 6
621 // escape as \U00000000
622 default:
623 res.Buf = append(res.Buf, '\\', 'U')
624 for s := 28; s >= 0; s -= 4 {
625 res.Buf = append(res.Buf, lowerhex[r>>uint(s)&0xf])
626 }
627 res.Width += 10
628 }
629 }
630 }
631 return res
632 }
633
634 // Value contains information pertaining to a formatted value.
635 type Value struct {
636 // Buf is the formatted value.
637 Buf []byte
638 // Newlines are the positions of newline characters in Buf.
639 Newlines [][2]int
640 // Tabs are the positions of tab characters in Buf, split per line.
641 Tabs [][][2]int
642 // Width is the remaining width.
643 Width int
644 // Align indicates value alignment.
645 Align Align
646 // Raw tracks whether or not the value should be encoded or not.
647 Raw bool
648 // Quoted tracks whether or not a raw value should be quoted or not (ie,
649 // contains a space or non printable character).
650 Quoted bool
651 }
652
653 func (v *Value) String() string {
654 return string(v.Buf)
655 }
656
657 // LineWidth returns the line width (in runes) of line l.
658 func (v *Value) LineWidth(l, offset, tab int) int {
659 var width int
660 if l < len(v.Newlines) {
661 width += v.Newlines[l][1]
662 }
663 if len(v.Tabs[l]) != 0 {
664 width += tabwidth(v.Tabs[l], offset, tab)
665 }
666 if l == len(v.Newlines) {
667 width += v.Width
668 }
669 return width
670 }
671
672 // MaxWidth calculates the maximum width (in runes) of the longest line
673 // contained in Buf, relative to starting offset and the tab width.
674 func (v *Value) MaxWidth(offset, tab int) int {
675 // simple values do not have tabulations
676 width := v.Width
677 for l := range len(v.Tabs) {
678 width = max(width, v.LineWidth(l, offset, tab))
679 }
680 return width
681 }
682
683 // Align indicates an alignment direction for a value.
684 type Align int
685
686 // Align values.
687 const (
688 AlignLeft Align = iota
689 AlignRight
690 AlignCenter
691 )
692
693 // String satisfies the fmt.Stringer interface.
694 func (a Align) String() string {
695 switch a {
696 case AlignLeft:
697 return "Left"
698 case AlignRight:
699 return "Right"
700 case AlignCenter:
701 return "Center"
702 }
703 return fmt.Sprintf("Align(%d)", a)
704 }
705
706 // tabwidth returns the rune width of buf containing tabs from start position
707 // in buf, a column offset, and given tab width.
708 func tabwidth(tabs [][2]int, offset, tab int) int {
709 // log.Printf("tabs: %v, offset: %d, tab: %d", tabs, offset, tab)
710 width := offset
711 for i := range tabs {
712 width += tabs[i][1]
713 width += (tab - width%tab)
714 }
715 // log.Printf("res: %d", width-offset)
716 return width - offset
717 }
718
719 // EscapeFormatterOption is an escape formatter option.
720 type EscapeFormatterOption func(*EscapeFormatter)
721
722 // WithMask is an escape formatter option to set the mask used for empty
723 // headers.
724 func WithMask(mask string) EscapeFormatterOption {
725 return func(f *EscapeFormatter) {
726 f.mask = mask
727 }
728 }
729
730 // WithTimeFormat is an escape formatter option to set the time format used for
731 // time values.
732 func WithTimeFormat(timeFormat string) EscapeFormatterOption {
733 return func(f *EscapeFormatter) {
734 f.timeFormat = timeFormat
735 }
736 }
737
738 // WithTimeLocation is an escape formatter option to set the time location used
739 // for time values.
740 func WithTimeLocation(timeLocation *time.Location) EscapeFormatterOption {
741 return func(f *EscapeFormatter) {
742 f.timeLocation = timeLocation
743 }
744 }
745
746 // WithEncoder is an escape formatter option to set a standard Go encoder to
747 // use for encoding the value.
748 func WithEncoder(encoder func(any) ([]byte, error)) EscapeFormatterOption {
749 return func(f *EscapeFormatter) {
750 f.encoder = encoder
751 }
752 }
753
754 // WithIsJSON is an escape formatter option to enable special escaping for JSON
755 // characters in non-complex values.
756 func WithIsJSON(isJSON bool) EscapeFormatterOption {
757 return func(f *EscapeFormatter) {
758 f.isJSON = isJSON
759 }
760 }
761
762 // WithJSONConfig is an escape formatter option to set the JSON encoding
763 // prefix, indent value, and whether or not to escape HTML. Passed to
764 // [encoding/json/v2] when a marshaler has not been set on the escape
765 // formatter.
766 //
767 // The prefix and indent must contain only spaces and tabs, and are ignored
768 // otherwise. Output is compact when both are empty.
769 func WithJSONConfig(prefix, indent string, escapeHTML bool) EscapeFormatterOption {
770 return func(f *EscapeFormatter) {
771 f.prefix, f.indent, f.escapeHTML = prefix, indent, escapeHTML
772 }
773 }
774
775 // WithIsRaw is an escape formatter option to enable special escaping for raw
776 // characters in values.
777 func WithIsRaw(isRaw bool, sep, quote rune) EscapeFormatterOption {
778 return func(f *EscapeFormatter) {
779 f.isRaw, f.sep, f.quote = isRaw, sep, quote
780 }
781 }
782
783 // WithInvalid is an escape formatter option to set the invalid value used when
784 // an invalid rune is encountered during escaping.
785 func WithInvalid(invalid string) EscapeFormatterOption {
786 return func(f *EscapeFormatter) {
787 f.invalid = []byte(invalid)
788 f.invalidWidth = runewidth.StringWidth(invalid)
789 }
790 }
791
792 // WithHeaderAlign sets the alignment of header values.
793 func WithHeaderAlign(a Align) EscapeFormatterOption {
794 return func(f *EscapeFormatter) {
795 f.headerAlign = a
796 }
797 }
798
799 // WithAlign sets the forced alignment for values.
800 func WithAlign(a Align) EscapeFormatterOption {
801 return func(f *EscapeFormatter) {
802 f.align = a
803 }
804 }
805
806 // WithNumericLocale sets the numeric locale printer, which groups the digits
807 // of a number as the locale does, as psql's \pset numericlocale does.
808 //
809 // It has no effect on JSON output: a grouped number is not a JSON number, and
810 // writing it as a JSON string would make a column's type depend on a display
811 // option. Every other format applies it, csv quoting the fields that need it
812 // exactly as psql does.
813 func WithNumericLocale(enable bool, locale string) EscapeFormatterOption {
814 return func(f *EscapeFormatter) {
815 if enable {
816 tag := language.English
817 if t, err := language.Parse(locale); err == nil {
818 tag = t
819 }
820 f.numericLocalePrinter = message.NewPrinter(tag)
821 }
822 }
823 }
824
825 // deref dereferences a pointer to an interface.
826 func deref(v any) any {
827 switch z := v.(type) {
828 case nil:
829 return nil
830 case *any:
831 return *z
832 }
833 val := reflect.ValueOf(v)
834 if val.Kind() == reflect.Ptr {
835 if val.IsNil() {
836 return nil
837 }
838 val = val.Elem()
839 }
840 return val.Interface()
841 }