Playground
doc.gno
// Package ufmt is a preview of gno.land/p/nt/ufmt/v2, published here before
// that path exists.
//
// This is v2 of ufmt. It is not yet published at its expected path,
// gno.land/p/nt/ufmt/v2. Until it is, import it from
// gno.land/p/nym-moultest123/vendor/nt/ufmt/v2; once gno.land/p/nt/ufmt/v2 is live,
// switch the import and nothing else, because the API is meant to be the same.
// This path is then frozen and never updated again.
//
// v0 (gno.land/p/nt/ufmt/v0) supports a handful of verbs and no flags, so
// "%08x", "%X" and "%-10s" print "(unhandled)" or drop their padding without a
// word. v2 follows Go's fmt instead: the same flags, widths, precisions and
// verbs, and the same error strings in place of panics. Where it cannot follow
// Go, because gno has no reflect, it says so below.
//
// Supported, as in Go's fmt:
//
// flags '+' '-' '#' ' ' '0'
// width %8d, %*d, and a negative * width left-justifies
// precision %.2f, %.*f, %.3s (in runes)
// indexes %[2]d %[1]s, %[1]*[2]d
// general %v %+v %#v %T %%
// bool %t
// integer %b %c %d %o %O %q %x %X %U, every int and uint type
// float %b %e %E %f %F %g %G %x %X, float32 and float64
// string %s %q %x %X, and []byte the same way
// errors %w in Errorf, unwrapped by errors.Unwrap and errors.Is
// methods Formatter, GoStringer, error, Stringer, in Go's order
// composite []T of the basic types, []any, []error, and map[string]T
// with its keys sorted, as Go prints them
//
// Errors are written into the output, never panicked: "%!d(string=hi)" for a
// wrong type, "%!d(MISSING)" for a missing argument, "%!(EXTRA int=1)" for an
// unused one, "%!(NOVERB)" for a trailing '%'.
//
// What gno cannot do, and what v2 prints instead:
//
// - no reflect, so a struct, a pointer, a named type without a String
// method, or a slice or map of anything other than the types listed above
// prints "(unhandled)", and %T names only the types it knows ("unknown"
// otherwise). Give the type a String method.
// - %p is not supported.
//
// What changed from v0, so a migration is a review and not a find-and-replace:
//
// - Sprint adds a space only between two operands when neither is a string,
// as Go does; v0 put a space between every pair.
// - %v of a float, and Sprint of one, is the shortest representation ("3.14"),
// as Go does; v0 printed "%f" ("3.140000") from Sprint.
// - %e defaults to 6 digits after the point, as Go does; v0 used 2.
// - %v of a []byte prints "[104 105]", as Go does; v0 wrote the raw bytes.
// Use %s for the string.
// - a missing or extra argument, or a trailing '%', is written into the
// output instead of panicking.
// - an error is preferred to a String method when a value has both.
package ufmt
format.gno
package ufmt
import (
"strconv"
"unicode/utf8"
)
// This file is the low level: padding, integers, floats, strings. It is a port
// of format.go in Go's fmt, kept close enough to read side by side.
const (
ldigits = "0123456789abcdefx"
udigits = "0123456789ABCDEFX"
)
// clearFlags resets everything a verb's specifier sets.
func (p *printer) clearFlags() {
p.plus, p.minus, p.sharp, p.space, p.zero = false, false, false, false, false
p.plusV, p.sharpV = false, false
p.wid, p.prec = 0, 0
p.widPresent, p.precPresent = false, false
}
// writePadding writes n pad bytes: zeros when the 0 flag is set, else spaces.
func (p *printer) writePadding(n int) {
if n <= 0 {
return
}
c := byte(' ')
if p.zero {
c = '0'
}
for i := 0; i < n; i++ {
p.buf = append(p.buf, c)
}
}
// pad writes b, padded to the width in runes, on the side the - flag says.
func (p *printer) pad(b []byte) {
if !p.widPresent || p.wid == 0 {
p.buf = append(p.buf, b...)
return
}
width := p.wid - utf8.RuneCount(b)
if !p.minus {
p.writePadding(width)
p.buf = append(p.buf, b...)
} else {
p.buf = append(p.buf, b...)
p.writePadding(width)
}
}
// padString is pad for a string.
func (p *printer) padString(s string) {
if !p.widPresent || p.wid == 0 {
p.buf = append(p.buf, s...)
return
}
width := p.wid - utf8.RuneCountInString(s)
if !p.minus {
p.writePadding(width)
p.buf = append(p.buf, s...)
} else {
p.buf = append(p.buf, s...)
p.writePadding(width)
}
}
// padNoZero pads with spaces whatever the 0 flag says.
func (p *printer) padNoZero(b []byte) {
oldZero := p.zero
p.zero = false
p.pad(b)
p.zero = oldZero
}
func (p *printer) fmtBoolean(v bool) {
if v {
p.padString("true")
} else {
p.padString("false")
}
}
// fmtInteger formats u, the magnitude, in base, with a '-' when negative.
func (p *printer) fmtInteger(u uint64, negative bool, base int, verb rune, digits string) {
// Fast path: no flags, width or precision, lowercase digits.
if !p.widPresent && !p.precPresent && !p.plus && !p.space && !p.sharp &&
verb != 'O' && (base != 16 || digits[10] == 'a') {
if negative {
p.buf = append(p.buf, '-')
}
p.buf = strconv.AppendUint(p.buf, u, base)
return
}
prec := 0
if p.precPresent {
prec = p.prec
// %.0d of zero prints nothing but its padding.
if prec == 0 && u == 0 {
oldZero := p.zero
p.zero = false
p.writePadding(p.wid)
p.zero = oldZero
return
}
} else if p.zero && !p.minus && p.widPresent {
// Zero padding is a precision in disguise, minus room for the sign.
prec = p.wid
if negative || p.plus || p.space {
prec--
}
}
size := 68 // 64 binary digits, a sign and a 0b/0x/0o prefix
if prec+4 > size {
size = prec + 4
}
buf := make([]byte, size)
i := size
switch base {
case 10:
for u >= 10 {
i--
next := u / 10
buf[i] = byte('0' + u - next*10)
u = next
}
case 16:
for u >= 16 {
i--
buf[i] = digits[u&0xF]
u >>= 4
}
case 8:
for u >= 8 {
i--
buf[i] = byte('0' + u&7)
u >>= 3
}
case 2:
for u >= 2 {
i--
buf[i] = byte('0' + u&1)
u >>= 1
}
}
i--
buf[i] = digits[u]
for i > 0 && prec > size-i {
i--
buf[i] = '0'
}
if p.sharp {
switch base {
case 2:
i--
buf[i] = 'b'
i--
buf[i] = '0'
case 8:
if buf[i] != '0' {
i--
buf[i] = '0'
}
case 16:
i--
buf[i] = digits[16]
i--
buf[i] = '0'
}
}
if verb == 'O' {
i--
buf[i] = 'o'
i--
buf[i] = '0'
}
if negative {
i--
buf[i] = '-'
} else if p.plus {
i--
buf[i] = '+'
} else if p.space {
i--
buf[i] = ' '
}
// The zeros, if any, are already in buf: pad the rest with spaces.
p.padNoZero(buf[i:])
}
// fmtUnicode formats u as "U+0078", or "U+0078 'x'" with the # flag.
func (p *printer) fmtUnicode(u uint64) {
prec := 4
if p.precPresent && p.prec > 4 {
prec = p.prec
}
hex := strconv.FormatUint(u, 16)
b := []byte("U+")
for n := len(hex); n < prec; n++ {
b = append(b, '0')
}
for i := 0; i < len(hex); i++ {
c := hex[i]
if c >= 'a' {
c -= 'a' - 'A'
}
b = append(b, c)
}
if p.sharp && u <= utf8.MaxRune && strconv.IsPrint(rune(u)) {
b = append(b, ' ', '\'')
b = utf8.AppendRune(b, rune(u))
b = append(b, '\'')
}
p.padNoZero(b)
}
// fmtC formats u as the rune it encodes, or U+FFFD when it encodes none.
func (p *printer) fmtC(u uint64) {
r := rune(utf8.RuneError)
if u <= utf8.MaxRune {
r = rune(u)
}
p.pad(utf8.AppendRune(nil, r))
}
// fmtQc formats u as a single-quoted rune literal.
func (p *printer) fmtQc(u uint64) {
r := rune(utf8.RuneError)
if u <= utf8.MaxRune {
r = rune(u)
}
if p.plus {
p.pad(strconv.AppendQuoteRuneToASCII(nil, r))
} else {
p.pad(strconv.AppendQuoteRune(nil, r))
}
}
// fmtFloat formats v, with prec digits (-1 for the shortest) unless the verb
// set its own precision.
func (p *printer) fmtFloat(v float64, size int, verb rune, prec int) {
if p.precPresent {
prec = p.prec
}
// num[0] is reserved for the sign.
num := strconv.AppendFloat([]byte{0}, v, byte(verb), prec, size)
if num[1] == '-' || num[1] == '+' {
num = num[1:]
} else {
num[0] = '+'
}
if p.space && num[0] == '+' && !p.plus {
num[0] = ' '
}
// Infinities and NaN do not look like numbers, so they are never zero padded.
if num[1] == 'I' || num[1] == 'N' {
oldZero := p.zero
p.zero = false
if num[1] == 'N' && !p.space && !p.plus {
num = num[1:]
}
p.pad(num)
p.zero = oldZero
return
}
// The # flag keeps the decimal point, and for %g the trailing zeros.
if p.sharp && verb != 'b' {
digits := 0
if verb == 'v' || verb == 'g' || verb == 'G' || verb == 'x' {
digits = prec
if digits == -1 {
digits = 6
}
}
var tail []byte
hasDecimalPoint := false
sawNonzeroDigit := false
for i := 1; i < len(num); i++ {
c := num[i]
if c == '.' {
hasDecimalPoint = true
continue
}
if c == 'p' || c == 'P' || ((c == 'e' || c == 'E') && verb != 'x' && verb != 'X') {
tail = append(tail, num[i:]...)
num = num[:i]
break
}
if c != '0' {
sawNonzeroDigit = true
}
if sawNonzeroDigit {
digits--
}
}
if !hasDecimalPoint {
// A lone leading zero counts as one significant digit.
if len(num) == 2 && num[1] == '0' {
digits--
}
num = append(num, '.')
}
for digits > 0 {
num = append(num, '0')
digits--
}
num = append(num, tail...)
}
if p.plus || num[0] != '+' {
// Zero padding goes after the sign.
if p.zero && !p.minus && p.widPresent && p.wid > len(num) {
p.buf = append(p.buf, num[0])
p.writePadding(p.wid - len(num))
p.buf = append(p.buf, num[1:]...)
return
}
p.pad(num)
return
}
p.pad(num[1:])
}
// truncate cuts s to the precision, counted in runes.
func (p *printer) truncate(s string) string {
if p.precPresent {
n := p.prec
for i := range s {
n--
if n < 0 {
return s[:i]
}
}
}
return s
}
func (p *printer) fmtS(s string) {
p.padString(p.truncate(s))
}
// fmtSx formats s as hex, two digits a byte. The space flag separates bytes,
// and # prefixes 0x, once or before each byte when spaced.
func (p *printer) fmtSx(s string, digits string) {
length := len(s)
if p.precPresent && p.prec < length {
length = p.prec
}
width := 2 * length
if width > 0 {
if p.space {
if p.sharp {
width *= 2
}
width += length - 1
} else if p.sharp {
width += 2
}
} else {
if p.widPresent {
p.writePadding(p.wid)
}
return
}
if p.widPresent && p.wid > width && !p.minus {
p.writePadding(p.wid - width)
}
if p.sharp {
p.buf = append(p.buf, '0', digits[16])
}
for i := 0; i < length; i++ {
if p.space && i > 0 {
p.buf = append(p.buf, ' ')
if p.sharp {
p.buf = append(p.buf, '0', digits[16])
}
}
c := s[i]
p.buf = append(p.buf, digits[c>>4], digits[c&0xF])
}
if p.widPresent && p.wid > width && p.minus {
p.writePadding(p.wid - width)
}
}
// fmtQ formats s as a double-quoted Go string, backquoted with the # flag when
// it can be, and ASCII only with the + flag.
func (p *printer) fmtQ(s string) {
s = p.truncate(s)
if p.sharp && strconv.CanBackquote(s) {
p.padString("`" + s + "`")
return
}
if p.plus {
p.pad(strconv.AppendQuoteToASCII(nil, s))
} else {
p.pad(strconv.AppendQuote(nil, s))
}
}
gnomod.toml
module = "gno.land/p/nym-moultest123/vendor/nt/ufmt/v2" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186405 max_deposit = "21000000ugnot"
gofmt_test.gno
package ufmt
import (
"math"
"testing"
)
// goCases were generated by running each row through Go's fmt.Sprintf
// (go1.27.1), so a row that fails here is a place v2 differs from Go.
var goCases = []struct {
format string
args []any
want string
}{
{"%d", []any{7}, "7"},
{"%03d", []any{7}, "007"},
{"%08X", []any{uint32(0xdead)}, "0000DEAD"},
{"0x%08X", []any{uint32(0x10074)}, "0x00010074"},
{"%08x", []any{uint32(0x00a00513)}, "00a00513"},
{"%x", []any{uint32(255)}, "ff"},
{"%X", []any{-255}, "-FF"},
{"%#x", []any{255}, "0xff"},
{"%#X", []any{255}, "0XFF"},
{"%#08x", []any{255}, "0x000000ff"},
{"%#o", []any{8}, "010"},
{"%O", []any{8}, "0o10"},
{"%b", []any{5}, "101"},
{"%#b", []any{5}, "0b101"},
{"%o", []any{-8}, "-10"},
{"%5d", []any{42}, " 42"},
{"%-5d|", []any{42}, "42 |"},
{"%+d", []any{42}, "+42"},
{"% d", []any{42}, " 42"},
{"%+05d", []any{42}, "+0042"},
{"%-05d|", []any{42}, "42 |"},
{"%.3d", []any{7}, "007"},
{"%8.3d", []any{-7}, " -007"},
{"%.0d", []any{0}, ""},
{"%5.0d|", []any{0}, " |"},
{"%d", []any{int64(-9223372036854775808)}, "-9223372036854775808"},
{"%x", []any{int64(-9223372036854775808)}, "-8000000000000000"},
{"%d", []any{uint64(18446744073709551615)}, "18446744073709551615"},
{"%x", []any{uint64(18446744073709551615)}, "ffffffffffffffff"},
{"%d", []any{int8(-128)}, "-128"},
{"%d", []any{uint8(200)}, "200"},
{"%x", []any{int16(-1)}, "-1"},
{"%d", []any{"hi"}, "%!d(string=hi)"},
{"%s", []any{42}, "%!s(int=42)"},
{"%c", []any{'x'}, "x"},
{"%c", []any{0x1F600}, "😀"},
{"%q", []any{'x'}, "'x'"},
{"%+q", []any{'é'}, "'\\u00e9'"},
{"%U", []any{0x1F600}, "U+1F600"},
{"%#U", []any{'x'}, "U+0078 'x'"},
{"%U", []any{1}, "U+0001"},
{"%.6U", []any{1}, "U+000001"},
{"%c", []any{-1}, "�"},
{"%s", []any{"hello"}, "hello"},
{"%10s|", []any{"hello"}, " hello|"},
{"%-10s|", []any{"hello"}, "hello |"},
{"%.2s", []any{"hello"}, "he"},
{"%.2s", []any{"héllo"}, "hé"},
{"%5.1s|", []any{"héllo"}, " h|"},
{"%05s", []any{"ab"}, "000ab"},
{"%q", []any{"hi\n"}, "\"hi\\n\""},
{"%+q", []any{"héllo"}, "\"h\\u00e9llo\""},
{"%#q", []any{"back`tick"}, "\"back`tick\""},
{"%#q", []any{"plain"}, "`plain`"},
{"%x", []any{"hello"}, "68656c6c6f"},
{"%X", []any{"hello"}, "68656C6C6F"},
{"% x", []any{"hello"}, "68 65 6c 6c 6f"},
{"%# x", []any{"hi"}, "0x68 0x69"},
{"%#x", []any{"hi"}, "0x6869"},
{"%10x|", []any{"hi"}, " 6869|"},
{"%-10x|", []any{"hi"}, "6869 |"},
{"%x", []any{""}, ""},
{"%5x|", []any{""}, " |"},
{"%.1x", []any{"hi"}, "68"},
{"%s", []any{[]byte("bytes")}, "bytes"},
{"%x", []any{[]byte{1, 171}}, "01ab"},
{"%X", []any{[]byte{1, 171}}, "01AB"},
{"%v", []any{[]byte{1, 2}}, "[1 2]"},
{"%d", []any{[]byte{1, 2}}, "[1 2]"},
{"%#v", []any{[]byte{1, 2}}, "[]byte{0x1, 0x2}"},
{"%q", []any{[]byte("q")}, "\"q\""},
{"%b", []any{[]byte{3}}, "[11]"},
{"%t", []any{true}, "true"},
{"%v", []any{false}, "false"},
{"%5t|", []any{true}, " true|"},
{"%d", []any{true}, "%!d(bool=true)"},
{"%f", []any{3.14159}, "3.141590"},
{"%.2f", []any{3.14159}, "3.14"},
{"%8.3f|", []any{3.14159}, " 3.142|"},
{"%-8.3f|", []any{3.14159}, "3.142 |"},
{"%08.3f", []any{-3.14159}, "-003.142"},
{"%+.1f", []any{2.0}, "+2.0"},
{"% .1f", []any{2.0}, " 2.0"},
{"%e", []any{1234.5678}, "1.234568e+03"},
{"%E", []any{1234.5678}, "1.234568E+03"},
{"%.2e", []any{1234.5678}, "1.23e+03"},
{"%g", []any{1234.5678}, "1234.5678"},
{"%g", []any{1e21}, "1e+21"},
{"%g", []any{0.00001}, "1e-05"},
{"%G", []any{1e-10}, "1E-10"},
{"%v", []any{3.14}, "3.14"},
{"%v", []any{1e6}, "1e+06"},
{"%v", []any{100000.0}, "100000"},
{"%v", []any{float32(0.1)}, "0.1"},
{"%F", []any{1.5}, "1.500000"},
{"%#g", []any{1.0}, "1.00000"},
{"%#.3g", []any{1.0}, "1.00"},
{"%#f", []any{1.0}, "1.000000"},
{"%#.0f", []any{1.0}, "1."},
{"%#.0e", []any{1.0}, "1.e+00"},
{"%x", []any{1.0}, "0x1p+00"},
{"%X", []any{1.0}, "0X1P+00"},
{"%b", []any{1.0}, "4503599627370496p-52"},
{"%.3x", []any{3.14159}, "0x1.922p+01"},
{"%f", []any{math.Inf(1)}, "+Inf"},
{"%+f", []any{math.Inf(1)}, "+Inf"},
{"%08f", []any{math.Inf(-1)}, " -Inf"},
{"%f", []any{math.NaN()}, "NaN"},
{"%+f", []any{math.NaN()}, "+NaN"},
{"%010.2f", []any{12.5}, "0000012.50"},
{"%s", []any{1.5}, "%!s(float64=1.5)"},
{"%v", []any{nil}, "<nil>"},
{"%d", []any{nil}, "%!d(<nil>)"},
{"%s", []any{nil}, "%!s(<nil>)"},
{"%T", []any{nil}, "<nil>"},
{"%T", []any{42}, "int"},
{"%T", []any{"s"}, "string"},
{"%T", []any{[]byte("x")}, "[]uint8"},
{"%T", []any{3.0}, "float64"},
{"%T", []any{int8(1)}, "int8"},
{"%T", []any{[]string{"a"}}, "[]string"},
{"%T", []any{map[string]int{}}, "map[string]int"},
{"%5T|", []any{1}, " int|"},
{"%v", []any{[]string{"a", "b"}}, "[a b]"},
{"%q", []any{[]string{"a", "b"}}, "[\"a\" \"b\"]"},
{"%#v", []any{[]string{"a", "b"}}, "[]string{\"a\", \"b\"}"},
{"%#v", []any{[]string(nil)}, "[]string(nil)"},
{"%v", []any{[]int{1, 2, 3}}, "[1 2 3]"},
{"%3d", []any{[]int{1, 2}}, "[ 1 2]"},
{"%x", []any{[]int{10, 255}}, "[a ff]"},
{"%d", []any{[]string{"a"}}, "[%!d(string=a)]"},
{"%v", []any{[]any{1, "a", nil, true}}, "[1 a <nil> true]"},
{"%#v", []any{[]any{1, "a", nil}}, "[]interface {}{1, \"a\", interface {}(nil)}"},
{"%v", []any{[]float64{1.5, 2}}, "[1.5 2]"},
{"%v", []any{map[string]int{"b": 2, "a": 1, "c": 3}}, "map[a:1 b:2 c:3]"},
{"%#v", []any{map[string]int{"b": 2, "a": 1}}, "map[string]int{\"a\":1, \"b\":2}"},
{"%v", []any{map[string]string{"k": "v"}}, "map[k:v]"},
{"%v", []any{map[string]any{"x": nil, "y": 1}}, "map[x:<nil> y:1]"},
{"%v", []any{map[string]bool{}}, "map[]"},
{"%#v", []any{"str"}, "\"str\""},
{"%#v", []any{42}, "42"},
{"%#v", []any{uint(42)}, "0x2a"},
{"%#v", []any{3.0}, "3"},
{"%#v", []any{true}, "true"},
{"%#v", []any{nil}, "<nil>"},
{"%+v", []any{42}, "42"},
{"%+v", []any{"x"}, "x"},
{"%%", []any{}, "%"},
{"100%%", []any{}, "100%"},
{"%5%", []any{}, "%"},
{"%", []any{}, "%!(NOVERB)"},
{"abc%", []any{}, "abc%!(NOVERB)"},
{"%!", []any{}, "%!!(MISSING)"},
{"%z", []any{1}, "%!z(int=1)"},
{"%d", []any{}, "%!d(MISSING)"},
{"%d %d", []any{1}, "1 %!d(MISSING)"},
{"%d", []any{1, 2}, "1%!(EXTRA int=2)"},
{"%s", []any{"a", 3, nil}, "a%!(EXTRA int=3, <nil>)"},
{"%[2]d %[1]d", []any{1, 2}, "2 1"},
{"%[1]d %[1]x", []any{255}, "255 ff"},
{"%[3]d", []any{1, 2}, "%!d(BADINDEX)"},
{"%[0]d", []any{1}, "%!d(BADINDEX)"},
{"%[x]d", []any{1}, "%!d(BADINDEX)"},
{"%[1]*d|", []any{5, 42}, " 42|"},
{"%[2]*[1]d|", []any{42, 6}, " 42|"},
{"%*d|", []any{5, 42}, " 42|"},
{"%-*d|", []any{5, 42}, "42 |"},
{"%*d|", []any{-5, 42}, "42 |"},
{"%.*f", []any{2, 3.14159}, "3.14"},
{"%.*f", []any{-1, 3.14159}, "%!(BADPREC)3.141590"},
{"%*d", []any{"x", 1}, "%!(BADWIDTH)1"},
{"%.*d", []any{"x", 1}, "%!(BADPREC)1"},
{"%*.*f|", []any{8, 2, 3.14159}, " 3.14|"},
{"%d %s", []any{1}, "1 %!s(MISSING)"},
{"%[2]d", []any{1}, "%!d(BADINDEX)"},
{"%5.2v|", []any{3.14159}, " 3.1|"},
{"%v %v", []any{"a", "b"}, "a b"},
{"%-+5d|", []any{3}, "+3 |"},
{"%+-5d|", []any{3}, "+3 |"},
{"%0-5d|", []any{3}, "3 |"},
{"%x", []any{-1}, "-1"},
{"%#v", []any{[]byte(nil)}, "[]byte(nil)"},
{"%v", []any{[]byte{}}, "[]"},
{"%v", []any{[]string{}}, "[]"},
{"%d", []any{[]any{1, "x"}}, "[1 %!d(string=x)]"},
{"%v", []any{int32(-5)}, "-5"},
{"%c", []any{65}, "A"},
{"%x", []any{"\xff\x00"}, "ff00"},
{"%s", []any{"日本語"}, "日本語"},
{"%6s|", []any{"日本語"}, " 日本語|"},
{"%-6s|", []any{"日本語"}, "日本語 |"},
{"%q", []any{"日本語"}, "\"日本語\""},
{"%+q", []any{"日本語"}, "\"\\u65e5\\u672c\\u8a9e\""},
{"%x", []any{"日本"}, "e697a5e69cac"},
{"%v", []any{"\x00"}, "\x00"},
{"%q", []any{'\n'}, "'\\n'"},
{"%q", []any{0x110000}, "'�'"},
{"%U", []any{-1}, "U+FFFFFFFFFFFFFFFF"},
{"%10.4f|", []any{1234.56789}, " 1234.5679|"},
{"%-10.1e|", []any{1234.56789}, "1.2e+03 |"},
{"%+e", []any{0.0}, "+0.000000e+00"},
{"%g", []any{-0.0}, "0"},
{"%.3g", []any{123456.0}, "1.23e+05"},
{"%.10g", []any{1.0 / 3}, "0.3333333333"},
{"%e", []any{float32(1.0) / 3}, "3.333333e-01"},
{"%v", []any{float32(16777216.0)}, "1.6777216e+07"},
{"%v", []any{1e100}, "1e+100"},
{"%v", []any{123456789.0}, "1.23456789e+08"},
{"%v", []any{0.000001}, "1e-06"},
{"%v", []any{0.0000001}, "1e-07"},
}
func TestSprintfMatchesGo(t *testing.T) {
for _, c := range goCases {
if got := Sprintf(c.format, c.args...); got != c.want {
t.Errorf("Sprintf(%q, %v) = %q, want %q", c.format, c.args, got, c.want)
}
}
}
methods_test.gno
package ufmt
import (
"errors"
"strings"
"testing"
)
type str struct{ s string }
func (v str) String() string { return v.s }
type errT struct{}
func (errT) Error() string { return "boom" }
func (errT) String() string { return "stringer" }
type goStr struct{}
func (goStr) GoString() string { return "goStr{}" }
func (goStr) String() string { return "plain" }
type formatter struct{}
func (formatter) Format(f State, verb rune) {
w, wok := f.Width()
p, pok := f.Precision()
Fprintf(f, "F[%c w=%d/%t p=%d/%t minus=%t plus=%t sharp=%t]",
verb, w, wok, p, pok, f.Flag('-'), f.Flag('+'), f.Flag('#'))
}
type panicky struct{}
func (panicky) String() string { panic("nope") }
type opaque struct{ n int }
// Every want below is what Go's fmt prints for the same call (go1.27.1),
// except where a comment says gno cannot see what Go sees.
func TestMethods(t *testing.T) {
cases := []struct{ got, want string }{
{Sprintf("%v|%s|%q|%x|%10s|%-6v|", str{"hi"}, str{"hi"}, str{"hi"}, str{"hi"}, str{"hi"}, str{"hi"}),
`hi|hi|"hi"|6869| hi|hi |`},
{Sprintf("%v %s", errT{}, errT{}), "boom boom"}, // Error wins over String
{Sprintf("%#v %v", goStr{}, goStr{}), "goStr{} plain"},
{Sprintf("%v|%-8.3s|%+#x", formatter{}, formatter{}, formatter{}),
"F[v w=0/false p=0/false minus=false plus=false sharp=false]|" +
"F[s w=8/true p=3/true minus=true plus=false sharp=false]|" +
"F[x w=0/false p=0/false minus=false plus=true sharp=true]"},
{Sprintf("%v", panicky{}), "%!v(PANIC=String method: nope)"},
{Sprintf("%v", []any{str{"a"}, errT{}}), "[a boom]"},
{Sprintf("%s", []error{errors.New("base"), errT{}}), "[base boom]"},
{Sprint("a", 1, 2, "b", "c", 3.5, true, nil), "a1 2bc3.5 true <nil>"},
{Sprint(str{"x"}, str{"y"}), "x y"},
{Sprintln("a", 1, 2, "b"), "a 1 2 b\n"},
// Go reflects into the struct and prints "{%!d(string=hi)}" and
// "{7}"; gno has no reflect, so v2 says so instead of guessing.
{Sprintf("%d", str{"hi"}), "%!d(unhandled)"},
{Sprintf("%v", opaque{7}), "(unhandled)"},
{Sprintf("%T", opaque{7}), "unknown"},
// Go prints "%!w(*errors.errorString=&{base})": the type is not
// nameable here either.
{Sprintf("%w", errors.New("base")), "%!w(unhandled)"},
}
for i, c := range cases {
if c.got != c.want {
t.Errorf("case %d: got %q, want %q", i, c.got, c.want)
}
}
}
func TestErrorf(t *testing.T) {
base := errors.New("base")
e := Errorf("wrap: %w", base)
if e.Error() != "wrap: base" || !errors.Is(e, base) || errors.Unwrap(e) != base {
t.Errorf("single %%w: %q, Is=%t", e.Error(), errors.Is(e, base))
}
e2 := Errorf("two: %w and %w", base, errT{})
if e2.Error() != "two: base and boom" || !errors.Is(e2, base) || errors.Unwrap(e2) != nil {
t.Errorf("two %%w: %q, Is=%t", e2.Error(), errors.Is(e2, base))
}
if got := Errorf("%w", "notanerror").Error(); got != "%!w(string=notanerror)" {
t.Errorf("non-error %%w: %q", got)
}
plain := Errorf("plain %d", 1)
if plain.Error() != "plain 1" || errors.Unwrap(plain) != nil {
t.Errorf("plain: %q", plain.Error())
}
}
func TestWriters(t *testing.T) {
var sb strings.Builder
n, err := Fprintf(&sb, "%04d|", 7)
Fprint(&sb, "a", 1)
Fprintln(&sb, "!", 2)
if sb.String() != "0007|a1! 2\n" || n != 5 || err != nil {
t.Errorf("Fprint*: %q n=%d err=%v", sb.String(), n, err)
}
b := Appendf([]byte("x="), "%x", 255)
b = Append(b, " ", true)
b = Appendln(b, "", 1)
if string(b) != "x=ff true 1\n" {
t.Errorf("Append*: %q", string(b))
}
}
// The register dump that v0 could not print: "0x(unhandled verb: %X)".
func TestRegisterDump(t *testing.T) {
got := Sprintf("0x%08X %08x", uint32(0x1004), uint32(0xa00513))
if got != "0x00001004 00a00513" {
t.Errorf("got %q", got)
}
}
print.gno
package ufmt
import (
"sort"
"unicode/utf8"
)
// This file is the high level: parsing the format, and choosing how each
// operand prints. It is a port of print.go in Go's fmt, minus reflect.
const (
commaSpace = ", "
nilAngle = "<nil>"
nilParen = "(nil)"
unhandled = "(unhandled)"
percentBang = "%!"
missing = "(MISSING)"
badIndex = "(BADINDEX)"
extra = "%!(EXTRA "
badWidth = "%!(BADWIDTH)"
badPrec = "%!(BADPREC)"
noVerb = "%!(NOVERB)"
)
// printer holds the output and the state of the verb being printed.
type printer struct {
buf []byte
// The flags, width and precision of the current verb.
plus, minus, sharp, space, zero bool
plusV, sharpV bool // %+v and %#v
wid, prec int
widPresent, precPresent bool
arg any // the operand being printed, for error messages
erroring bool // printing an error message: do not call methods
reordered bool // an explicit index was used
goodArgNum bool // the last index was valid
wrapErrs bool // Errorf: %w is allowed
wrapped []int
}
func newPrinter() *printer {
return &printer{}
}
// Write implements State, so a Formatter can write.
func (p *printer) Write(b []byte) (int, error) {
p.buf = append(p.buf, b...)
return len(b), nil
}
// WriteString lets a Formatter write a string without a conversion.
func (p *printer) WriteString(s string) (int, error) {
p.buf = append(p.buf, s...)
return len(s), nil
}
// Width implements State.
func (p *printer) Width() (int, bool) { return p.wid, p.widPresent }
// Precision implements State.
func (p *printer) Precision() (int, bool) { return p.prec, p.precPresent }
// Flag implements State.
func (p *printer) Flag(c int) bool {
switch c {
case '-':
return p.minus
case '+':
return p.plus || p.plusV
case '#':
return p.sharp || p.sharpV
case ' ':
return p.space
case '0':
return p.zero
}
return false
}
func (p *printer) writeString(s string) { p.buf = append(p.buf, s...) }
func (p *printer) writeByte(c byte) { p.buf = append(p.buf, c) }
func (p *printer) writeRune(r rune) { p.buf = utf8.AppendRune(p.buf, r) }
// doPrint is Sprint: %v, with a space between two operands neither of which is
// a string.
func (p *printer) doPrint(a []any) {
prevString := false
for argNum, arg := range a {
_, isString := arg.(string)
if argNum > 0 && !isString && !prevString {
p.writeByte(' ')
}
p.printArg(arg, 'v')
prevString = isString
}
}
// doPrintln is Sprintln: %v, always a space between operands, then a newline.
func (p *printer) doPrintln(a []any) {
for argNum, arg := range a {
if argNum > 0 {
p.writeByte(' ')
}
p.printArg(arg, 'v')
}
p.writeByte('\n')
}
// parsenum reads a decimal number at s[start:end].
func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
if start >= end {
return 0, false, end
}
for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
if num > 1e6 {
return 0, false, end // absurdly large: refuse rather than allocate
}
num = num*10 + int(s[newi]-'0')
isnum = true
}
return
}
// intFromArg reads a * width or precision from a[argNum].
func intFromArg(a []any, argNum int) (num int, isInt bool, newArgNum int) {
newArgNum = argNum
if argNum >= len(a) {
return
}
isInt = true
switch v := a[argNum].(type) {
case int:
num = v
case int8:
num = int(v)
case int16:
num = int(v)
case int32:
num = int(v)
case int64:
num = int(v)
case uint:
num = int(v)
case uint8:
num = int(v)
case uint16:
num = int(v)
case uint32:
num = int(v)
case uint64:
num = int(v)
default:
isInt = false
}
newArgNum = argNum + 1
if num > 1e6 || num < -1e6 {
num = 0
isInt = false
}
return
}
// argNumber reads an explicit index, "[3]", at format[i:].
func (p *printer) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) {
if len(format) <= i || format[i] != '[' {
return argNum, i, false
}
p.reordered = true
for j := 1; j < len(format)-i; j++ {
if format[i+j] == ']' {
width, ok, newi := parsenum(format, i+1, i+j)
if !ok || newi != i+j {
p.goodArgNum = false
return argNum, i + j + 1, true
}
index := width - 1
if index >= 0 && index < numArgs {
return index, i + j + 1, true
}
p.goodArgNum = false
return argNum, i + j + 1, true
}
}
p.goodArgNum = false
return argNum, i + 1, false
}
// doPrintf is Sprintf.
func (p *printer) doPrintf(format string, a []any) {
end := len(format)
argNum := 0
afterIndex := false // the previous item was an index like [3]
p.reordered = false
for i := 0; i < end; {
p.goodArgNum = true
lasti := i
for i < end && format[i] != '%' {
i++
}
if i > lasti {
p.writeString(format[lasti:i])
}
if i >= end {
break
}
i++ // skip '%'
p.clearFlags()
// Fast path: a bare lowercase verb, "%d" or "%s", is most of what any
// realm prints, and skips the specifier parsing entirely.
if i < end && 'a' <= format[i] && format[i] <= 'z' && argNum < len(a) {
verb := rune(format[i])
if verb == 'w' {
p.wrapped = append(p.wrapped, argNum)
}
p.printArg(a[argNum], verb)
argNum++
i++
continue
}
flags:
for ; i < end; i++ {
switch format[i] {
case '#':
p.sharp = true
case '0':
p.zero = !p.minus // zero padding only ever goes on the left
case '+':
p.plus = true
case '-':
p.minus = true
p.zero = false
case ' ':
p.space = true
default:
break flags
}
}
argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
// Width.
if i < end && format[i] == '*' {
i++
p.wid, p.widPresent, argNum = intFromArg(a, argNum)
if !p.widPresent {
p.writeString(badWidth)
}
if p.wid < 0 {
p.wid = -p.wid
p.minus = true
p.zero = false
}
afterIndex = false
} else {
p.wid, p.widPresent, i = parsenum(format, i, end)
if afterIndex && p.widPresent { // "%[3]2d"
p.goodArgNum = false
}
}
// Precision.
if i+1 < end && format[i] == '.' {
i++
if afterIndex { // "%[3].2d"
p.goodArgNum = false
}
argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
if i < end && format[i] == '*' {
i++
p.prec, p.precPresent, argNum = intFromArg(a, argNum)
if p.prec < 0 {
p.prec = 0
p.precPresent = false
}
if !p.precPresent {
p.writeString(badPrec)
}
afterIndex = false
} else {
p.prec, p.precPresent, i = parsenum(format, i, end)
if !p.precPresent {
p.prec = 0
p.precPresent = true
}
}
}
if !afterIndex {
argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
}
if i >= end {
p.writeString(noVerb)
break
}
verb, size := rune(format[i]), 1
if verb >= utf8.RuneSelf {
verb, size = utf8.DecodeRuneInString(format[i:])
}
i += size
switch {
case verb == '%': // takes no operand, ignores width and precision
p.writeByte('%')
case !p.goodArgNum:
p.badArgNum(verb)
case argNum >= len(a):
p.missingArg(verb)
default:
if verb == 'w' {
p.wrapped = append(p.wrapped, argNum)
}
if verb == 'v' || verb == 'w' {
p.sharpV, p.sharp = p.sharp, false
p.plusV, p.plus = p.plus, false
}
p.printArg(a[argNum], verb)
argNum++
}
}
// Report unused operands, unless an index made the count meaningless.
if !p.reordered && argNum < len(a) {
p.clearFlags()
p.writeString(extra)
for i, arg := range a[argNum:] {
if i > 0 {
p.writeString(commaSpace)
}
if arg == nil {
p.writeString(nilAngle)
continue
}
p.writeString(typeName(arg))
p.writeByte('=')
p.printArg(arg, 'v')
}
p.writeByte(')')
}
}
func (p *printer) badArgNum(verb rune) {
p.writeString(percentBang)
p.writeRune(verb)
p.writeString(badIndex)
}
func (p *printer) missingArg(verb rune) {
p.writeString(percentBang)
p.writeRune(verb)
p.writeString(missing)
}
// badVerb writes "%!d(string=hi)": the verb, the operand's type and its value.
func (p *printer) badVerb(verb rune) {
p.erroring = true
p.writeString(percentBang)
p.writeRune(verb)
p.writeByte('(')
switch {
case p.arg == nil:
p.writeString(nilAngle)
default:
if t := typeName(p.arg); t != "unknown" {
p.writeString(t)
p.writeByte('=')
p.printArg(p.arg, 'v')
} else {
p.writeString("unhandled")
}
}
p.writeByte(')')
p.erroring = false
}
// printArg prints one operand.
func (p *printer) printArg(arg any, verb rune) {
p.arg = arg
if arg == nil {
switch verb {
case 'T', 'v':
p.padString(nilAngle)
default:
p.badVerb(verb)
}
return
}
switch verb {
case 'T':
p.fmtS(typeName(arg))
return
case 'p':
p.badVerb(verb)
return
}
// The basic types first, exactly as Go: a named type never matches these,
// so its methods are still found below.
switch f := arg.(type) {
case bool:
p.fmtBool(f, verb)
case float32:
p.fmtFloatVerb(float64(f), 32, verb)
case float64:
p.fmtFloatVerb(f, 64, verb)
case int:
p.fmtSigned(int64(f), verb)
case int8:
p.fmtSigned(int64(f), verb)
case int16:
p.fmtSigned(int64(f), verb)
case int32:
p.fmtSigned(int64(f), verb)
case int64:
p.fmtSigned(f, verb)
case uint:
p.fmtUnsigned(uint64(f), verb)
case uint8:
p.fmtUnsigned(uint64(f), verb)
case uint16:
p.fmtUnsigned(uint64(f), verb)
case uint32:
p.fmtUnsigned(uint64(f), verb)
case uint64:
p.fmtUnsigned(f, verb)
case string:
p.fmtString(f, verb)
case []byte:
p.fmtBytes(f, verb)
default:
if !p.handleMethods(verb) {
p.printComposite(arg, verb)
}
}
}
// handleMethods prints arg with its own Format, GoString, Error or String
// method, in Go's order, and reports whether it did.
func (p *printer) handleMethods(verb rune) (handled bool) {
if p.erroring {
return false
}
if verb == 'w' {
// %w is for Errorf, and for an error.
if _, ok := p.arg.(error); !ok || !p.wrapErrs {
p.badVerb(verb)
return true
}
verb = 'v'
}
if f, ok := p.arg.(Formatter); ok {
handled = true // stays true if the method panics
defer p.catchPanic(p.arg, verb, "Format")
f.Format(p, verb)
return
}
if p.sharpV {
if g, ok := p.arg.(GoStringer); ok {
handled = true
defer p.catchPanic(p.arg, verb, "GoString")
p.fmtS(g.GoString())
return
}
return false
}
switch verb {
case 'v', 's', 'x', 'X', 'q':
switch v := p.arg.(type) {
case error:
handled = true
defer p.catchPanic(p.arg, verb, "Error")
p.fmtString(v.Error(), verb)
return
case Stringer:
handled = true
defer p.catchPanic(p.arg, verb, "String")
p.fmtString(v.String(), verb)
return
}
}
return false
}
// catchPanic turns a panicking method into "%!v(PANIC=String method: msg)".
func (p *printer) catchPanic(arg any, verb rune, method string) {
r := recover()
if r == nil {
return
}
if p.erroring {
panic(r) // the method panicked again while printing its own panic
}
p.clearFlags()
p.writeString(percentBang)
p.writeRune(verb)
p.writeString("(PANIC=")
p.writeString(method)
p.writeString(" method: ")
p.erroring = true
p.printArg(r, 'v')
p.erroring = false
p.writeByte(')')
}
func (p *printer) fmtBool(v bool, verb rune) {
switch verb {
case 't', 'v':
p.fmtBoolean(v)
default:
p.badVerb(verb)
}
}
// fmtSigned prints a signed integer. The magnitude of math.MinInt64 does not
// fit an int64, so it is computed without ever negating v itself.
func (p *printer) fmtSigned(v int64, verb rune) {
if v >= 0 {
p.fmtIntegerVerb(uint64(v), false, true, verb)
return
}
mag := uint64(-(v + 1)) + 1
p.fmtIntegerVerb(mag, true, true, verb)
}
func (p *printer) fmtUnsigned(u uint64, verb rune) {
p.fmtIntegerVerb(u, false, false, verb)
}
func (p *printer) fmtIntegerVerb(u uint64, negative, isSigned bool, verb rune) {
switch verb {
case 'v':
if p.sharpV && !isSigned {
p.fmt0x64(u, true)
} else {
p.fmtInteger(u, negative, 10, verb, ldigits)
}
case 'd':
p.fmtInteger(u, negative, 10, verb, ldigits)
case 'b':
p.fmtInteger(u, negative, 2, verb, ldigits)
case 'o', 'O':
p.fmtInteger(u, negative, 8, verb, ldigits)
case 'x':
p.fmtInteger(u, negative, 16, verb, ldigits)
case 'X':
p.fmtInteger(u, negative, 16, verb, udigits)
case 'c', 'q', 'U':
if negative {
u = ^u + 1 // back to two's complement, as Go sees it: never a rune
}
switch verb {
case 'c':
p.fmtC(u)
case 'q':
p.fmtQc(u)
default:
p.fmtUnicode(u)
}
default:
p.badVerb(verb)
}
}
// fmt0x64 prints u in hex with a 0x prefix (leading0x) or without one.
func (p *printer) fmt0x64(u uint64, leading0x bool) {
sharp := p.sharp
p.sharp = leading0x
p.fmtInteger(u, false, 16, 'v', ldigits)
p.sharp = sharp
}
func (p *printer) fmtFloatVerb(v float64, size int, verb rune) {
switch verb {
case 'v':
p.fmtFloat(v, size, 'g', -1)
case 'b', 'g', 'G', 'x', 'X':
p.fmtFloat(v, size, verb, -1)
case 'f', 'e', 'E':
p.fmtFloat(v, size, verb, 6)
case 'F':
p.fmtFloat(v, size, 'f', 6)
default:
p.badVerb(verb)
}
}
func (p *printer) fmtString(v string, verb rune) {
switch verb {
case 'v':
if p.sharpV {
p.fmtQ(v)
} else {
p.fmtS(v)
}
case 's':
p.fmtS(v)
case 'x':
p.fmtSx(v, ldigits)
case 'X':
p.fmtSx(v, udigits)
case 'q':
p.fmtQ(v)
default:
p.badVerb(verb)
}
}
func (p *printer) fmtBytes(v []byte, verb rune) {
switch verb {
case 'v', 'd':
if p.sharpV {
p.writeString("[]byte")
if v == nil {
p.writeString(nilParen)
return
}
p.writeByte('{')
for i, c := range v {
if i > 0 {
p.writeString(commaSpace)
}
p.fmt0x64(uint64(c), true)
}
p.writeByte('}')
return
}
p.writeByte('[')
for i, c := range v {
if i > 0 {
p.writeByte(' ')
}
p.fmtInteger(uint64(c), false, 10, verb, ldigits)
}
p.writeByte(']')
case 's':
p.fmtS(string(v))
case 'x':
p.fmtSx(string(v), ldigits)
case 'X':
p.fmtSx(string(v), udigits)
case 'q':
p.fmtQ(string(v))
default:
// Every other verb applies to each byte, as for any slice.
p.writeByte('[')
for i, c := range v {
if i > 0 {
p.writeByte(' ')
}
p.fmtUnsigned(uint64(c), verb)
}
p.writeByte(']')
}
}
// printComposite prints the slices and maps gno can see without reflect.
func (p *printer) printComposite(arg any, verb rune) {
switch v := arg.(type) {
case []any:
p.printSlice("[]interface {}", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []string:
p.printSlice("[]string", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []error:
p.printSlice("[]error", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []bool:
p.printSlice("[]bool", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []int:
p.printSlice("[]int", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []int8:
p.printSlice("[]int8", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []int16:
p.printSlice("[]int16", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []int32:
p.printSlice("[]int32", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []int64:
p.printSlice("[]int64", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []uint:
p.printSlice("[]uint", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []uint16:
p.printSlice("[]uint16", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []uint32:
p.printSlice("[]uint32", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []uint64:
p.printSlice("[]uint64", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []float32:
p.printSlice("[]float32", v == nil, len(v), func(i int) any { return v[i] }, verb)
case []float64:
p.printSlice("[]float64", v == nil, len(v), func(i int) any { return v[i] }, verb)
case map[string]string:
keys := sortedKeys(len(v), func(add func(string)) {
for k := range v {
add(k)
}
})
p.printMap("map[string]string", v == nil, keys, func(k string) any { return v[k] }, verb)
case map[string]any:
keys := sortedKeys(len(v), func(add func(string)) {
for k := range v {
add(k)
}
})
p.printMap("map[string]interface {}", v == nil, keys, func(k string) any { return v[k] }, verb)
case map[string]int:
keys := sortedKeys(len(v), func(add func(string)) {
for k := range v {
add(k)
}
})
p.printMap("map[string]int", v == nil, keys, func(k string) any { return v[k] }, verb)
case map[string]bool:
keys := sortedKeys(len(v), func(add func(string)) {
for k := range v {
add(k)
}
})
p.printMap("map[string]bool", v == nil, keys, func(k string) any { return v[k] }, verb)
default:
if verb == 'v' {
p.padString(unhandled)
} else {
p.badVerb(verb)
}
}
}
// printSlice prints "[a b]", or "[]T{a, b}" for %#v, each element with verb.
func (p *printer) printSlice(typ string, isNil bool, n int, at func(int) any, verb rune) {
if p.sharpV {
p.writeString(typ)
if isNil {
p.writeString(nilParen)
return
}
p.writeByte('{')
for i := 0; i < n; i++ {
if i > 0 {
p.writeString(commaSpace)
}
p.printElem(at(i), verb)
}
p.writeByte('}')
return
}
p.writeByte('[')
for i := 0; i < n; i++ {
if i > 0 {
p.writeByte(' ')
}
p.printElem(at(i), verb)
}
p.writeByte(']')
}
// printMap prints "map[a:1 b:2]", or "map[string]int{"a":1, "b":2}" for %#v,
// keys sorted as Go sorts them.
func (p *printer) printMap(typ string, isNil bool, keys []string, at func(string) any, verb rune) {
if p.sharpV {
p.writeString(typ)
if isNil {
p.writeString(nilParen)
return
}
p.writeByte('{')
} else {
p.writeString("map[")
}
for i, k := range keys {
if i > 0 {
if p.sharpV {
p.writeString(commaSpace)
} else {
p.writeByte(' ')
}
}
p.printElem(k, verb)
p.writeByte(':')
p.printElem(at(k), verb)
}
if p.sharpV {
p.writeByte('}')
} else {
p.writeByte(']')
}
}
// printElem prints one element of a composite, keeping the outer operand for
// error messages. A nil element prints "<nil>" whatever the verb, as in Go.
func (p *printer) printElem(v any, verb rune) {
outer := p.arg
if v == nil {
if p.sharpV {
p.writeString("interface {}(nil)")
} else {
p.padString(nilAngle)
}
} else {
p.printArg(v, verb)
}
p.arg = outer
}
func sortedKeys(n int, each func(add func(string))) []string {
keys := make([]string, 0, n)
each(func(k string) { keys = append(keys, k) })
sort.Strings(keys)
return keys
}
// typeName is %T for the types gno can name without reflect.
func typeName(v any) string {
switch v.(type) {
case bool:
return "bool"
case int:
return "int"
case int8:
return "int8"
case int16:
return "int16"
case int32:
return "int32"
case int64:
return "int64"
case uint:
return "uint"
case uint8:
return "uint8"
case uint16:
return "uint16"
case uint32:
return "uint32"
case uint64:
return "uint64"
case float32:
return "float32"
case float64:
return "float64"
case string:
return "string"
case []byte:
return "[]uint8"
case []any:
return "[]interface {}"
case []string:
return "[]string"
case []error:
return "[]error"
case []bool:
return "[]bool"
case []int:
return "[]int"
case []int8:
return "[]int8"
case []int16:
return "[]int16"
case []int32:
return "[]int32"
case []int64:
return "[]int64"
case []uint:
return "[]uint"
case []uint16:
return "[]uint16"
case []uint32:
return "[]uint32"
case []uint64:
return "[]uint64"
case []float32:
return "[]float32"
case []float64:
return "[]float64"
case map[string]string:
return "map[string]string"
case map[string]any:
return "map[string]interface {}"
case map[string]int:
return "map[string]int"
case map[string]bool:
return "map[string]bool"
}
return "unknown"
}
ufmt.gno
package ufmt
import (
"io"
"strings"
)
// State is what a Formatter's Format method is handed: the flags, width and
// precision of the verb being printed, and somewhere to write.
type State interface {
// Write emits formatted output.
Write(b []byte) (n int, err error)
// Width returns the width and whether one was set.
Width() (wid int, ok bool)
// Precision returns the precision and whether one was set.
Precision() (prec int, ok bool)
// Flag reports whether the flag c, a character, was set.
Flag(c int) bool
}
// Formatter is implemented by a value that formats itself. Format is called
// for every verb, and its output replaces what ufmt would have printed.
type Formatter interface {
Format(f State, verb rune)
}
// Stringer is implemented by a value that has a natural string form. It is
// used for %v, %s, %q, %x and %X, and by Print.
type Stringer interface {
String() string
}
// GoStringer is implemented by a value that has a Go-syntax form, used for %#v.
type GoStringer interface {
GoString() string
}
// Sprintf formats according to a format specifier and returns the string.
func Sprintf(format string, a ...any) string {
p := newPrinter()
p.doPrintf(format, a)
return string(p.buf)
}
// Appendf formats according to a format specifier and appends the result to b.
func Appendf(b []byte, format string, a ...any) []byte {
p := newPrinter()
p.doPrintf(format, a)
return append(b, p.buf...)
}
// Fprintf formats according to a format specifier and writes to w.
func Fprintf(w io.Writer, format string, a ...any) (n int, err error) {
p := newPrinter()
p.doPrintf(format, a)
return w.Write(p.buf)
}
// Printf formats according to a format specifier and prints the result with
// the print builtin, which is what a test or a filetest captures.
func Printf(format string, a ...any) (n int, err error) {
return printOut(Sprintf(format, a...))
}
// Sprint formats its operands with %v and returns the string. A space is added
// between two operands when neither is a string.
func Sprint(a ...any) string {
p := newPrinter()
p.doPrint(a)
return string(p.buf)
}
// Append formats its operands as Sprint does and appends the result to b.
func Append(b []byte, a ...any) []byte {
p := newPrinter()
p.doPrint(a)
return append(b, p.buf...)
}
// Fprint formats its operands as Sprint does and writes to w.
func Fprint(w io.Writer, a ...any) (n int, err error) {
p := newPrinter()
p.doPrint(a)
return w.Write(p.buf)
}
// Print formats its operands as Sprint does and prints the result.
func Print(a ...any) (n int, err error) {
return printOut(Sprint(a...))
}
// Sprintln formats its operands with %v, always separated by a space, and
// appends a newline.
func Sprintln(a ...any) string {
p := newPrinter()
p.doPrintln(a)
return string(p.buf)
}
// Appendln formats its operands as Sprintln does and appends the result to b.
func Appendln(b []byte, a ...any) []byte {
p := newPrinter()
p.doPrintln(a)
return append(b, p.buf...)
}
// Fprintln formats its operands as Sprintln does and writes to w.
func Fprintln(w io.Writer, a ...any) (n int, err error) {
p := newPrinter()
p.doPrintln(a)
return w.Write(p.buf)
}
// Println formats its operands as Sprintln does and prints the result.
func Println(a ...any) (n int, err error) {
return printOut(Sprintln(a...))
}
func printOut(s string) (int, error) {
var sb strings.Builder
n, err := sb.WriteString(s)
print(sb.String())
return n, err
}
// Errorf formats according to a format specifier and returns the string as an
// error. Each %w operand must be an error; it is printed as %v and returned by
// the error's Unwrap method, so errors.Is and errors.Unwrap can find it. One %w
// gives an Unwrap() error, several give an Unwrap() []error, as in Go.
func Errorf(format string, a ...any) error {
p := newPrinter()
p.wrapErrs = true
p.doPrintf(format, a)
s := string(p.buf)
switch len(p.wrapped) {
case 0:
return &errorString{s}
case 1:
w := &wrapError{msg: s}
w.err, _ = a[p.wrapped[0]].(error)
return w
default:
if p.reordered {
sortInts(p.wrapped)
}
var errs []error
for i, argNum := range p.wrapped {
if i > 0 && p.wrapped[i-1] == argNum {
continue
}
if e, ok := a[argNum].(error); ok {
errs = append(errs, e)
}
}
return &wrapErrors{s, errs}
}
}
type errorString struct {
s string
}
func (e *errorString) Error() string { return e.s }
type wrapError struct {
msg string
err error
}
func (e *wrapError) Error() string { return e.msg }
func (e *wrapError) Unwrap() error { return e.err }
type wrapErrors struct {
msg string
errs []error
}
func (e *wrapErrors) Error() string { return e.msg }
func (e *wrapErrors) Unwrap() []error { return e.errs }
// sortInts is an insertion sort: the slice holds one entry per %w.
func sortInts(a []int) {
for i := 1; i < len(a); i++ {
for j := i; j > 0 && a[j] < a[j-1]; j-- {
a[j], a[j-1] = a[j-1], a[j]
}
}
}