w

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: Apache-2.0 Imports: 22 Imported by: 8

Documentation

Overview

Package w provides generic helpers for functions, slices, maps, templates, queues, and process groups.

Index

Constants

View Source
const (
	// PosRight truncates from the right, keeping the start of the slice.
	PosRight = iota
	// PosLeft truncates from the left, keeping the end of the slice.
	PosLeft
	// PosCenter truncates from the middle, keeping both ends of the slice.
	PosCenter
)

Variables

View Source
var (
	// QueueFull is returned by RingQueue.Put when the queue has no remaining capacity.
	QueueFull = errors.New("queue is full") //nolint:revive
	// QueueNull is returned by RingQueue.Get when the queue is empty.
	QueueNull = errors.New("queue is null") //nolint:revive
)
View Source
var (
	// GitCommit is the git commit hash of the build, typically set via -ldflags.
	GitCommit string
	// BuildDate is the build timestamp, typically set via -ldflags.
	BuildDate string
	// GoVersion is the Go toolchain version used to build the binary, typically set via -ldflags.
	GoVersion string
	// Platform is the GOOS/GOARCH of the build, typically set via -ldflags.
	Platform string
	// Version is the semantic version of the build. It defaults to "0.0.0".
	Version string = "0.0.0"
)
View Source
var ErrStopping = errors.New("program stopping")

ErrStopping is returned by Group.Run when a termination signal is received.

View Source
var ExitFunc = os.Exit

ExitFunc is the function used to terminate the process after a shutdown timeout. It defaults to os.Exit.

View Source
var NopInterrupt = func(err error) {}

NopInterrupt is an interrupt function that does nothing.

Functions

func AddFuncMaps

func AddFuncMaps(funcName string, f interface{})

AddFuncMaps registers a named function that templates can call.

func AddVersionFlags

func AddVersionFlags(flagFunc func(shortVersion, fullVersion string))

AddVersionFlags normalizes BuildDate to RFC3339 when possible and passes the short and full version strings to flagFunc.

func DefaultNumber

func DefaultNumber[T Number](vals ...T) T

DefaultNumber returns the first non-zero number among vals, or the zero value if all are zero.

func DefaultPointer

func DefaultPointer[T any](vals ...*T) *T

DefaultPointer returns the first non-nil pointer among vals, or nil if all are nil.

func DefaultString

func DefaultString(vals ...string) string

DefaultString returns the first non-empty string among vals, or "" if all are empty.

func E

func E[T any](_ T, err error) error

E returns the error from a (value, error) pair, discarding the value.

func Filter

func Filter[T any](old []T, f func(item T) bool) []T

Filter returns a new slice containing only the items for which f returns true.

func Find

func Find[T any](s []T, f func(T) bool) T

Find returns the first element for which f returns true, or the zero value of T if none matches.

func FindIndex

func FindIndex[T any](s []T, t T, compare func(a, b T) bool) int

FindIndex returns the index of the first element that compare considers equal to t, or -1 if none matches.

func GroupBy

func GroupBy[T any, K comparable, V any](old []T, f func(item T) (groupKey K, value V)) map[K][]V

GroupBy groups items by the key returned from f and collects the corresponding values.

func Has

func Has[T any](s []T, t T, compare func(a, b T) bool) bool

Has reports whether s contains an element that compare considers equal to t.

func Include

func Include[T comparable](s []T, t T) bool

Include reports whether s contains t.

func Index

func Index[T comparable](s []T, t T) int

Index returns the index of the first occurrence of t in s, or -1 if t is not present.

func Interfaces

func Interfaces[T any](objs []T) []interface{}

Interfaces converts a slice of T to a slice of interface{}.

func JSONStringer

func JSONStringer(v any) fmt.Stringer

JSONStringer returns an fmt.Stringer that encodes v as JSON.

func Limit

func Limit[T any](s []T, limit int, hidePosition int, manySuffix ...T) []T

Limit shortens s to at most limit elements, hiding overflow at hidePosition and appending manySuffix.

func M

func M[T any](v T, err error) T

M unwraps a (value, error) pair and returns the value, or panics if err is non-nil.

func Map

func Map[S any, T any](old []S, f func(item S) T) []T

Map applies f to each item in old and returns a new slice of the results.

func Merge

func Merge[M ~map[K]V, K comparable, V any](maps ...M) M

Merge combines maps into a single map. Later maps overwrite earlier keys.

func NewStringer

func NewStringer(stringer func() string) fmt.Stringer

NewStringer returns an fmt.Stringer that calls stringer to produce its string value.

func P

func P[T any](o T) *T

P takes the address of o and returns a pointer to a copy of o.

func Pipe

func Pipe[sT any, dT any](v sT, e error) func(func(sT) (dT, error)) (dT, error)

Pipe returns a function that applies f to v if e is nil, or returns the zero value of dT and e otherwise.

func StringEqual

func StringEqual(a, b string) bool

StringEqual reports whether a and b are equal.

func T

func T[vT any](expr bool, trueVal, falseVal vT) vT

T is a ternary operator: it returns trueVal if expr is true, and falseVal otherwise.

Types

type Comparable

type Comparable interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64 | ~string
}

Comparable is the constraint of ordered types that can be used as SortedMap keys.

type Equal

type Equal[T any] interface {
	// Equal reports whether the receiver is equal to the given value.
	Equal(T) bool
}

Equal is implemented by types that can compare themselves to a value of type T.

type Group

type Group run.Group

Group is a collection of actors that run concurrently and interrupt together.

func (*Group) Add

func (g *Group) Add(execute func() error, interrupt func(error))

Add registers execute to run as part of the group. interrupt is called when the group begins shutting down.

func (*Group) Run

func (g *Group) Run() error

Run starts all registered actors and blocks until they have all finished.

type Number

type Number interface {
	~int8 | ~int16 | ~int32 | ~int64 |
		~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float64 | ~float32 | ~int | ~uint
}

Number is the constraint of integer and floating-point types accepted by DefaultNumber.

type OneOrMore

type OneOrMore[T any] []T

OneOrMore is a slice that marshals as a single value when it has one element, and as an array otherwise.

func (OneOrMore[T]) Contains

func (s OneOrMore[T]) Contains(value T) bool

Contains reports whether value is present in the slice.

func (OneOrMore[T]) MarshalJSON

func (s OneOrMore[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, encoding a single-element slice as a JSON value rather than an array.

func (OneOrMore[T]) MarshalYAML

func (s OneOrMore[T]) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaler by encoding a single-element slice as a scalar.

func (*OneOrMore[T]) UnmarshalJSON

func (s *OneOrMore[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, accepting either a single JSON value or a JSON array.

func (*OneOrMore[T]) UnmarshalYAML

func (s *OneOrMore[T]) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler, accepting either a YAML scalar or a sequence.

type RingQueue

type RingQueue[T any] struct {
	// contains filtered or unexported fields
}

RingQueue is a concurrent, fixed-capacity ring buffer.

func NewRingQueue

func NewRingQueue[T any](n int) *RingQueue[T]

NewRingQueue returns a RingQueue that can hold at most n elements.

func (*RingQueue[T]) Do

func (r *RingQueue[T]) Do(f func(a T))

Do calls f for each element currently in the queue, from front to back.

func (*RingQueue[T]) Get

func (r *RingQueue[T]) Get() (T, error)

Get removes and returns the front element. It returns QueueNull if the queue is empty.

func (*RingQueue[T]) Len

func (r *RingQueue[T]) Len() int

Len reports the number of elements currently in the queue.

func (*RingQueue[T]) List

func (r *RingQueue[T]) List() []T

List returns a snapshot of the elements currently in the queue, from front to back.

func (*RingQueue[T]) Put

func (r *RingQueue[T]) Put(val T) error

Put appends val to the queue. It returns QueueFull if the queue has no remaining capacity.

func (*RingQueue[T]) Remove

func (r *RingQueue[T]) Remove(f func(a T) bool)

Remove deletes every element for which f returns true.

type SortedMap

type SortedMap[K Comparable, V any] []SortedMapItem[K, V]

SortedMap is a slice of key-value pairs sorted by key.

func NewSortedMap

func NewSortedMap[K Comparable, V any](kvs ...map[K]V) SortedMap[K, V]

NewSortedMap builds a SortedMap from one or more maps and sorts it by key.

func (SortedMap[K, V]) Len

func (s SortedMap[K, V]) Len() int

Len reports the number of items in the sorted map.

func (SortedMap[K, V]) Less

func (s SortedMap[K, V]) Less(i, j int) bool

Less reports whether the item at i should sort before the item at j.

func (SortedMap[K, V]) Swap

func (s SortedMap[K, V]) Swap(i, j int)

Swap exchanges the items at i and j.

type SortedMapItem

type SortedMapItem[K Comparable, V any] struct {
	// Key is the map key used for sorting.
	Key K
	// Value is the value associated with Key.
	Value V
}

SortedMapItem is a key-value pair stored in a SortedMap.

type Stringer

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

Stringer wraps a function as an fmt.Stringer.

func (Stringer) String

func (s Stringer) String() string

String implements fmt.Stringer by calling the wrapped function.

type Template

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

Template holds a parsed text or HTML template together with its raw source.

func NewHTMLTemplate

func NewHTMLTemplate(raw string) (*Template, error)

NewHTMLTemplate parses raw as an html/template and returns a Template.

func NewTextTemplate

func NewTextTemplate(raw string) (*Template, error)

NewTextTemplate parses raw as a text/template and returns a Template.

func (*Template) DefinedTemplates

func (t *Template) DefinedTemplates() string

DefinedTemplates returns a string listing the defined template names.

func (*Template) Execute

func (t *Template) Execute(wr io.Writer, data any) error

Execute applies the template to data and writes the output to wr.

func (*Template) ExecuteTemplate

func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error

ExecuteTemplate applies the named template to data and writes the output to wr.

func (*Template) ExecuteToString

func (t *Template) ExecuteToString(data any) (string, error)

ExecuteToString applies the template to data and returns the output as a string.

func (Template) MarshalJSON

func (t Template) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler by returning the raw template source.

func (Template) MarshalYAML

func (t Template) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaler by returning the raw template source.

func (*Template) Name

func (t *Template) Name() string

Name returns the name of the underlying template.

func (*Template) UnmarshalJSON

func (t *Template) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON implements json.Unmarshaler. A JSON string is parsed as a text template; a single-key object such as {"fn::html": "..."} selects the parser.

func (*Template) UnmarshalYAML

func (t *Template) UnmarshalYAML(value *yaml.Node) (err error)

UnmarshalYAML implements yaml.Unmarshaler. It parses a text or HTML template from a YAML scalar, using tags such as !text, !html, !file, and !htmlFile.

type TemplateHandler

type TemplateHandler interface {
	// Name returns the name of the template.
	Name() string
	// ExecuteTemplate applies the named template to data and writes the output to wr.
	ExecuteTemplate(wr io.Writer, name string, data any) error
	// Execute applies the template to data and writes the output to wr.
	Execute(wr io.Writer, data any) error
	// DefinedTemplates returns a string listing the defined template names.
	DefinedTemplates() string
}

TemplateHandler is the common execution surface shared by text and HTML templates.

Jump to

Keyboard shortcuts

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