Documentation ¶
Index ¶
- Constants
- Variables
- func AppendableFile(name string) (*os.File, error)
- func CamelCase(s string) string
- func CliRun(ex string, args ...string) ([]byte, error)
- func CollectFields(ptr any) []reflect.StructField
- func CollectTypeFields(eleType reflect.Type) []reflect.StructField
- func CopyFilter[T any](l []T, f func(T) bool) []T
- func DebugNamedPrintlnf(debug bool, pat string, p map[string]any)
- func DebugPrintlnf(debug bool, pat string, args ...any)
- func Distinct(l []string) []string
- func ERand(len int) string
- func FastDistinct(l []string) []string
- func FileExists(path string) (bool, error)
- func Filter[T any](l []T, f func(T) bool) []T
- func FmtFloat(f float64, width int, precision int) string
- func FuncName(f any) string
- func FuzzParseTime(formats []string, value string) (time.Time, error)
- func FuzzParseTimeLoc(formats []string, value string, loc *time.Location) (time.Time, error)
- func GenId() (id string)
- func GenIdP(prefix string) (id string)
- func GenNo(prefix string) string
- func GenNoL(prefix string, len int) string
- func GetLocalIPV4() string
- func HasPrefixIgnoreCase(s string, prefix string) bool
- func HasSuffixIgnoreCase(s string, suffix string) bool
- func IsBlankStr(s string) bool
- func IsBool(boolStr string) bool
- func IsFieldExposed(fieldName string) bool
- func IsLocalAddress(address string) bool
- func IsTrue(boolStr string) bool
- func IsVoid(t reflect.Type) bool
- func LastNStr(s string, n int) string
- func MapFirst[K comparable, V any](m map[K]V) V
- func MapKeys[T comparable, V any](m map[T]V) []T
- func MapTo[T any, V any](ts []T, mapFunc func(t T) V) []V
- func MapValues[K comparable, V any](m map[K]V) []V
- func MaxInt(a int, b int) int
- func MaxLenStr(s string, max int) string
- func MergeSlice[K comparable, V any](vs []V, keyFunc func(v V) K) map[K][]V
- func MergeStrPairs(p ...StrPair) map[string][]any
- func MinInt(a int, b int) int
- func MkdirAll(path string) error
- func MkdirParentAll(path string) error
- func Must(err error)
- func MustGet[V any](v V, err error) V
- func NamedPrintlnf(pat string, p map[string]any)
- func NamedSprintf(pat string, p map[string]any) string
- func NewSubmitAsyncFunc[T any](pool *AsyncPool) func(task func() (T, error)) Future[T]
- func NewVar[T any]() T
- func OpenFile(name string, flag int) (*os.File, error)
- func PadNum(n int, digit int) string
- func PadSpace(n int, s string) string
- func PanicSafeFunc(op func()) func()
- func ParseClassicDateTime(val string, loc *time.Location) (time.Time, error)
- func Pick(set []rune) rune
- func Printlnf(pat string, args ...any)
- func RandAlpha(n int) string
- func RandLowerAlpha(n int) string
- func RandLowerAlphaNumeric(n int) string
- func RandLowerAlphaNumeric16() string
- func RandNum(n int) string
- func RandOp(ops ...func())
- func RandPick[T any](s []T) T
- func RandRune(n int, set []rune) string
- func RandStr(n int) string
- func RandUpperAlpha(n int) string
- func RandUpperAlphaNumeric(n int) string
- func ReadFileAll(path string) ([]byte, error)
- func ReadWriteFile(name string) (*os.File, error)
- func SAddLineIndent(s string, indentChar string) string
- func SaveTmpFile(tmpDir string, reader io.Reader) (string, error)
- func SetMachineCode(code int) error
- func SetToSlice[T comparable](s Set[T]) []T
- func ShuffleRunes(letters []rune, times int) []rune
- func ShuffleStr(letters string, times int) string
- func SliceCopy[T any](v []T) []T
- func SliceFilterFirst[T any](items []T, f func(T) bool) (T, bool)
- func SliceGetOne[T any](items []*T) *T
- func SliceRemove[T any](v []T, idx ...int) []T
- func Spaces(count int) string
- func SplitKV(s string, token string) (string, string, bool)
- func StrMap[T any, V any](l []T, keyMapper func(T) string, valueMapper func(T) V) map[string]V
- func Tabs(count int) string
- func TermOpenUrl(url string) error
- func ToStr(v any) string
- func TypeName(t reflect.Type) string
- func UnsafeByt2Str(b []byte) string
- func UnsafeStr2Byt(s string) (b []byte)
- func WalkTagShallow(ptr any, callbacks ...WalkTagCallback) error
- func WeightedRandPick[T interface{ ... }](s []T) T
- type AsyncPool
- type AwaitFutures
- type ByteBufPool
- type Consumer
- type Converter
- type ETime
- func (t ETime) Add(d time.Duration) ETime
- func (t ETime) AddDate(years int, months int, days int) ETime
- func (t ETime) After(u ETime) bool
- func (t ETime) Before(u ETime) bool
- func (t ETime) FormatClassic() string
- func (t ETime) FormatClassicLocale() string
- func (t ETime) FormatDate() string
- func (t ETime) MarshalJSON() ([]byte, error)
- func (et *ETime) Scan(value interface{}) error
- func (t ETime) Sub(u ETime) time.Duration
- func (t ETime) ToTime() time.Time
- func (t *ETime) UnmarshalJSON(b []byte) error
- func (t ETime) Value() (driver.Value, error)
- type ForEachField
- type Future
- type IndWritef
- type IndentWriter
- func (i *IndentWriter) DecrIndent()
- func (i *IndentWriter) IncrIndent()
- func (i *IndentWriter) NoIndWritef(pat string, args ...any) *IndentWriter
- func (i *IndentWriter) NoLbWritef(pat string, args ...any) *IndentWriter
- func (i *IndentWriter) SetIndent(ind int)
- func (i *IndentWriter) StepIn(f func(iw *IndentWriter)) *IndentWriter
- func (i *IndentWriter) Writef(pat string, args ...any) *IndentWriter
- type Introspector
- func (it *Introspector) Field(fieldName string) (field reflect.StructField, isFieldFound bool)
- func (it *Introspector) FieldAt(idx int) (field reflect.StructField)
- func (it *Introspector) FieldIdx(fieldName string) (index int, isFieldFound bool)
- func (it *Introspector) IterFields(forEach ForEachField)
- func (it *Introspector) Tag(fieldName string, tagName string) (tag string, isFieldFound bool)
- func (it *Introspector) TagRetriever(fieldName string) (t TagRetriever, isFieldFound bool)
- type Opt
- type Pair
- type Peek
- type Predicate
- type RWMap
- type SLPinter
- type Set
- type Stack
- type StrPair
- type StrSliceFlag
- type Supplier
- type TagRetriever
- type Transform
- type Void
- type WalkTagCallback
- type WeightedItem
Constants ¶
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
const ( LoopbackLocalHost = "localhost" Loopback127 = "127.0.0.1" LocalIpAny = "0.0.0.0" )
const ( BoolStrTrue = "true" BoolStrFalse = "false" )
const (
DEFAULT_LEN = 35
)
const (
// Default File Mode
DefFileMode = 0666
)
const (
SQLDateTimeFormat = "2006/01/02 15:04:05"
)
Variables ¶
var (
ErrGetTimeout = errors.New("future.TimedGet timeout")
)
Functions ¶
func AppendableFile ¶
Create appendable file with 0666 permission.
func CollectTypeFields ¶
func CollectTypeFields(eleType reflect.Type) []reflect.StructField
Get Fields of A Type
func DebugNamedPrintlnf ¶ added in v0.1.5
func DebugPrintlnf ¶ added in v0.1.5
func FastDistinct ¶
Filter duplicate values, faster but values are sorted, and the slice values are filtered in place.
func Filter ¶
Filter slice values in place.
Be cautious that both slices are backed by the same array.
func FuzzParseTimeLoc ¶ added in v0.1.1
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 ¶
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 GetLocalIPV4 ¶ added in v0.1.8
func GetLocalIPV4() string
Get local ipv4 address (excluding loopback address)
func HasPrefixIgnoreCase ¶
Check if s has the prefix in a case-insensitive way.
func HasSuffixIgnoreCase ¶
Check if s has the suffix in a case-insensitive way.
func IsLocalAddress ¶ added in v0.1.8
Check whether the address is local (localhost/127.0.0.1)
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 MkdirParentAll ¶
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 NamedPrintlnf ¶ added in v0.1.3
func NamedSprintf ¶ added in v0.1.2
Format message using named args.
Equivalent to NamedFmt(pat).Sprintf(p).
e.g., '${startTime} ${message}'
func NewSubmitAsyncFunc ¶
Create func that calls SubmitAsync(...) with the given pool.
func PanicSafeFunc ¶ added in v0.1.1
func PanicSafeFunc(op func()) func()
func ParseClassicDateTime ¶ added in v0.1.1
Parse classic datetime format using patterns: "2006-01-02 15:04:05", "2006/01/02 15:04:05".
func RandAlpha ¶
Generate random alphabetic string with specified length
the generated string will contains [a-zA-Z]
func RandLowerAlpha ¶
Generate random alphabetic, lowercase string with specified length
the generated string will contains [a-z]
func RandLowerAlphaNumeric ¶
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 ¶
Generate random numeric string with specified length
the generated string will contains [0-9]
func RandStr ¶
Generate random string with specified length
the generated string will contains [a-zA-Z0-9]
ERand() is preferred for higher entrophy
func RandUpperAlpha ¶
Generate random alphabetic, uppercase string with specified length
the generated string will contains [A-Z]
func RandUpperAlphaNumeric ¶
Generate random alphabetic, uppercase string with specified length
the generated string will contains [A-Z0-9]
func ReadWriteFile ¶
Create readable & writable file with 0666 permission.
func SAddLineIndent ¶ added in v0.1.9
func SaveTmpFile ¶ added in v0.1.1
Save to temp file, returns temp file path or error.
func SetMachineCode ¶
Overwrite the randomly generated machine code, machine code must be between 0 and 999999, at most 6 digits.
func ShuffleRunes ¶
func ShuffleStr ¶
func SliceFilterFirst ¶
Select one from the slice that matches the condition.
func SliceRemove ¶ added in v0.1.6
func SplitKV ¶ added in v0.1.5
Splist kv pair. Returns false if token is not found or key is absent.
func TermOpenUrl ¶
func UnsafeByt2Str ¶
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.
func UnsafeStr2Byt ¶
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.
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 ¶
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 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 ETime ¶
ETime, same as time.Time but is serialized/deserialized in forms of unix epoch milliseconds.
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).
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 (ETime) FormatClassic ¶
func (ETime) FormatClassicLocale ¶
func (ETime) FormatDate ¶ added in v0.1.1
func (ETime) MarshalJSON ¶
Implements encoding/json Marshaler
func (*ETime) UnmarshalJSON ¶
Implements encoding/json Unmarshaler.
type ForEachField ¶
type ForEachField func(index int, field reflect.StructField) (breakIteration bool)
type Future ¶
type IndentWriter ¶
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) 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 (*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 RWMap ¶
type RWMap[K comparable, V any] struct { // contains filtered or unexported fields }
Map with sync.RWMutex embeded.
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.
type Stack ¶ added in v0.1.3
type Stack[T any] struct { // contains filtered or unexported fields }
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 TagRetriever ¶
type WalkTagCallback ¶
type WeightedItem ¶ added in v0.1.11
func (WeightedItem[T]) GetWeight ¶ added in v0.1.11
func (w WeightedItem[T]) GetWeight() float64