util

package
v0.1.27 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2025 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	//lint:ignore U1000 ansi color code, keep it for future use
	ANSIRed   = "\033[1;31m"
	ANSIGreen = "\033[1;32m"
	ANSICyan  = "\033[1;36m"
	ANSIReset = "\033[0m"
)

https://stackoverflow.com/questions/8357203/is-it-possible-to-display-text-in-a-console-with-a-strike-through-effect https://en.wikipedia.org/wiki/ANSI_escape_code

View Source
const (
	// Default File Mode
	DefFileMode = 0666

	GbUnit uint64 = MbUnit * 1024
	MbUnit uint64 = KbUnit * 1024
	KbUnit uint64 = 1024
)
View Source
const (
	LoopbackLocalHost = "localhost"
	Loopback127       = "127.0.0.1"
	LocalIpAny        = "0.0.0.0"
)
View Source
const (
	ClassicDateTimeLocaleFormat = "2006/01/02 15:04:05 (MST)"
	ClassicDateTimeFormat       = "2006/01/02 15:04:05"
	StdDateTimeFormat           = "2006-01-02 15:04:05"
	StdDateTimeMilliFormat      = "2006-01-02 15:04:05.000"
	StdDateTimeLocaleFormat     = "2006-01-02 15:04:05 (MST)"
	SQLDateTimeFormat           = "2006-01-02 15:04:05.999999"
	SQLDateTimeFormatWithT      = "2006-01-02T15:04:05.999999"
	SQLDateFormat               = "2006-01-02"
)
View Source
const (
	BoolStrTrue  = "true"
	BoolStrFalse = "false"
)
View Source
const (
	DEFAULT_LEN = 35
)

Variables

View Source
var (
	PanicLog func(pat string, args ...any) = Printlnf
	DebugLog func(pat string, args ...any) = func(pat string, args ...any) {}
)
View Source
var CliErrLog func(pat string, args ...any) = Printlnf
View Source
var (
	ErrGetTimeout = errors.New("future.TimedGet timeout")
)

Functions

func AddETimeParseFormat added in v0.1.21

func AddETimeParseFormat(fmt ...string)

func AppendableFile

func AppendableFile(name string) (*os.File, error)

Create appendable file with 0666 permission.

func CamelCase

func CamelCase(s string) string

func CliRun

func CliRun(executable string, args ...string) (out []byte, err error)

CLI runs command.

If err is not nil, out may still contain output from the command.

func CliRunWithEnv added in v0.1.16

func CliRunWithEnv(dir string, env []string, executable string, args ...string) (out []byte, err error)

CLI runs command with env.

If err is not nil, out may still contain output from the command.

func CollectFields

func CollectFields(ptr any) []reflect.StructField

Get Fields of A Type

func CollectTypeFields

func CollectTypeFields(eleType reflect.Type) []reflect.StructField

Get Fields of A Type

func ContainsAnyStr added in v0.1.17

func ContainsAnyStr(s string, substrings ...string) bool

func CopyFilter

func CopyFilter[T any](l []T, f func(T) bool) []T

Filter slice value.

The original slice is not modified only copied.

func CpuProfileFunc added in v0.1.13

func CpuProfileFunc(file string, fu func()) error

func CsvReadAll added in v0.1.27

func CsvReadAll(reader io.Reader) ([][]string, error)

func CsvReader added in v0.1.27

func CsvReader(reader io.Reader) *csv.Reader

func DebugNamedPrintlnf added in v0.1.5

func DebugNamedPrintlnf(debug bool, pat string, p map[string]any)

func DebugPrintlnf added in v0.1.5

func DebugPrintlnf(debug bool, pat string, args ...any)

func Distinct

func Distinct(l []string) []string

Filter duplicate values

func ERand

func ERand(len int) string

Generate random string with high entrophy

func EqualAnyStr added in v0.1.17

func EqualAnyStr(s string, canditates ...string) bool

func EscapeString added in v0.1.13

func EscapeString(s string) string

Escape String

Acknowledgement: following code is copied from https://github.com/pingcap/tidb/blob/master/pkg/util/sqlescape/utils.go (Copyright 2021 PingCAP, Inc. Apache License)

func FastDistinct

func FastDistinct(l []string) []string

Filter duplicate values, faster but values are sorted, and the slice values are filtered in place.

func FileCutSuffix added in v0.1.27

func FileCutSuffix(name string, ext string) (string, bool)

func FileExists

func FileExists(path string) (bool, error)

Check if file exists

func FileHasSuffix added in v0.1.27

func FileHasSuffix(name string, ext string) bool

func Filter

func Filter[T any](l []T, f func(T) bool) []T

Filter slice values in place.

Be cautious that both slices are backed by the same array.

func FixedPoolFilterFunc added in v0.1.21

func FixedPoolFilterFunc[T any](filterFunc func(t T) (dropped bool)) func(*FixedPool[T])

func FmtFloat added in v0.1.3

func FmtFloat(f float64, width int, precision int) string

func FuncName

func FuncName(f any) string

Get name of func

func FuzzParseTime

func FuzzParseTime(formats []string, value string) (time.Time, error)

func FuzzParseTimeLoc added in v0.1.1

func FuzzParseTimeLoc(formats []string, value string, loc *time.Location) (time.Time, error)

func GenId

func GenId() (id string)

Generate Id

The id consists of [64 bits long] + [6 digits machine_code] The 64 bits long consists of: [sign bit (1 bit)] + [timestamp (49 bits, ~1487.583 years)] + [sequenceNo (14 bits, 0~16383)]

The max value of Long is 9223372036854775807, which is a string with 19 characters, so the generated id will be of at most 25 characters

This func is thread-safe

func GenIdP

func GenIdP(prefix string) (id string)

Generate Id with prefix.

The id consists of [64 bits long] + [6 digits machine_code].

The 64 bits long consists of: [sign bit (1 bit)] + [timestamp (49 bits, ~ 1487.583 years)] + [sequenceNo (14 bits, 0~16383)].

The max value of Long is 9223372036854775807, which is a string with 19 characters, so the generated id will be of at most 25 characters.

This func is thread-safe

func GenNo

func GenNo(prefix string) string

generate a random sequence number with specified prefix

func GenNoL

func GenNoL(prefix string, len int) string

generate a random sequence number with specified prefix

func GetLocalIPV4 added in v0.1.8

func GetLocalIPV4() string

Get local ipv4 address (excluding loopback address)

func HasPrefixIgnoreCase

func HasPrefixIgnoreCase(s string, prefix string) bool

Check if s has the prefix in a case-insensitive way.

func HasSuffixIgnoreCase

func HasSuffixIgnoreCase(s string, suffix string) bool

Check if s has the suffix in a case-insensitive way.

func IsBlankStr

func IsBlankStr(s string) bool

Check if the string is blank

func IsBool

func IsBool(boolStr string) bool

func IsFieldExposed

func IsFieldExposed(fieldName string) bool

Check if field is exposed

func IsLocalAddress added in v0.1.8

func IsLocalAddress(address string) bool

Check whether the address is local (localhost/127.0.0.1)

func IsTrue

func IsTrue(boolStr string) bool

func IsVoid

func IsVoid(t reflect.Type) bool

func LastNStr

func LastNStr(s string, n int) string

func MapFirst

func MapFirst[K comparable, V any](m map[K]V) V

Get first from map

func MapKeys

func MapKeys[T comparable, V any](m map[T]V) []T

Get keys from map

func MapTo added in v0.1.1

func MapTo[T any, V any](ts []T, mapFunc func(t T) V) []V

Map slice item to another.

func MapValues

func MapValues[K comparable, V any](m map[K]V) []V

Copy values of map

func MatchPath added in v0.1.14

func MatchPath(pattern, s string) bool

func MatchPathAny added in v0.1.19

func MatchPathAny(pattern []string, s string) bool

func MaxInt

func MaxInt(a int, b int) int

func MaxLenStr

func MaxLenStr(s string, max int) string

Substring such that len(s) <= max

func MemoryProfileFunc added in v0.1.13

func MemoryProfileFunc(file string, fu func()) error

func MergeSlice added in v0.1.1

func MergeSlice[K comparable, V any](vs []V, keyFunc func(v V) K) map[K][]V

Merge slice of items to a map.

func MergeStrPairs

func MergeStrPairs(p ...StrPair) map[string][]any

Merge StrPair into a map

func MinInt

func MinInt(a int, b int) int

func MkdirAll

func MkdirAll(path string) error

MkdirAll with 0755 perm.

func MkdirParentAll

func MkdirParentAll(path string) error

MkdirAll but only for the parent directory of the path, perm 0755 is used.

The path should always point to a specific file under some directories, as this method always attempts to extract parent dir of the file. It the path fails to fulfill this requirement, the output might be unexpected.

func Must added in v0.1.4

func Must(err error)

func MustGet added in v0.1.11

func MustGet[V any](v V, err error) V

func NamedPrintlnf added in v0.1.3

func NamedPrintlnf(pat string, p map[string]any)

func NamedSprintf added in v0.1.2

func NamedSprintf(pat string, p map[string]any) string

Format message using named args, e.g., '${startTime} ${message}'

func NamedSprintfv added in v0.1.13

func NamedSprintfv(pat string, v any) string

Format message using fields in struct, e.g., '${startTime} ${message}'

Equivalent to following code:

NamedSprintf(pat, ReflectGenMap(myStruct))

func NewSubmitAsyncFunc

func NewSubmitAsyncFunc[T any](pool *AsyncPool) func(task func() (T, error)) Future[T]

Create func that calls SubmitAsync(...) with the given pool.

func NewVar

func NewVar[T any]() T

func OpenFile

func OpenFile(name string, flag int) (*os.File, error)

Open file with 0666 permission.

func OpenRFile added in v0.1.27

func OpenRFile(name string) (*os.File, error)

Open readable file with 0666 permission.

func OpenRWFile added in v0.1.27

func OpenRWFile(name string, createIfAbsent bool) (*os.File, error)

Open readable & writable file with 0666 permission.

func PadNum

func PadNum(n int, digit int) string

func PadSpace added in v0.1.3

func PadSpace(n int, s string) string

func PadToken added in v0.1.17

func PadToken(n int, s string, tok string) string

func PanicSafeFunc added in v0.1.1

func PanicSafeFunc(op func()) func()

func ParseClassicDateTime added in v0.1.1

func ParseClassicDateTime(val string, loc *time.Location) (time.Time, error)

Parse classic datetime format using patterns: "2006-01-02 15:04:05", "2006/01/02 15:04:05".

func Pick

func Pick(set []rune) rune

pick random rune from the slice

func Printlnf

func Printlnf(pat string, args ...any)

func QuoteStr added in v0.1.19

func QuoteStr(s string) string

func RandAlpha

func RandAlpha(n int) string

Generate random alphabetic string with specified length

the generated string will contains [a-zA-Z]

func RandLowerAlpha

func RandLowerAlpha(n int) string

Generate random alphabetic, lowercase string with specified length

the generated string will contains [a-z]

func RandLowerAlphaNumeric

func RandLowerAlphaNumeric(n int) string

Generate random alphabetic, lowercase string with specified length

the generated string will contains [a-z0-9]

func RandLowerAlphaNumeric16

func RandLowerAlphaNumeric16() string

Same as RandLowerAlphaNumeric(16) but with less allocation.

func RandNum

func RandNum(n int) string

Generate random numeric string with specified length

the generated string will contains [0-9]

func RandOp added in v0.1.11

func RandOp(ops ...func())

invoke one of the funcs randomly

func RandPick added in v0.1.11

func RandPick[T any](s []T) T

func RandRune added in v0.1.6

func RandRune(n int, set []rune) string

generate randon str based on given length and given charset

func RandStr

func RandStr(n int) string

Generate random string with specified length

the generated string will contains [a-zA-Z0-9]

ERand() is preferred for higher entrophy

func RandUpperAlpha

func RandUpperAlpha(n int) string

Generate random alphabetic, uppercase string with specified length

the generated string will contains [A-Z]

func RandUpperAlphaNumeric

func RandUpperAlphaNumeric(n int) string

Generate random alphabetic, uppercase string with specified length

the generated string will contains [A-Z0-9]

func ReadFileAll

func ReadFileAll(path string) ([]byte, error)

Read all content from file.

func ReadWriteFile

func ReadWriteFile(name string) (*os.File, error)

Create readable & writable file with 0666 permission.

If file is missing, new empty file is created.

func ReflectFuncName added in v0.1.13

func ReflectFuncName(fun any) string

func ReflectGenMap added in v0.1.13

func ReflectGenMap(t any) map[string]any

Construct Struct/Interface/Pointer values to map[string]any.

This method doesn't convert recursively.

func SAddLineIndent added in v0.1.9

func SAddLineIndent(s string, indentChar string) string

func SaveTmpFile added in v0.1.1

func SaveTmpFile(tmpDir string, reader io.Reader) (string, error)

Save to temp file, returns temp file path or error.

func SetETimeMarshalFormat added in v0.1.19

func SetETimeMarshalFormat(fmt string)

func SetMachineCode

func SetMachineCode(code int) error

Overwrite the randomly generated machine code, machine code must be between 0 and 999999, at most 6 digits.

func SetToSlice

func SetToSlice[T comparable](s Set[T]) []T

Copy keys of set

func ShuffleRunes

func ShuffleRunes(letters []rune, times int) []rune

func ShuffleStr

func ShuffleStr(letters string, times int) string

func SliceCopy added in v0.1.6

func SliceCopy[T any](v []T) []T

func SliceFilterFirst

func SliceFilterFirst[T any](items []T, f func(T) bool) (T, bool)

Select one from the slice that matches the condition.

func SliceFirst added in v0.1.14

func SliceFirst[T any](v []T) (t T, ok bool)

func SliceGetOne

func SliceGetOne[T any](items []*T) *T

Select random one from the slice

func SliceRemove added in v0.1.6

func SliceRemove[T any](v []T, idx ...int) []T

func Spaces

func Spaces(count int) string

func SplitKV added in v0.1.5

func SplitKV(s string, token string) (string, string, bool)

Splist kv pair. Returns false if token is not found or key is absent.

func StrByteLen added in v0.1.14

func StrByteLen(s string) int

Get string's length in bytes

func StrMap

func StrMap[T any, V any](l []T, keyMapper func(T) string, valueMapper func(T) V) map[string]V

Build a map with string type key and any type of value

func StrSliceMap added in v0.1.26

func StrSliceMap[T any, V any](l []T, keyMapper func(T) string, valueMapper func(T) V) map[string][]V

Build a map with string type key and slice value of any type

func TPrintlnf added in v0.1.14

func TPrintlnf(pat string, args ...any)

func Tabs

func Tabs(count int) string

func TermOpenUrl

func TermOpenUrl(url string) error

func ToStr

func ToStr(v any) string

func TrimStrSlice added in v0.1.23

func TrimStrSlice(s []string)

func TypeName

func TypeName(t reflect.Type) string

func UnquoteStr added in v0.1.17

func UnquoteStr(s string) string

func UnsafeByt2Str

func UnsafeByt2Str(b []byte) string

Convert []byte to string without alloc.

Both the []byte and the string share the same memory.

Any modification on the original []byte is reflected on the returned string.

byt = []byte("abc")
s = UnsafeByt2Str(byt) // "abc" using the same memory
byt[0] = 'd' // modified in place at 0, also reflected on s ("dbc")

Tricks from https://github.com/valyala/fasthttp and https://go101.org/article/unsafe.html

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

func UnsafeStr2Byt

func UnsafeStr2Byt(s string) (b []byte)

Convert string to []byte without alloc.

Both the []byte and the string share the same memory.

The resulting []byte is not modifiable, program will panic if modified.

s := "abc"
byt := UnsafeStr2Byt(s) // "abc" but in []byte
byt[0] = 'd' // will panic

Tricks from https://github.com/valyala/fasthttp and https://go101.org/article/unsafe.html

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

func WalkTagShallow

func WalkTagShallow(ptr any, callbacks ...WalkTagCallback) error

Walk fields of *struct, won't go deeper even if the field is a struct.

func WeightedRandPick added in v0.1.11

func WeightedRandPick[T interface{ GetWeight() float64 }](s []T) T

Types

type AsyncPool

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

A long live, bounded pool of goroutines.

Use miso.NewAsyncPool to create a new pool.

AsyncPool internally maintains a task queue with limited size and limited number of workers. If the task queue is full, the caller of *AsyncPool.Go is blocked indefinitively.

func NewAsyncPool

func NewAsyncPool(maxTasks int, maxWorkers int) *AsyncPool

Create a bounded pool of goroutines.

The maxTasks determines the capacity of the task queues. If the task queue is full, the caller of *AsyncPool.Go is blocked.

The maxWorkers determines the max number of workers.

func NewCpuAsyncPool added in v0.1.11

func NewCpuAsyncPool() *AsyncPool

Create AsyncPool with number of workers equals to number of cpu cores and a task queue of size 500.

func NewIOAsyncPool added in v0.1.11

func NewIOAsyncPool() *AsyncPool

Create AsyncPool with number of workers equals to two times of the number of cpu cores and a task queue of size 500.

func (*AsyncPool) Go

func (p *AsyncPool) Go(f func())

Submit task to the pool.

If the task queue is full, the caller is blocked.

If the pool is closed, caller will execute the submitted task directly.

func (*AsyncPool) Stop added in v0.1.10

func (p *AsyncPool) Stop()

Stop the pool.

Once the pool is stopped, new tasks submitted are executed directly by the caller.

func (*AsyncPool) StopAndWait added in v0.1.10

func (p *AsyncPool) StopAndWait()

Stop the pool and wait until existing workers drain all the remaining tasks.

Once the pool is stopped, new tasks submitted are executed directly by the caller.

type AwaitFutures

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

AwaitFutures represent tasks that are submitted to the pool asynchronously whose results are awaited together.

AwaitFutures should only be used once for the same group of tasks.

Use miso.NewAwaitFutures() to create one.

func NewAwaitFutures

func NewAwaitFutures[T any](pool *AsyncPool) *AwaitFutures[T]

Create new AwaitFutures for a group of tasks.

*AsyncPool is optional, provide nil if not needed.

func (*AwaitFutures[T]) Await

func (a *AwaitFutures[T]) Await() []Future[T]

Await results of all tasks.

func (*AwaitFutures[T]) AwaitAnyErr added in v0.1.2

func (a *AwaitFutures[T]) AwaitAnyErr() error

Await results of all tasks and return any error that is found in the task Futures.

func (*AwaitFutures[T]) SubmitAsync

func (a *AwaitFutures[T]) SubmitAsync(task func() (T, error))

Submit task to AwaitFutures.

type BatchTask added in v0.1.16

type BatchTask[T any, V any] struct {
	// contains filtered or unexported fields
}

func NewBatchTask added in v0.1.16

func NewBatchTask[T any, V any](parallel int, bufferSize int, consumer func(T) (V, error)) *BatchTask[T, V]

Create a batch of concurrent task for one time use.

func (*BatchTask[T, V]) Close added in v0.1.16

func (b *BatchTask[T, V]) Close()

Close underlying pipeline channel without waiting.

func (*BatchTask[T, V]) Generate added in v0.1.16

func (b *BatchTask[T, V]) Generate(task T)

Generate task.

func (*BatchTask[T, V]) Wait added in v0.1.16

func (b *BatchTask[T, V]) Wait() []BatchTaskResult[V]

Wait until all generated tasks are completed and close pipeline channel.

type BatchTaskResult added in v0.1.19

type BatchTaskResult[V any] struct {
	Result V
	Err    error
}

type ByteBufPool added in v0.1.2

type ByteBufPool struct {
	MaxCap int // default max cap is 4096 bytes.
	// contains filtered or unexported fields
}

func NewByteBufferPool added in v0.1.2

func NewByteBufferPool(initCap int) *ByteBufPool

func (*ByteBufPool) Get added in v0.1.2

func (b *ByteBufPool) Get() *bytes.Buffer

func (*ByteBufPool) Put added in v0.1.2

func (b *ByteBufPool) Put(buf *bytes.Buffer)

type Consumer added in v0.1.4

type Consumer[T any] func(t T) error

Consume t

type Converter added in v0.1.4

type Converter[T any, V any] func(t T) (V, error)

Convert t to v

type ETime

type ETime struct {
	time.Time
}

ETime enhanced wrapper of time.Time.

This type implements sql.Scanner and driver.Valuer, and thus can be safely used in GORM just like time.Time. It also implements json/encoding Marshaler and Unmarshaler to support json marshalling (in forms of epoch milliseconds 'by default').

In previous releases, ETime was a type alias to time.Time. Since v0.1.2, ETime embeds time.Time to access all of it's methods.

To cast from time.Time to ETime, use ToETime() method. To cast from ETime to time.Time, use ETime.ToTime() method.

func MayParseETime added in v0.1.25

func MayParseETime(v any) ETime

func Now

func Now() ETime

func ParseETime added in v0.1.24

func ParseETime(v any) (ETime, error)

func ToETime added in v0.1.2

func ToETime(t time.Time) ETime

func (ETime) Add added in v0.1.1

func (t ETime) Add(d time.Duration) ETime

func (ETime) AddDate added in v0.1.2

func (t ETime) AddDate(years int, months int, days int) ETime

func (ETime) After added in v0.1.2

func (t ETime) After(u ETime) bool

func (ETime) Before added in v0.1.2

func (t ETime) Before(u ETime) bool

func (ETime) EndOfDay added in v0.1.19

func (t ETime) EndOfDay() ETime

func (ETime) FormatClassic

func (t ETime) FormatClassic() string

func (ETime) FormatClassicLocale

func (t ETime) FormatClassicLocale() string

func (ETime) FormatDate added in v0.1.1

func (t ETime) FormatDate() string

func (ETime) FormatStd added in v0.1.14

func (t ETime) FormatStd() string

func (ETime) FormatStdLocale added in v0.1.14

func (t ETime) FormatStdLocale() string

func (ETime) FormatStdMilli added in v0.1.14

func (t ETime) FormatStdMilli() string

func (ETime) MarshalJSON

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

Implements encoding/json Marshaler

func (*ETime) Scan

func (et *ETime) Scan(value interface{}) error

Implements sql.Scanner in database/sql.

func (ETime) StartOfDay added in v0.1.24

func (t ETime) StartOfDay() ETime

func (ETime) String

func (t ETime) String() string

func (ETime) Sub added in v0.1.2

func (t ETime) Sub(u ETime) time.Duration

func (ETime) ToTime

func (t ETime) ToTime() time.Time

func (*ETime) UnmarshalJSON

func (t *ETime) UnmarshalJSON(b []byte) error

Implements encoding/json Unmarshaler.

func (ETime) Value

func (t ETime) Value() (driver.Value, error)

Implements driver.Valuer in database/sql.

type FixedPool added in v0.1.21

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

func NewFixedPool added in v0.1.21

func NewFixedPool[T any](cap int, options ...func(*FixedPool[T])) *FixedPool[T]

func (*FixedPool[T]) Pop added in v0.1.21

func (r *FixedPool[T]) Pop() (T, bool)

func (*FixedPool[T]) Push added in v0.1.21

func (r *FixedPool[T]) Push(t T)

func (*FixedPool[T]) TryPop added in v0.1.21

func (r *FixedPool[T]) TryPop() (T, bool)

func (*FixedPool[T]) TryPush added in v0.1.21

func (r *FixedPool[T]) TryPush(t T) bool

type ForEachField

type ForEachField func(index int, field reflect.StructField) (breakIteration bool)

type Future

type Future[T any] interface {

	// Get result without timeout.
	Get() (T, error)

	// Get result with timeout, returns ErrGetTimeout if timeout exceeded.
	TimedGet(timeout int) (T, error)

	// Then callback to be invoked when the Future is completed.
	//
	// Then callback should only be set once for every Future.
	Then(tf func(T, error))
}

Result of a asynchronous task.

func NewCompletedFuture added in v0.1.25

func NewCompletedFuture[T any](t T, err error) Future[T]

func RunAsync

func RunAsync[T any](task func() (T, error)) Future[T]

Create Future, once the future is created, it starts running on a new goroutine.

func SubmitAsync

func SubmitAsync[T any](pool *AsyncPool, task func() (T, error)) Future[T]

Create Future, once the future is created, it starts running on a saperate goroutine from the pool.

type Heap added in v0.1.14

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

func NewHeap added in v0.1.14

func NewHeap[T any](cap int, lessFunc func(iv T, jv T) bool) *Heap[T]

func (*Heap[T]) Len added in v0.1.14

func (h *Heap[T]) Len() int

func (*Heap[T]) Peek added in v0.1.14

func (h *Heap[T]) Peek() T

func (*Heap[T]) Pop added in v0.1.14

func (h *Heap[T]) Pop() T

func (*Heap[T]) Push added in v0.1.14

func (h *Heap[T]) Push(t T)

type IndWritef

type IndWritef = func(indentCnt int, pat string, args ...any)

func NewIndWritef

func NewIndWritef(indentStr string) (*strings.Builder, IndWritef)

Wrap strings.Builder, and returns a Writef func that automatically adds indentation.

type IndentWriter

type IndentWriter struct {
	*strings.Builder
	// contains filtered or unexported fields
}

func NewIndentWriter

func NewIndentWriter(indentStr string) IndentWriter

func (*IndentWriter) DecrIndent added in v0.1.4

func (i *IndentWriter) DecrIndent()

func (*IndentWriter) IncrIndent added in v0.1.4

func (i *IndentWriter) IncrIndent()

func (*IndentWriter) NoIndWritef added in v0.1.4

func (i *IndentWriter) NoIndWritef(pat string, args ...any) *IndentWriter

Writef without indentation and with line break.

func (*IndentWriter) NoLbWritef added in v0.1.4

func (i *IndentWriter) NoLbWritef(pat string, args ...any) *IndentWriter

Writef with indentation and without line break.

func (*IndentWriter) NoLbWritefWhen added in v0.1.21

func (i *IndentWriter) NoLbWritefWhen(condition bool, pat string, args ...any) *IndentWriter

NoLbWritef(..) when condition is true else Writef(..).

func (*IndentWriter) SetIndent added in v0.1.4

func (i *IndentWriter) SetIndent(ind int)

func (*IndentWriter) StepIn

func (i *IndentWriter) StepIn(f func(iw *IndentWriter)) *IndentWriter

func (*IndentWriter) Writef

func (i *IndentWriter) Writef(pat string, args ...any) *IndentWriter

type Introspector

type Introspector struct {
	Type   reflect.Type
	Fields []reflect.StructField
	// contains filtered or unexported fields
}

func Introspect

func Introspect(ptr any) Introspector

Create new Introspector

func (*Introspector) Field

func (it *Introspector) Field(fieldName string) (field reflect.StructField, isFieldFound bool)

Get field by name

func (*Introspector) FieldAt

func (it *Introspector) FieldAt(idx int) (field reflect.StructField)

Get field at index

func (*Introspector) FieldIdx

func (it *Introspector) FieldIdx(fieldName string) (index int, isFieldFound bool)

Get field index

func (*Introspector) IterFields

func (it *Introspector) IterFields(forEach ForEachField)

Iterate fields

func (*Introspector) Tag

func (it *Introspector) Tag(fieldName string, tagName string) (tag string, isFieldFound bool)

Get tag by of field

func (*Introspector) TagRetriever

func (it *Introspector) TagRetriever(fieldName string) (t TagRetriever, isFieldFound bool)

Get tag retriever for a field

type Opt

type Opt[T any] struct {
	Val       T
	IsPresent bool
}

Optional value, useful for passing zero value struct

func EmptyOpt

func EmptyOpt[T any]() Opt[T]

Empty Optional

func OptWith

func OptWith[T any](t T) Opt[T]

Optional with value present

func (*Opt[T]) Get

func (o *Opt[T]) Get() (T, bool)

func (*Opt[T]) IfPresent

func (o *Opt[T]) IfPresent(call func(t T))

type Pair

type Pair struct {
	Left  any
	Right any
}

Pair data structure

type Peek added in v0.1.4

type Peek[T any] func(t T)

Peek t

type Predicate added in v0.1.4

type Predicate[T any] func(t T) bool

Predicate based on t

type Queue added in v0.1.12

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

func NewQueue added in v0.1.12

func NewQueue[T any]() *Queue[T]

func (*Queue[T]) Len added in v0.1.12

func (q *Queue[T]) Len() int

func (*Queue[T]) PopBack added in v0.1.12

func (q *Queue[T]) PopBack() T

func (*Queue[T]) PopFront added in v0.1.12

func (q *Queue[T]) PopFront() T

func (*Queue[T]) PushBack added in v0.1.12

func (q *Queue[T]) PushBack(t T)

func (*Queue[T]) PushFront added in v0.1.12

func (q *Queue[T]) PushFront(t T)

type RWMap

type RWMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Map with sync.RWMutex embeded.

func NewRWMap

func NewRWMap[K comparable, V any]() *RWMap[K, V]

Create new RWMap

func (*RWMap[K, V]) Clear added in v0.1.12

func (r *RWMap[K, V]) Clear()

func (*RWMap[K, V]) Del

func (r *RWMap[K, V]) Del(k K)

func (*RWMap[K, V]) Get

func (r *RWMap[K, V]) Get(k K) (V, bool)

func (*RWMap[K, V]) GetElse

func (r *RWMap[K, V]) GetElse(k K, elseFunc func(k K) V) (V, bool)

func (*RWMap[K, V]) Keys

func (r *RWMap[K, V]) Keys() []K

func (*RWMap[K, V]) Put

func (r *RWMap[K, V]) Put(k K, v V)

func (*RWMap[K, V]) PutIfAbsent added in v0.1.12

func (r *RWMap[K, V]) PutIfAbsent(k K, f func() V)

type SLPinter

type SLPinter struct {
	*strings.Builder
	LineSuffix string
	LinePrefix string
}

func (*SLPinter) Printf

func (s *SLPinter) Printf(st string, args ...any)

func (*SLPinter) Println added in v0.1.11

func (s *SLPinter) Println(st string)

func (*SLPinter) Printlnf

func (s *SLPinter) Printlnf(st string, args ...any)

type Set

type Set[T comparable] struct {
	// Keys in Set
	Keys map[T]Void
}

Set data structure

It's internally backed by a Map.

To create a new Set, use NewSet() func.

func NewSet

func NewSet[T comparable](keys ...T) Set[T]

Create new Set

func NewSetFromSlice added in v0.1.13

func NewSetFromSlice[T comparable](ts []T) Set[T]

Create new Set from slice

func (*Set[T]) Add

func (s *Set[T]) Add(key T) bool

Add key to set, return true if the key wasn't present previously

func (*Set[T]) AddAll

func (s *Set[T]) AddAll(keys []T)

Add keys to set

func (*Set[T]) AddThen

func (s *Set[T]) AddThen(key T) *Set[T]

Add key to set (same as Add, but used for method chaining)

func (*Set[T]) CopyKeys

func (s *Set[T]) CopyKeys() []T

Copy keys in set

func (*Set[T]) Del added in v0.1.1

func (s *Set[T]) Del(key T)

Delete key.

func (*Set[T]) Has

func (s *Set[T]) Has(key T) bool

Test whether the key is in the set

func (*Set[T]) IsEmpty

func (s *Set[T]) IsEmpty() bool

Check if the Set is empty

func (*Set[T]) Size

func (s *Set[T]) Size() int

Get the size of the Set

func (Set[T]) String

func (s Set[T]) String() string

To string

type SignalOnce added in v0.1.13

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

func NewSignalOnce added in v0.1.13

func NewSignalOnce() *SignalOnce

func (*SignalOnce) Closed added in v0.1.13

func (s *SignalOnce) Closed() bool

func (*SignalOnce) Notify added in v0.1.13

func (s *SignalOnce) Notify()

func (*SignalOnce) TimedWait added in v0.1.13

func (s *SignalOnce) TimedWait(timeout time.Duration) (isTimeout bool)

func (*SignalOnce) Wait added in v0.1.13

func (s *SignalOnce) Wait()

type Stack added in v0.1.3

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

func NewStack added in v0.1.3

func NewStack[T any](cap int) *Stack[T]

func (*Stack[T]) Empty added in v0.1.3

func (s *Stack[T]) Empty() bool

func (*Stack[T]) ForEach added in v0.1.3

func (s *Stack[T]) ForEach(f func(v T) bool)

Iterate Stack from top to bottom, iter func can return false to break the loop.

func (*Stack[T]) Len added in v0.1.12

func (s *Stack[T]) Len() int

func (*Stack[T]) Peek added in v0.1.3

func (s *Stack[T]) Peek() (T, bool)

func (*Stack[T]) Pop added in v0.1.3

func (s *Stack[T]) Pop() (T, bool)

func (*Stack[T]) Push added in v0.1.3

func (s *Stack[T]) Push(v T)

func (*Stack[T]) Slice added in v0.1.3

func (s *Stack[T]) Slice() []T

func (Stack[T]) String added in v0.1.3

func (s Stack[T]) String() string

type StrPair

type StrPair struct {
	Left  string
	Right any
}

String-based Pair data structure

type StrRWMap added in v0.1.25

type StrRWMap[V any] struct {
	// contains filtered or unexported fields
}

func NewStrRWMap added in v0.1.25

func NewStrRWMap[V any]() *StrRWMap[V]

Create new sharded, concurrent access StrRWMap.

func (*StrRWMap[V]) Del added in v0.1.25

func (r *StrRWMap[V]) Del(k string)

func (*StrRWMap[V]) Get added in v0.1.25

func (r *StrRWMap[V]) Get(k string) (V, bool)

func (*StrRWMap[V]) GetElse added in v0.1.25

func (r *StrRWMap[V]) GetElse(k string, elseFunc func(k string) V) (V, bool)

func (*StrRWMap[V]) Put added in v0.1.25

func (r *StrRWMap[V]) Put(k string, v V)

func (*StrRWMap[V]) PutIfAbsent added in v0.1.25

func (r *StrRWMap[V]) PutIfAbsent(k string, f func() V)

type StrSliceFlag

type StrSliceFlag []string

func FlagStrSlice

func FlagStrSlice(name string, usage string) *StrSliceFlag

func (*StrSliceFlag) Set

func (s *StrSliceFlag) Set(t string) error

func (*StrSliceFlag) String

func (s *StrSliceFlag) String() string

type Supplier added in v0.1.4

type Supplier[T any] func() T

Supplier of T

type TagRetriever

type TagRetriever func(tagName string) string

type Transform added in v0.1.4

type Transform[T any] func(t T) T

Transform t to another t

type TransformAsync added in v0.1.16

type TransformAsync[T any] func(t T) Future[T]

Transform t to another t

type Void

type Void struct{}

Empty Struct

type WalkTagCallback

type WalkTagCallback struct {
	Tag      string
	OnWalked func(tagVal string, fieldVal reflect.Value, fieldType reflect.StructField) error
}

type WeightedItem added in v0.1.11

type WeightedItem[T any] struct {
	Value  T
	Weight float64
}

func (WeightedItem[T]) GetWeight added in v0.1.11

func (w WeightedItem[T]) GetWeight() float64

Jump to

Keyboard shortcuts

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