Documentation
¶
Overview ¶
nstd package provides some missing types and functions in the standard library.
Index ¶
- func AppendMapKeys[K comparable, E any](s []K, m map[K]E) []K
- func BlankMap[M ~map[K]E, K comparable, E any](_ M, capHint int) M
- func Btoi[B ~bool](x B) int
- func ByteSeqCommonPrefix[X, Y ByteSeq](x X, y Y) (x2 X, y2 Y)
- func Clamp[T Ordered](v, min, max T) T
- func CloneSlice[S ~[]T, T any](s S) S
- func CollectMapKeys[K comparable, E any](m map[K]E) []K
- func CopyDir(dest, src string) error
- func Debug(v ...any) bool
- func Debugf(format string, v ...any) bool
- func ElapsedTimeLogFunc(commonPrefix string) func(prefix string) bool
- func Error(text string) error
- func Eval[T any](v T) T
- func HasEntry[K comparable, E any](m map[K]E, key K) bool
- func MakeSlice[S ~[]E, E any](len int) S
- func MakeSliceWithMinCap[S ~[]E, E any](cap int) S
- func Must[T any](v T, err error) T
- func New[T any](v T) *T
- func Panicf(format string, a ...any) bool
- func Printfln(format string, a ...any) (n int, err error)
- func ReverseByteSeq[Seq ByteSeq](s Seq) []byte
- func ReverseBytes[Bytes ~[]byte](s Bytes) Bytes
- func ReverseRuneSeq[Seq ByteSeq](s Seq) []byte
- func Sign[T Signed](x T) int
- func SliceElemPointers[E any](s []E) func(func(*E) bool)
- func SliceFrom[T any](vs ...T) []T
- func TrackError(err, target error) bool
- func TrackErrorOf[ErrorType error](err error, _ ...ErrorType) *ErrorType
- func Type[T any]() reflect.Type
- func TypeAssert[T any](x any, into *T) (ok bool)
- func TypeOf[T any](v T) reflect.Type
- func UnnamedSlice[S ~[]T, T any](s S) []T
- func ValueOf[T any](v T) reflect.Value
- func WriteStringWithBuffer(w io.Writer, s string, buffer []byte) (int, error)
- func WriteWithCheck(w io.Writer, p []byte) (n int, err error)
- func Zero[T any](p *T)
- func ZeroOf[T any](T) T
- type BoolElementMap
- type BoolKeyMap
- type ByteSeq
- type Complex
- type Float
- type Integer
- type Mutex
- type Numeric
- type Ordered
- type Real
- type Signed
- type Unsigned
- type WaitGroup
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 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.
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.
func Debug ¶ added in v0.1.0
Debug calls log.Print and returns true, so that it can be used in
_ = DebugMode && nstd.Debug(...)
func Debugf ¶ added in v0.1.0
Debugf calls log.Printf and return true, so that it can be used in
_ = DebugMode && nstd.Debugf(...)
func ElapsedTimeLogFunc ¶
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
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
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
MakeSliceWithMinCap makes a slice with capacity not smaller than cap. The length of the result slice is zero.
func Must ¶
Must panics if err is not nil; otherwise, the T value is returned.
The function is mianly to support chain calls like Must(...).MethodOfT(...).
func New ¶
func New[T any](v T) *T
New allocates a T value and initialize it with the specified one.
func Panicf ¶
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 ¶
Printfln(format, a...) is a combintion of fmt.Printf(format, a...) and fmt.Println().
func ReverseByteSeq ¶ added in v0.0.8
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
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 ¶
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
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:
- Convert multiple results of a function call to a []any slice, then use the slice in fmt.Printf alike functions.
- Construct a []T slice from some T values without using the []T{...} form.
NOTE: SliceFrom(aSlice...) returns aSlice,
func TrackError ¶ added in v0.1.5
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.
func TrackErrorOf ¶ added in v0.1.5
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 ¶
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
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.
func TypeOf ¶
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 ¶
Value returns a reflect.Value which represents the value v, which may be either an non-interface value or interface value.
func WriteStringWithBuffer ¶
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
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
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 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 ¶
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 ¶
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()
type Ordered ¶
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 Signed ¶
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 ¶
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.
func (*WaitGroup) GoN ¶
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.