nstd

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2025 License: MIT Imports: 9 Imported by: 3

README

nstd is a single-package go module which provides some missing types and functions in the standard library.

Examples: https://go101.org/apps-and-libs/nstd.html

Docs: https://docs.go101.org/std/pkg/go101.org/nstd.html

Documentation

Overview

nstd package provides some missing types and functions in the standard library.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendMapKeys added in v0.0.6

func AppendMapKeys[K comparable, E any](s []K, m map[K]E) []K

AppendMapKeys appends all the keys in a map into the specified slice.

func BlankMap added in v0.1.3

func BlankMap[M ~map[K]E, K comparable, E any](_ M, capHint int) M

BlankMap returns a blank map which has the same type as the input map. It is mainly used to avoid writing some verbose map type literals.

* Usage 1: BlankMap[MapType](nil, 32) * Usage 2: BlankMap(aMap, 8)

func Btoi

func Btoi[B ~bool](x B) int

Btoi converts a bool value to int (true -> 1, false -> 0).

See: https://github.com/golang/go/issues/64825

func ByteSeqCommonPrefix

func ByteSeqCommonPrefix[X, Y ByteSeq](x X, y Y) (x2 X, y2 Y)

ByteSeqCommonPrefixes returns the common prefixes of two ByteSeq values.

func Clamp

func Clamp[T Ordered](v, min, max T) T

Clamp clamps an ordered value within a range. Both min and max are inclusive. If v is NaN, then NaN is returned.

See: https://github.com/golang/go/issues/58146

func CloneSlice added in v0.1.3

func CloneSlice[S ~[]T, T any](s S) S

CloneSlice clones a slice. Different from slices.Clone, the result of CloneSlice always has equal length and capacity.

func CollectMapKeys added in v0.0.6

func CollectMapKeys[K comparable, E any](m map[K]E) []K

CollectMapKeys collects all the keys in a map into a freshly created result slice. The length and capacity of the result slice are both equal to the length of the map.

See: https://github.com/golang/go/issues/68261

func CopyDir added in v0.0.9

func CopyDir(dest, src string) error

CopyDir copies a directory.

func Debug added in v0.1.0

func Debug(v ...any) bool

Debug calls log.Print and returns true, so that it can be used in

_ = DebugMode && nstd.Debug(...)

func Debugf added in v0.1.0

func Debugf(format string, v ...any) bool

Debugf calls log.Printf and return true, so that it can be used in

_ = DebugMode && nstd.Debugf(...)

func ElapsedTimeLogFunc

func ElapsedTimeLogFunc(commonPrefix string) func(prefix string) bool

ElapsedTimeLogFunc returns a function which prints the duration elapsed since the time the function is invoked.

Use example:

logElapsedTime := nstd.ElapsedTimeLogFunc("")
... // do task 1
logElapsedTime("task 1:")
... // do task 1
logElapsedTime("task 2:")

func Error added in v0.1.2

func Error(text string) error

Error returns an error that formats as the given text. Different from errors.New in the std library, two calls to Error return an identical error value if the texts are identical.

func Eval

func Eval[T any](v T) T

Eval is used to ensure the evaluation order of some expressions in a statement.

See:

* https://go101.org/article/evaluation-orders.html * https://github.com/golang/go/issues/27804 * https://github.com/golang/go/issues/36449

func HasEntry

func HasEntry[K comparable, E any](m map[K]E, key K) bool

HasMapEntry checks whether or not a map contains an entry with the specified key.

func MakeSlice added in v0.0.6

func MakeSlice[S ~[]E, E any](len int) S

MakeSlice makes a slice with the specified length. Different from the built-in [make] function, the capacity of the result slice might be larger than the length.

func MakeSliceWithMinCap added in v0.0.9

func MakeSliceWithMinCap[S ~[]E, E any](cap int) S

MakeSliceWithMinCap makes a slice with capacity not smaller than cap. The length of the result slice is zero.

See: https://github.com/golang/go/issues/69872

func Must

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

Must panics if err is not nil; otherwise, the T value is returned.

The function is mianly to support chain calls like Must(...).MethodOfT(...).

See: https://github.com/golang/go/issues/58280

func New

func New[T any](v T) *T

New allocates a T value and initialize it with the specified one.

func Panicf

func Panicf(format string, a ...any) bool

Generally, Panicf(format, v...) is a short form of panic(fmt.Sprintf(format, v...)). When format is blank, then it is a short form of panic(fmt.Sprint(v...)).

func Printfln

func Printfln(format string, a ...any) (n int, err error)

Printfln(format, a...) is a combintion of fmt.Printf(format, a...) and fmt.Println().

func ReverseByteSeq added in v0.0.8

func ReverseByteSeq[Seq ByteSeq](s Seq) []byte

ReverseByteSeq returnes a copy (in the form of byte slice) of a byte sequence (in the form of either string or byte slice) but reversed.

func ReverseBytes added in v0.0.8

func ReverseBytes[Bytes ~[]byte](s Bytes) Bytes

ReverseBytes inverts the bytes in a byte slice. The argument is returned so that calls to ReverseBytes can be used as expressions.

func ReverseRuneSeq added in v0.0.8

func ReverseRuneSeq[Seq ByteSeq](s Seq) []byte

ReverseRuneSeq returnes a copy (in the form of byte slice) of a rune sequence (in the form of either string or byte slice) but reversed.

See:

* https://github.com/golang/go/issues/14777 * https://github.com/golang/go/issues/68348

func Sign

func Sign[T Signed](x T) int

Sign returns the sign of a value of a Signed integer type. For a negative integer, it returns -1; for a positive integer, it returns 1; for 0, it returns 0.

func SliceElemPointers added in v0.1.3

func SliceElemPointers[E any](s []E) func(func(*E) bool)

SliceElemPointers returns an iterator which iterates element pointers of a slice.

func SliceFrom

func SliceFrom[T any](vs ...T) []T

SliceFrom is used to create a slice from some values of the same type. Some use scenarios:

  1. Convert multiple results of a function call to a []any slice, then use the slice in fmt.Printf alike functions.
  2. Construct a []T slice from some T values without using the []T{...} form.

NOTE: SliceFrom(aSlice...) returns aSlice,

See: https://github.com/golang/go/issues/61213

func TrackError added in v0.1.5

func TrackError(err, target error) bool

TrackError reports whether any error in err's tree matches target. It behaves almost the same as errors.Is, except that

* TrackError(anIncomparbleErr, anIncomparbleErr) panics. * TrackError(&aComparableErr, aComparableErr) returns true. * It panics if the type of target is a pointer which base type's size is 0.

See: https://github.com/golang/go/issues/74488

func TrackErrorOf added in v0.1.5

func TrackErrorOf[ErrorType error](err error, _ ...ErrorType) *ErrorType

TrackErrorOf finds the first error in err's tree that matches ErrorType, and if one is found, returns a pointer to a copy of that error. Otherwise, it returns nil.

Different from errors.As,

  • If *ErrorType is also an error type, then TrackErrorOf doesn't distinguish ErrorType and *ErrorType.
  • If ErrorType is pointer type and its base type is also an error type, then TrackErrorOf doesn't distinguish ErrorType and its base type.

func Type

func Type[T any]() reflect.Type

Type returns a reflect.Type which represents type T, which may be either an non-interface type or interface type.

func TypeAssert added in v0.0.3

func TypeAssert[T any](x any, into *T) (ok bool)

TypeAssert asserts an interface value x to type T. If the assertion succeeds, true is returned, othewise, false is returned. If into is not nil, then the concrete value of x will be assigned to the value referenced by into.

See: https://github.com/golang/go/issues/65846

func TypeOf

func TypeOf[T any](v T) reflect.Type

TypeOf returns a reflect.Type which represents the type of v, which may be either an non-interface value or interface value.

func UnnamedSlice added in v0.1.3

func UnnamedSlice[S ~[]T, T any](s S) []T

UnnamedSlice converts s to unnamed type.

func ValueOf

func ValueOf[T any](v T) reflect.Value

Value returns a reflect.Value which represents the value v, which may be either an non-interface value or interface value.

func WriteStringWithBuffer

func WriteStringWithBuffer(w io.Writer, s string, buffer []byte) (int, error)

WriteStringWithBuffer writes a string into an io.Writer with a provided buffer. The buffer is used to avoid a string-> []byte conversion (which might allocate). This function is like io.CopyBuffer but much simpler.

func WriteWithCheck added in v0.0.6

func WriteWithCheck(w io.Writer, p []byte) (n int, err error)

CheckWriteResult checks whether or not a Write method is badly implemented.

See:

* https://github.com/golang/go/issues/67921 * https://github.com/golang/go/issues/9096

func Zero

func Zero[T any](p *T)

Zero(p) zeros the value referenced by the pointer p. Zero is useful for resetting values of some unexported types, or resetting values of some other packages but without importing those packages.

func ZeroOf added in v0.0.7

func ZeroOf[T any](T) T

ZeroOf[T]() and ZeroOf(valueOfT) both return the zero value of type T.

Types

type BoolElementMap added in v0.1.0

type BoolElementMap[K comparable] struct {
	// contains filtered or unexported fields
}

BoolElementMap is optimized version of map[K]bool. Entries with false element value will not be put in BoolElementMap maps.

func (*BoolElementMap[K]) Get added in v0.1.0

func (m *BoolElementMap[K]) Get(k K) bool

Get returns the element indexed by key k.

func (*BoolElementMap[K]) Put added in v0.1.0

func (m *BoolElementMap[K]) Put(k K, e bool)

Put puts an entry {k, e} into m. Note, if e is false and the corresponding entry exists, the entry is deleted.

type BoolKeyMap added in v0.1.0

type BoolKeyMap[E any] struct {
	// contains filtered or unexported fields
}

BoolKeyMap is an optimized version of map[bool]E.

func (*BoolKeyMap[E]) Get added in v0.1.0

func (m *BoolKeyMap[E]) Get(k bool) E

Get returns the element indexed by key k.

func (*BoolKeyMap[E]) Put added in v0.1.0

func (m *BoolKeyMap[E]) Put(k bool, e E)

Put puts an entry {k, e} into m.

type ByteSeq

type ByteSeq interface{ ~string | ~[]byte }

A ByteSeq is either a string or a byte slice.

type Complex

type Complex interface {
	~complex64 | ~complex128
}

Complex is a constraint that permits any complex numeric type. If future releases of Go add new predeclared complex numeric types, this constraint will be modified to include them.

type Float

type Float interface {
	~float32 | ~float64
}

Float is a constraint that permits any floating-point type. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.

type Integer

type Integer interface {
	Signed | Unsigned
}

Integer is a constraint that permits any integer type. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.

type Mutex

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

Methods of *Mutex return a *Mutex result, so that these methods may be called in a chain. It is just a simpler wrapper of the sync.Mutex. The main purpose of this type is to support the following use case:

var aMutex nstd.Mutex

func foo() {
	defer aMutex.Lock().Unlock()
	... // do something
}

func (*Mutex) Do

func (m *Mutex) Do(f func())

Do guards the execution of a function in Lock() and Unlock()

See: https://github.com/golang/go/issues/63941

func (*Mutex) Lock

func (m *Mutex) Lock() *Mutex

Lock return m, so that the methods of m can be called in chain.

func (*Mutex) Unlock

func (m *Mutex) Unlock() *Mutex

Unlock return m, so that the methods of m can be called in chain.

type Numeric

type Numeric interface {
	Integer | Float | Complex
}

type Ordered

type Ordered interface {
	Real | ~string
}

Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

type Real

type Real interface {
	Integer | Float
}

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

Signed is a constraint that permits any signed integer type. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.

type Unsigned

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Unsigned is a constraint that permits any unsigned integer type. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.

type WaitGroup

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

WaitGroup extends sync.WaitGroup. Each WaitGroup maintains an internal count which initial value is zero.

func (*WaitGroup) Go

func (wg *WaitGroup) Go(fs ...func())

GoN starts several concurrent tasks and increases the internal count by len(fs). The internal count will be descreased by one when each of the task is done.

See: https://github.com/golang/go/issues/18022

func (*WaitGroup) GoN

func (wg *WaitGroup) GoN(n int, f func())

GoN starts a task n times concurrently and increases the internal count by n. The internal count will be descreased by one when each of the task instances is done.

func (*WaitGroup) Wait added in v0.0.9

func (wg *WaitGroup) Wait()

Wait blocks until the internal counter is zero.

func (*WaitGroup) WaitChannel added in v0.0.9

func (wg *WaitGroup) WaitChannel() <-chan struct{}

WaitChannel returns a channel which reads will block until the internal counter is zero.

Jump to

Keyboard shortcuts

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