format

package
v2.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 17, 2025 License: MIT Imports: 9 Imported by: 1

README

format

a low-level string formatting library that takes arbitrary input types as interfaces, and arguments as a struct. this does not contain any printf-like argument parsing, only log-friendly serialization of arbitrary input arguments. (noting that our output is noticably more log-friendly for struct / map types than stdlib "fmt").

benchmarks:

goos: linux
goarch: amd64
pkg: codeberg.org/gruf/go-kv/v2/format
cpu: AMD Ryzen 7 7840U w/ Radeon  780M Graphics

# go-kv/v2/format (i.e. latest)
BenchmarkFormatV2Append
BenchmarkFormatV2Append-16                590422              1977 ns/op             488 B/op         23 allocs/op
BenchmarkFormatV2AppendVerbose
BenchmarkFormatV2AppendVerbose-16         375628              2981 ns/op            1704 B/op         45 allocs/op

# go-kv/format (i.e. v1)
BenchmarkFormatAppend
BenchmarkFormatAppend-16                  208357              5883 ns/op            2624 B/op        169 allocs/op
BenchmarkFormatAppendVerbose
BenchmarkFormatAppendVerbose-16            35916             33563 ns/op            3734 B/op        208 allocs/op

# fmt (i.e. stdlib)
BenchmarkFmtAppend
BenchmarkFmtAppend-16                     147722              8418 ns/op            4747 B/op        191 allocs/op
BenchmarkFmtAppendVerbose
BenchmarkFmtAppendVerbose-16              167112              7238 ns/op            4401 B/op        178 allocs/op

PASS
ok      codeberg.org/gruf/go-kv/v2/format

Documentation

Index

Constants

View Source
const (
	// TypeMask when set in argument flags
	// indicates that type information of
	// the passed value, and all nested types,
	// should be included in formatted output.
	TypeMask = uint64(1) << 0

	// LogfmtMask when set in argument flags
	// indicates that strings should be escaped
	// and quoted only where necessary. i.e. if
	// it contains any unsafe ASCII chars or double
	// quotes it will be quoted and escaped, if it
	// contains any spaces it will be quoted, and
	// all else will be printed as-is. This proves
	// particularly well readable in key-value types.
	LogfmtMask = uint64(1) << 1

	// NumberMask when set in argument flags
	// indicates that where possible value
	// types should be formatted as numbers,
	// i.e. byte or rune types.
	NumberMask = uint64(1) << 2

	// TextMask when set in argument flags
	// indicates that where possible value
	// types should be formatted as text,
	// i.e. []byte or []rune types.
	TextMask = uint64(1) << 3

	// QuotedTextMask when set in argument flags
	// indicates that text should always be quoted.
	QuotedTextMask = uint64(1) << 4

	// QuotedAsciiMask when set in argument flags
	// indicates that text should always be quoted,
	// and escaped as ASCII characters where needed.
	QuotedAsciiMask = uint64(1) << 5

	// NoMethodMask when set in argument flags
	// indicates that where a type supports a
	// known method, (e.g. Error() or String()),
	// this should not be used for formatting
	// instead treating as a method-less type.
	// e.g. printing the entire struct value of
	// a &url.URL{} without calling String().
	NoMethodMask = uint64(1) << 6
)
View Source
const (
	// SingleTermLine: beyond a certain length of string, all of the
	// extra checks to handle quoting/not-quoting add a significant
	// amount of extra processing time. Quoting in this manner only really
	// effects readability on a single line, so a max string length that
	// encompasses the maximum number of columns on *most* terminals was
	// selected. This was chosen using the metric that 1080p is one of the
	// most common display resolutions, and that a relatively small font size
	// of 7 requires 223 columns. So 256 should be >= $COLUMNS (fullscreen)
	// in 99% of usecases (these figures all pulled out of my ass).
	SingleTermLine = 256
)

Variables

This section is empty.

Functions

func AppendEscape

func AppendEscape(buf []byte, str string) []byte

AppendEscape will append 's' to 'buf' and escape any double quotes. EXPECTS ASCII.

func AppendEscapeByte

func AppendEscapeByte(buf []byte, c byte) []byte

AppendEscapeByte ...

func AppendEscapeRune

func AppendEscapeRune(buf []byte, r rune) []byte

AppendEscapeRune ...

func AppendQuoteByte

func AppendQuoteByte(buf []byte, c byte) []byte

AppendQuoteByte ...

func ContainsDoubleQuote

func ContainsDoubleQuote(s string) bool

ContainsDoubleQuote checks if "s" contains a double quote. EXPECTS ASCII.

func ContainsSpaceOrTab

func ContainsSpaceOrTab(s string) bool

ContainsSpaceOrTab checks if "s" contains space or tabs. EXPECTS ASCII.

func IsSafeASCII

func IsSafeASCII(str string) bool

IsSafeASCII checks whether string is printable (i.e. non-control char) ASCII text.

Types

type Args

type Args struct {

	// Boolean argument
	// flags as bit-field.
	Flags uint64

	// Integer
	// arguments.
	// i.e. for:
	// - int
	// - int8
	// - int16
	// - int32 (treated as rune char, number with NumberMask)
	// - int64
	Int IntArgs

	// Unsigned
	// integer
	// arguments.
	// i.e. for:
	// - uint
	// - uint8 (treated as byte char, number with NumberMask)
	// - uint16
	// - uint32
	// - uint64
	Uint IntArgs

	// Float
	// arguments.
	// i.e. for:
	// - float32
	// - float64
	Float FloatArgs

	// Complex
	// arguments.
	// i.e. for:
	// - complex64
	// - complex128
	Complex ComplexArgs
}

Args contains arguments for a call to a FormatFunc.

func DefaultArgs

func DefaultArgs() Args

DefaultArgs returns default set of formatter arguments.

func (*Args) AsNumber

func (a *Args) AsNumber() bool

AsNumber returns if NumberMask is set.

func (*Args) AsQuotedASCII

func (a *Args) AsQuotedASCII() bool

AsQuotedASCII returns if QuotedAsciiMask is set.

func (*Args) AsQuotedText

func (a *Args) AsQuotedText() bool

AsQuotedText returns if QuotedTextMask is set.

func (*Args) AsText

func (a *Args) AsText() bool

AsText returns if TextMask is set.

func (*Args) Logfmt

func (a *Args) Logfmt() bool

Logfmt returns if LogfmtMask is set.

func (*Args) NoMethod

func (a *Args) NoMethod() bool

NoMethod returns if NoMethodMask is set.

func (*Args) SetAsNumber

func (a *Args) SetAsNumber()

SetAsNumber sets the NumberMask bit.

func (*Args) SetAsQuotedASCII

func (a *Args) SetAsQuotedASCII()

SetAsQuotedASCII sets the QuotedAsciiMask bit.

func (*Args) SetAsQuotedText

func (a *Args) SetAsQuotedText()

SetAsQuotedText sets the QuotedTextMask bit.

func (*Args) SetAsText

func (a *Args) SetAsText()

SetAsText sets the TextMask bit.

func (*Args) SetLogfmt

func (a *Args) SetLogfmt()

SetLogfmt sets the LogfmtMask bit.

func (*Args) SetNoMethod

func (a *Args) SetNoMethod()

SetNoMethod sets the NoMethodMask bit.

func (*Args) SetWithType

func (a *Args) SetWithType()

SetWithType sets the TypeMask bit.

func (*Args) UnsetAsNumber

func (a *Args) UnsetAsNumber()

UnsetAsNumber unsets the NumberMask bit.

func (*Args) UnsetAsQuotedASCII

func (a *Args) UnsetAsQuotedASCII()

UnsetAsQuotedASCII unsets the QuotedAsciiMask bit.

func (*Args) UnsetAsQuotedText

func (a *Args) UnsetAsQuotedText()

UnsetAsQuotedText unsets the QuotedTextMask bit.

func (*Args) UnsetAsText

func (a *Args) UnsetAsText()

UnsetAsText unsets the TextMask bit.

func (*Args) UnsetLogfmt

func (a *Args) UnsetLogfmt()

UnsetLogfmt unsets the LogfmtMask bit.

func (*Args) UnsetNoMethod

func (a *Args) UnsetNoMethod()

UnsetNoMethod unsets the NoMethodMask bit.

func (*Args) UnsetWithType

func (a *Args) UnsetWithType()

UnsetWithType unsets the TypeMask bit.

func (*Args) WithType

func (a *Args) WithType() bool

WithType returns if TypeMask is set.

type ComplexArgs

type ComplexArgs struct {
	Real FloatArgs
	Imag FloatArgs
}

ComplexArgs provides a set of arguments for customizing complex number serialization, as real and imaginary float number parts.

type FloatArgs

type FloatArgs struct {
	Fmt  byte
	Prec int
}

FloatArgs provides a set of arguments for customizing float number serialization.

type FormatFunc

type FormatFunc func(*State)

FormatFunc defines a function capable of formatting the value contained in State{}.P, based on args in State{}.A, storing the result in buffer State{}.B.

type Formattable added in v2.0.6

type Formattable interface{ Format(*State) }

type Formatter

type Formatter struct {

	// Defaults defines the default
	// set of arguments to use when
	// none are supplied to calls to
	// Append() and AppendState().
	Defaults Args
	// contains filtered or unexported fields
}

Formatter provides access to value formatting provided by this library. It encompasses a set of configurable default arguments for when none are set, and an internal concurrency-safe cache of FormatFuncs to passed value type.

var Global Formatter

Global formatter instance.

func (*Formatter) Append

func (fmt *Formatter) Append(buf []byte, value any, args Args) []byte

Append calls AppendState() with a newly allocated State{}, returning byte buffer.

func (*Formatter) AppendState

func (fmt *Formatter) AppendState(s *State, value any)

AppendState will format the given value into the given State{}'s byte buffer, using currently-set arguments.

type IntArgs

type IntArgs struct {
	Base int
	Pad  int
}

IntArgs provides a set of arguments for customizing integer number serialization.

type State

type State struct {

	// A contains args
	// passed to this
	// FormatFunc call.
	A Args

	// B is the buffer
	// that values will
	// be formatted into.
	B []byte

	// P contains a ptr
	// to the value type
	// being formatted.
	P unsafe.Pointer
	// contains filtered or unexported fields
}

State contains all necessary arguments, buffer and value data pointer required for a FormatFunc operation, in a reusable structure if wanted.

type Stringer

type Stringer interface{ String() string }

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL