util

package
v0.1.0-beta.4 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2024 License: Apache-2.0 Imports: 23 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 (
	BoolStrTrue  = "true"
	BoolStrFalse = "false"
)
View Source
const (
	DEFAULT_LEN = 35
)
View Source
const (
	// Default File Mode
	DefFileMode = 0666
)

Variables

View Source
var (
	ErrGetTimeout = errors.New("future.TimedGet timeout")
)

Functions

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(ex string, args ...string) ([]byte, error)

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 CopyFilter

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

Filter slice value, the original slice is copied before filtering.

func DecodeJson

func DecodeJson(reader io.Reader, ptr any) error

Decode JSON using jsoniter.

func Distinct

func Distinct(l []string) []string

Filter duplicate values

func ERand

func ERand(len int) string

Generate random string with high entrophy

func EncodeJson

func EncodeJson(writer io.Writer, body any) error

Encode JSON using jsoniter.

func FastDistinct

func FastDistinct(l []string) []string

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

func FileExists

func FileExists(path string) (bool, error)

Check if file exists

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 FuncName

func FuncName(f any) string

Get name of func

func FuzzParseTime

func FuzzParseTime(formats []string, value string) (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 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 IsTrue

func IsTrue(boolStr string) bool

func IsVoid

func IsVoid(t reflect.Type) bool

func LastNStr

func LastNStr(s string, n int) string

func LowercaseNamingStrategy

func LowercaseNamingStrategy(name string) string

Change first rune to lower case.

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 MapValues

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

Copy values of map

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 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 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 PadNum

func PadNum(n int, digit int) string

func ParseJson

func ParseJson(body []byte, ptr any) error

Parse JSON using jsoniter.

func Pick

func Pick(set []rune) rune

pick random rune from the slice

func Printlnf

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

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 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.

func SWriteJson

func SWriteJson(body any) (string, error)

Write JSON as string using jsoniter.

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 SliceFilterFirst

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

Select one from the slice that matches the condition.

func SliceGetOne

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

Select random one from the slice

func SliceMap

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

Map slice item to another.

func Spaces

func Spaces(count int) string

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 Tabs

func Tabs(count int) string

func TermOpenUrl

func TermOpenUrl(url string) error

func ToStr

func ToStr(v any) string

func TypeName

func TypeName(t reflect.Type) 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.

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.

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 WriteJson

func WriteJson(body any) ([]byte, error)

Write JSON using jsoniter.

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 (*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, return ErrAsyncPoolClosed.

type AwaitFutures

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

AwaitFutures represent multiple tasks that will be submitted to the pool asynchronously whose results will be awaited together.

AwaitFutures should only be used once everytime it's needed.

Use miso.NewAwaitFutures() to create one.

func NewAwaitFutures

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

func (*AwaitFutures[T]) Await

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

func (*AwaitFutures[T]) SubmitAsync

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

type ETime

type ETime time.Time

EpochTime, same as time.Time but will be serialized/deserialized as epoch milliseconds

This type can be safely used in GORM just like time.Time

func Now

func Now() ETime

func (ETime) FormatClassic

func (t ETime) FormatClassic() string

func (ETime) FormatClassicLocale

func (t ETime) FormatClassicLocale() string

func (ETime) MarshalJSON

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

func (*ETime) Scan

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

Implements sql.Scanner in database/sql.

func (ETime) String

func (t ETime) String() string

func (ETime) ToTime

func (t ETime) ToTime() time.Time

func (ETime) UnixMilli

func (t ETime) UnixMilli() int64

func (*ETime) UnmarshalJSON

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

implements decorder.Unmarshaler in encoding/json.

func (ETime) Value

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

Implements driver.Valuer in database/sql.

type ForEachField

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

type Future

type Future[T any] interface {
	Get() (T, error)
	TimedGet(timeout int) (T, error)
}

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 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) 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 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]) 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)

type SLPinter

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

func (*SLPinter) Printf

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

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]() Set[T]

Create new Set

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]) 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 StrPair

type StrPair struct {
	Left  string
	Right any
}

String-based Pair data structure

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 TagRetriever func(tagName string) string

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
}

Jump to

Keyboard shortcuts

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