summaryrefslogtreecommitdiff
path: root/lib/fmtutil/fmt.go
blob: b310eb67ff3431bffa5fddcadffcdca9a51b2656 (plain)
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
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package fmtutil

import (
	"fmt"
	"strings"
)

// FmtStateString returns the fmt.Printf string that produced a given
// fmt.State and verb.
func FmtStateString(st fmt.State, verb rune) string {
	var ret strings.Builder
	ret.WriteByte('%')
	for _, flag := range []int{'-', '+', '#', ' ', '0'} {
		if st.Flag(flag) {
			ret.WriteByte(byte(flag))
		}
	}
	if width, ok := st.Width(); ok {
		fmt.Fprintf(&ret, "%v", width)
	}
	if prec, ok := st.Precision(); ok {
		if prec == 0 {
			ret.WriteByte('.')
		} else {
			fmt.Fprintf(&ret, ".%v", prec)
		}
	}
	ret.WriteRune(verb)
	return ret.String()
}

// FormatByteArrayStringer is function for helping to implement
// fmt.Formatter for []byte or [n]byte types that have a custom string
// representation.  Use it like:
//
//	type MyType [16]byte
//
//	func (val MyType) String() string {
//	    …
//	}
//
//	func (val MyType) Format(f fmt.State, verb rune) {
//	    util.FormatByteArrayStringer(val, val[:], f, verb)
//	}
func FormatByteArrayStringer(
	obj interface {
		fmt.Stringer
		fmt.Formatter
	},
	objBytes []byte,
	f fmt.State, verb rune,
) {
	switch verb {
	case 'v':
		if !f.Flag('#') {
			FormatByteArrayStringer(obj, objBytes, f, 's') // as a string
		} else {
			byteStr := fmt.Sprintf("%#v", objBytes)
			objType := fmt.Sprintf("%T", obj)
			objStr := objType + strings.TrimPrefix(byteStr, "[]byte")
			fmt.Fprintf(f, FmtStateString(f, 's'), objStr)
		}
	case 's', 'q': // string
		fmt.Fprintf(f, FmtStateString(f, verb), obj.String())
	default:
		fmt.Fprintf(f, FmtStateString(f, verb), objBytes)
	}
}