strutil: modernc.org/strutil Index | Examples | Files

package strutil

import "modernc.org/strutil"

Package strutil collects utils supplemental to the standard strings package.

Index

Examples

Package Files

strutil.go

func Base32ExtDecode Uses

func Base32ExtDecode(text []byte) (data []byte, err error)

Base32ExtDecode decodes base32 extended (RFC 4648) text to binary data.

func Base32ExtEncode Uses

func Base32ExtEncode(data []byte) (text []byte)

Base32ExtEncode encodes binary data to base32 extended (RFC 4648) encoded text.

func Base64Decode Uses

func Base64Decode(text []byte) (data []byte, err error)

Base64Decode decodes base64 text to binary data.

func Base64Encode Uses

func Base64Encode(data []byte) (text []byte)

Base64Encode encodes binary data to base64 encoded text.

func Gopath Uses

func Gopath() string

Gopath returns the value of the $GOPATH environment variable or its default value if not set.

func Homepath Uses

func Homepath() string

Homepath returns the user's home directory path.

func ImportPath Uses

func ImportPath() (string, error)

ImportPath returns the import path of the caller or an error, if any.

func JoinFields Uses

func JoinFields(flds []string, sep string) string

JoinFields returns strings in flds joined by sep. Flds may contain arbitrary bytes, including the sep as they are safely escaped. JoinFields panics if sep is the backslash character or if len(sep) != 1.

func PrettyPrint Uses

func PrettyPrint(w io.Writer, v interface{}, prefix, suffix string, hooks PrettyPrintHooks)

PrettyPrint pretty prints v to w. Zero values and unexported struct fields are omitted.

Force printing of zero values of struct fields by including in the field tag PrettyPrint:"zero".

Enable using a String method, if any, of a struct field type by including in the field tag PrettyPrint:"stringer".

The tags can be combined as in PrettyPrint:"zero,stringer". The order is not important, so PrettyPrint:stringer,zero has the same effect.

A hook attached to the field type has priority over the struct field tag described above.

func PrettyString Uses

func PrettyString(v interface{}, prefix, suffix string, hooks PrettyPrintHooks) string

PrettyString returns the output of PrettyPrint as a string.

Code:

type prettyStringType struct {
    Array         [3]int
    Bool          bool
    Chan          <-chan int
    Complex128    complex128
    Complex64     complex64
    Float32       float32
    Float64       float64
    Func          func()
    Func2         interface{}
    Func3         interface{}
    Int           int
    Int16         int16
    Int32         int32
    Int64         int64
    Int8          int8
    Interface     interface{}
    Map           map[int]string
    Ptr           *int
    Slice         []int
    String        string
    Struct        *prettyStringType
    Struct2       *prettyStringType
    Uint          uint
    Uint16        uint16
    Uint32        uint32
    Uint64        uint64
    Uint8         byte
    Uintptr       uintptr
    UnsafePointer unsafe.Pointer
}

i := 314
v := &prettyStringType{
    Array:         [...]int{10, 20, 30},
    Bool:          true,
    Chan:          make(<-chan int, 100),
    Complex128:    3 - 4i,
    Complex64:     1 + 2i,
    Float32:       1.5,
    Float64:       3.5,
    Func2:         func(a, b, c int, z ...string) (d, e, f string) { return },
    Func3:         func(a, b, c int, z ...string) {},
    Func:          func() {},
    Int16:         -44,
    Int32:         -45,
    Int64:         -46,
    Int8:          -43,
    Int:           -42,
    Map:           map[int]string{100: "100", 200: "200", 300: "300"},
    Ptr:           &i,
    Slice:         []int{10, 20, 30},
    String:        "foo",
    Struct:        &prettyStringType{Int: 8888},
    Struct2:       &prettyStringType{},
    Uint16:        44,
    Uint32:        45,
    Uint64:        46,
    Uint8:         43,
    Uint:          42,
    Uintptr:       uintptr(99),
    UnsafePointer: unsafe.Pointer(uintptr(0x12345678)),
}
v.Interface = v
fmt.Println(PrettyString(v, "", "", nil))

Output:

&strutil.prettyStringType{
· Array: [3]int{
· · 0: 10,
· · 1: 20,
· · 2: 30,
· },
· Bool: true,
· Chan: <-chan int// capacity: 100,
· Complex128: (3-4i),
· Complex64: (1+2i),
· Float32: 1.5,
· Float64: 3.5,
· Func: func() { ... },
· Func2: func(int, int, int, ...string) (string, string, string) { ... },
· Func3: func(int, int, int, ...string) { ... },
· Int: -42,
· Int16: -44,
· Int32: -45,
· Int64: -46,
· Int8: -43,
· Interface: &strutil.prettyStringType{ /* recursive/repetitive pointee not shown */ },
· Map: map[int]string{
· · 100: "100",
· · 200: "200",
· · 300: "300",
· },
· Ptr: &314,
· Slice: []int{ // len 3
· · 0: 10,
· · 1: 20,
· · 2: 30,
· },
· String: "foo",
· Struct: &strutil.prettyStringType{
· · Int: 8888,
· },
· Uint: 42,
· Uint16: 44,
· Uint32: 45,
· Uint64: 46,
· Uint8: 43,
· Uintptr: 99,
· UnsafePointer: 0x12345678,
}

func SplitFields Uses

func SplitFields(s, sep string) (flds []string)

SplitFields splits s, which must be produced by JoinFields using the same sep, into flds. SplitFields panics if sep is the backslash character or if len(sep) != 1.

func StrPack Uses

func StrPack(s string) string

StrPack returns a new instance of s which is tightly packed in memory. It is intended for avoiding the situation where having a live reference to a string slice over an unreferenced biger underlying string keeps the biger one in memory anyway - it can't be GCed.

type Dict Uses

type Dict struct {
    // contains filtered or unexported fields
}

Dict is a string <-> id bijection. Dict is *not* concurrent access safe for assigning new ids to strings not yet contained in the bijection. Id for an empty string is guaranteed to be 0, thus Id for any non empty string is guaranteed to be non zero.

func NewDict Uses

func NewDict() (d *Dict)

NewDict returns a newly created Dict.

func (*Dict) Count Uses

func (d *Dict) Count() int

Count returns the number of items in the dict.

func (*Dict) Id Uses

func (d *Dict) Id(s string) (y int)

Id maps string s to its numeric identificator.

func (*Dict) S Uses

func (d *Dict) S(id int) (s string, ok bool)

S maps an id to its string value and ok == true. Id values not contained in the bijection return "", false.

type Formatter Uses

type Formatter interface {
    io.Writer
    Format(format string, args ...interface{}) (n int, errno error)
}

Formatter is an io.Writer extended by a fmt.Printf like function Format

func FlatFormatter Uses

func FlatFormatter(w io.Writer) Formatter

FlatFormatter returns a newly created Formatter with the same functionality as the one returned by IndentFormatter except it allows a newline in the 'format' string argument of Format to pass through iff indent level is currently zero.

If indent level is non-zero then such new lines are changed to a space character. There is no indent string, the %i and %u format verbs are used solely to determine the indent level.

The FlatFormatter is intended for flattening of normally nested structure textual representation to a one top level structure per line form.

FlatFormatter(os.Stdout, " ").Format("abc%d%%e%i\nx\ny\n%uz\n", 3)

output in the form of a Go quoted string literal:

"abc3%%e x y z\n"

func IndentFormatter Uses

func IndentFormatter(w io.Writer, indent string) Formatter

IndentFormatter returns a new Formatter which interprets %i and %u in the Format() format string as indent and undent commands. The commands can nest. The Formatter writes to io.Writer 'w' and inserts one 'indent' string per current indent level value. Behaviour of commands reaching negative indent levels is undefined.

IndentFormatter(os.Stdout, "\t").Format("abc%d%%e%i\nx\ny\n%uz\n", 3)

output:

abc3%e
	x
	y
z

The Go quoted string literal form of the above is:

"abc%%e\n\tx\n\tx\nz\n"

The commands can be scattered between separate invocations of Format(), i.e. the formatter keeps track of the indent level and knows if it is positioned on start of a line and should emit indentation(s). The same output as above can be produced by e.g.:

f := IndentFormatter(os.Stdout, " ")
f.Format("abc%d%%e%i\nx\n", 3)
f.Format("y\n%uz\n")

type GoDict Uses

type GoDict struct {
    // contains filtered or unexported fields
}

GoDict is a concurrent access safe version of Dict.

func NewGoDict Uses

func NewGoDict() (d *GoDict)

NewGoDict returns a newly created GoDict.

func (*GoDict) Count Uses

func (d *GoDict) Count() int

Count returns the number of items in the dict.

func (*GoDict) Id Uses

func (d *GoDict) Id(s string) (y int)

Id maps string s to its numeric identificator. The implementation honors getting an existing id at the cost of assigning a new one.

func (*GoDict) S Uses

func (d *GoDict) S(id int) (s string, ok bool)

S maps an id to its string value and ok == true. Id values not contained in the bijection return "", false.

type GoPool Uses

type GoPool struct {
    // contains filtered or unexported fields
}

GoPool is a concurrent access safe version of Pool.

func NewGoPool Uses

func NewGoPool() (p *GoPool)

NewGoPool returns a newly created GoPool.

func (*GoPool) Align Uses

func (p *GoPool) Align(s string) (y string)

Align returns a string with the same value as its argument. It guarantees that all aligned strings share a single instance in memory.

func (*GoPool) Count Uses

func (p *GoPool) Count() int

Count returns the number of items in the pool.

type Pool Uses

type Pool struct {
    // contains filtered or unexported fields
}

Pool handles aligning of strings having equal values to the same string instance. Intended use is to conserve some memory e.g. where a large number of identically valued strings with non identical backing arrays may exists in several semantically distinct instances of some structs. Pool is *not* concurrent access safe. It doesn't handle common prefix/suffix aligning, e.g. having s1 == "abc" and s2 == "bc", s2 is not automatically aligned as s1[1:].

func NewPool Uses

func NewPool() *Pool

NewPool returns a newly created Pool.

func (*Pool) Align Uses

func (p *Pool) Align(s string) string

Align returns a string with the same value as its argument. It guarantees that all aligned strings share a single instance in memory.

func (*Pool) Count Uses

func (p *Pool) Count() int

Count returns the number of items in the pool.

type PrettyPrintHooks Uses

type PrettyPrintHooks map[reflect.Type]func(f Formatter, v interface{}, prefix, suffix string)

PrettyPrintHooks allow to customize the result of PrettyPrint for types listed in the map value.

Package strutil imports 13 packages (graph) and is imported by 26 packages. Updated 2019-09-30. Refresh now. Tools for package owners.