utils

package
v1.1.14 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2024 License: Apache-2.0 Imports: 45 Imported by: 6

Documentation

Index

Constants

View Source
const (
	UnmarshalTypeJson unmarshalType = "json"
	UnmarshalTypeYaml unmarshalType = "yaml"
	UnmarshalTypeToml unmarshalType = "toml"
)

Variables

View Source
var (
	// BytesBufferPool 64 is bytes.Buffer smallBufferSize, which is an initial allocation minimal capacity.
	BytesBufferPool = NewPool(
		func() *bytes.Buffer { return bytes.NewBuffer(make([]byte, 0, 64)) },
		PoolableEvictFunc(poolBytesBufferEvict),
	)
	BytesPool = NewPool(
		func() poolBytes { return make([]byte, 0, 64) },
		PoolableEvictFunc(poolBytesEvict),
	)
)
View Source
var (
	ErrEmptyArray = errors.New("empty array")
)
View Source
var (
	ErrOutOfRange = errors.New("out of range")
)
View Source
var LocalIP = &localIP{
	str: ClientIP(),
	bytes: func() []byte {
		reverse := func(bs []byte) {
			i, j := 0, len(bs)-1
			for i < j {
				bs[i], bs[j] = bs[j], bs[i]
				i++
				j--
			}
		}

		if ipAddr := ClientIP(); ipAddr != "" {
			realIP := []byte("000000000000")
			idx := 0
			for i := len(ipAddr) - 1; i >= 0; i-- {
				c := ipAddr[i]
				if c == '.' {
					idx = (((idx - 1) / 3) + 1) * 3
					continue
				}
				realIP[idx] = c
				idx++
			}
			reverse(realIP)
			return realIP
		}
		return []byte("000000000000")
	}(),
}

Functions

func AnyPtr

func AnyPtr[T any](s T) *T

func ApplyOptions

func ApplyOptions[T any](opts ...OptionExtender) (t *T)

func Catch

func Catch(fn any) (isPanic bool, err error)

func CheckIfAny

func CheckIfAny(fnList ...func() error) error

func ClientIP

func ClientIP() (ip string)

func CloseAnyway

func CloseAnyway[T any](closer T)

func ComparableToSortable

func ComparableToSortable[T comparable](s T) (d any)

ComparableToSortable convert generic type to sortable type

func CryptoRandom

func CryptoRandom(b []byte) (n int, err error)

func CryptoRandomBytes

func CryptoRandomBytes(size int) ([]byte, error)

func CryptoRandomLetterAndNumber

func CryptoRandomLetterAndNumber(n int) (string, error)

func CryptoRandomNumbers

func CryptoRandomNumbers(n int) (string, error)

func DecimalPlaces

func DecimalPlaces(num float64) int

func EmbedsType

func EmbedsType(i any, e reflect.Type) bool

EmbedsType Returns true if t embeds e or if any of the types embedded by t embed e. Forked from go.uber.org/dig@v1.16.1/inout.embedsType

func ErrIgnore

func ErrIgnore(src error, ignored ...error) (dst error)

func FlushAnyway

func FlushAnyway[T any](flusher T)

func FuzzyKeyword

func FuzzyKeyword(keyword string) []string

func GetCaller

func GetCaller(maximumCallerDepth int, opts ...OptionExtender) (frame *runtime.Frame)

GetCaller retrieves the name after stack skip

func GetCtxAny

func GetCtxAny[T any](ctx context.Context, key string, args ...T) (val T)

GetCtxAny with a default value

func GetFieldByTag

func GetFieldByTag(data any, tag, key string) (r reflect.Value, e error)

func GetFieldByTagWithKeys

func GetFieldByTagWithKeys(data any, tag string, keys []string) (r reflect.Value, e error)

func GetFieldTagValue

func GetFieldTagValue(data any, tag string, pattern *regexp.Regexp) (tagValue string, e error)

func GetFuncName

func GetFuncName(fn any) string

func GetGormColumnValue

func GetGormColumnValue(data any, column string) (columnVal reflect.Value, ok bool)

func GetTime

func GetTime(timestampMs int64) time.Time

GetTime 将毫秒级的时间戳转换成时间

func GetTimeStamp

func GetTimeStamp(t time.Time) int64

GetTimeStamp 将时间转换成毫秒级的时间戳

func HostIPInDocker

func HostIPInDocker() (ip string)

func IfAny

func IfAny(fnList ...func() bool)

func IgnoreEnumStringCase

func IgnoreEnumStringCase() enumStringOptFn

func IndirectType

func IndirectType(s reflect.Type) (d reflect.Type)

func IndirectValue

func IndirectValue(s reflect.Value) (d reflect.Value)

func IntNarrow

func IntNarrow(num int) (result any)

func IsBlank

func IsBlank(object any) bool

IsBlank gets whether the specified object is considered empty or not. fork from: github.com/stretchr/testify@v1.8.0/assert/assertions.go

func IsChannelClosed

func IsChannelClosed[T any](ch <-chan T) (data T, ok bool)

func IsInRange

func IsInRange[T constraint.Sortable](num, min, max T) bool

func IsStrBlank

func IsStrBlank(s string) bool

func IsStrNotBlank

func IsStrNotBlank(s string) bool

func IsStrPtrBlank

func IsStrPtrBlank(s *string) bool

func IsStrPtrNotBlank

func IsStrPtrNotBlank(s *string) bool

func IsValidTimestamp

func IsValidTimestamp(timeMS int64) bool

IsValidTimestamp 返回 false 表示无法对毫秒时间戳和 time.Time 进行精确转换

func LookupByFuzzyKeyword

func LookupByFuzzyKeyword[T any, F lookupByFuzzyKeywordFuncType[T]](lookup F, keyword string) (v T)

func LoopWithInterval

func LoopWithInterval(ctx context.Context, interval time.Duration,
	fn func() bool, opts ...OptionExtender) (err error)

LoopWithInterval Deprecated, try github.com/rican7/retry.Retry instead

func MapKeys

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

func MapMerge

func MapMerge[T comparable, K any](a, b map[T]K) (r map[T]K)

func MapSliceToMap

func MapSliceToMap[T comparable, K any](s []map[T]K) (d map[T]K)

func MapValues

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

func MapValuesByKeys

func MapValuesByKeys[T comparable, K any, TS ~[]T](m map[T]K, keys TS) (vals []K)

func Max

func Max[T constraint.Sortable](arr ...T) T

func Min

func Min[T constraint.Sortable](arr ...T) T

func Must

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

func MustJsonMarshal

func MustJsonMarshal(s any) []byte

func MustJsonMarshalString

func MustJsonMarshalString(s any) string

func MustJsonUnmarshal

func MustJsonUnmarshal[T any](s []byte) (t *T)

func MustOk

func MustOk[T any](out T, ok bool) T

func MustSuccess

func MustSuccess(err error)

func NewSafeRand

func NewSafeRand(seed int64) *rand.Rand

func NextJitterIntervalFunc

func NextJitterIntervalFunc(base, max time.Duration, ratio, exp float64, symmetric bool) func() time.Duration

NextJitterIntervalFunc generate a jitter and exponential power duration, inspired by net/http.(*Server).Shutdown

func NginxID

func NginxID() string

func ParseTag

func ParseTag(data any, opts ...OptionExtender) (err error)

func ParseVariadicFuncResult

func ParseVariadicFuncResult[T any](rs []reflect.Value, idx int) (t T)

func Random

func Random(b []byte, seed int64) (n int, err error)

func RandomLetterAndNumber

func RandomLetterAndNumber(n int) string

func RandomNumbers

func RandomNumbers(n int) string

func SetCtxAny

func SetCtxAny[T any](ctx context.Context, key string, val T) context.Context

SetCtxAny with any value

func ShortUUID

func ShortUUID() string

ShortUUID returns a new short UUID with base57

func SliceConvert

func SliceConvert(src any, dstType reflect.Type) any

SliceConvert >= go1.18 recommend to use SliceMapping

func SliceMapping

func SliceMapping[T, K any](s []T, mapFn func(t T) K) (d []K)

SliceMapping Mapping slice convert go1.18 version

func SliceRemove

func SliceRemove[T any, TS ~[]T](s TS, filter func(t T) bool) (d TS)

func SliceReverse

func SliceReverse[T any, TS ~[]T](s TS)

func SliceSplit added in v0.0.65

func SliceSplit[T any, TS ~[]T](arr TS, size int) []TS

SliceSplit Separate objects into several size

func SliceToMap

func SliceToMap[K comparable, V any](s []V, groupFn func(v V) K) (d map[K]V)

func Sort

func Sort[E any](data []E, cmp func(e1, e2 E) bool)

func SortStable

func SortStable[E any](data []E, cmp func(e1, e2 E) bool)

func SortableToGeneric

func SortableToGeneric[T, K constraint.Sortable](s T) (d K)

SortableToGeneric convert sortable type to generic type

func Timeout

func Timeout(timeout time.Duration, opts ...OptionExtender) bool

func TravelCtx

func TravelCtx(child context.Context, fn func(ctx context.Context) bool)

TravelCtx context parent traversal

func TraverseValue

func TraverseValue(data any, indirect bool, handler func(reflect.StructField, reflect.Value) (end, stepIn bool))

func ULID

func ULID() string

ULID returns a new ULID.

func UUID

func UUID() string

func UUID20

func UUID20() string

func UUID22

func UUID22() string

func UUID_

func UUID_() string

UUID_ nolint: revive // uuid without hyphen function issue

func UintNarrow

func UintNarrow(num uint) (result any)

func Unmarshal

func Unmarshal(s, d any, tag unmarshalType) (err error)

func UnsafeBytesToString

func UnsafeBytesToString(b []byte) string

UnsafeBytesToString converts byte slice to string without a memory allocation. Fork from github.com/gin-gonic/gin@v1.7.7/internal/bytesconv/bytesconv.go

func UnsafeStringToBytes

func UnsafeStringToBytes(s string) []byte

UnsafeStringToBytes converts string to byte slice without a memory allocation. Fork from github.com/gin-gonic/gin@v1.7.7/internal/bytesconv/bytesconv.go

func WrapFunc

func WrapFunc(fn any) func(...any)

func WrapFunc1

func WrapFunc1[T any](fn any) func(...any) T

func WrapFunc2

func WrapFunc2[T1, T2 any](fn any) func(...any) (T1, T2)

WrapFunc2 wrap a function with any number inputs and 2 generic type return, return nothing if function has 0 outputs return T1 if function only has 1 output return function first output and last output if function has more than 2 outputs

func WrapFunc3

func WrapFunc3[T1, T2, T3 any](fn any) func(...any) (T1, T2, T3)

func WrapFunc4

func WrapFunc4[T1, T2, T3, T4 any](fn any) func(...any) (T1, T2, T3, T4)

func WrapFunc5

func WrapFunc5[T1, T2, T3, T4, T5 any](fn any) func(...any) (T1, T2, T3, T4, T5)

func WrapFunc6

func WrapFunc6[T1, T2, T3, T4, T5, T6 any](fn any) func(...any) (T1, T2, T3, T4, T5, T6)

func WrapFunc7

func WrapFunc7[T1, T2, T3, T4, T5, T6, T7 any](fn any) func(...any) (T1, T2, T3, T4, T5, T6, T7)

func WrapFuncAny

func WrapFuncAny(fn any) func(...any) []any

Types

type Enumerable

type Enumerable[T comparable, TS ~[]T] interface {
	Enum(s string) TS
	String(k any) string
	IsValid(t T) bool
}

func NewEnumString

func NewEnumString[T comparable, TS ~[]T](mapping map[T]string, opts ...OptionExtender) Enumerable[T, TS]

type Error

type Error string

func (Error) Error

func (e Error) Error() string

type Heap

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

Heap base on generics to build a heap tree for any type

func NewHeap

func NewHeap[E any](t []E, cmp func(e1, e2 E) bool) *Heap[E]

NewHeap return an initial Heap pointer

func (*Heap[E]) Clone added in v1.1.11

func (h *Heap[E]) Clone() (r *Heap[E])

Clone heap

func (*Heap[E]) CmpFn added in v1.1.11

func (h *Heap[E]) CmpFn() func(e1, e2 E) bool

func (*Heap[E]) Copy

func (h *Heap[E]) Copy() (r *Heap[E])

Copy heap

func (*Heap[E]) Data added in v1.1.11

func (h *Heap[E]) Data() []E

func (*Heap[E]) Element

func (h *Heap[E]) Element(index int) (e E, err error)

func (*Heap[E]) Fix added in v1.1.11

func (h *Heap[E]) Fix(index int)

func (*Heap[E]) Init added in v1.1.11

func (h *Heap[E]) Init()

func (*Heap[E]) Len

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

func (*Heap[E]) Pop

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

Pop removes and returns the minimum element (according to Less) from the heap. The complexity is O(log n) where n = h.Len(). Pop is equivalent to Remove(h, 0).

func (*Heap[E]) Push

func (h *Heap[E]) Push(v E)

Push pushes the element x onto the heap. The complexity is O(log n) where n = h.Len().

func (*Heap[E]) Remove

func (h *Heap[E]) Remove(index int) E

Remove removes and returns the element at index i from the heap. The complexity is O(log n) where n = h.Len().

type InvalidUnmarshalError

type InvalidUnmarshalError struct {
	Type reflect.Type
}

An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)

func (*InvalidUnmarshalError) Error

func (e *InvalidUnmarshalError) Error() string

type JsonStringify

type JsonStringify[T any] struct {
	Value T
}

JsonStringify for k8s ConfigMap, Secret

func (*JsonStringify[T]) MarshalJSON

func (j *JsonStringify[T]) MarshalJSON() (output []byte, err error)

func (*JsonStringify[T]) UnmarshalJSON

func (j *JsonStringify[T]) UnmarshalJSON(input []byte) (err error)

type OptionExtender

type OptionExtender interface {
	// contains filtered or unexported methods
}

type OptionFunc

type OptionFunc[T any] func(*T)

func LoopJitterInterval

func LoopJitterInterval(base, max time.Duration, ratio, exp float64,
	symmetric bool) OptionFunc[loopWithIntervalOption]

LoopJitterInterval Deprecated, try github.com/rican7/retry.Retry instead

func LoopMaxTimes

func LoopMaxTimes(maxTimes uint) OptionFunc[loopWithIntervalOption]

LoopMaxTimes Deprecated, try github.com/rican7/retry.Retry instead

func ParseTagName

func ParseTagName(tag string) OptionFunc[parseTagOption]

func ParseTagOverwrite

func ParseTagOverwrite(overwrite bool) OptionFunc[parseTagOption]

func ParseTagUnmarshalType

func ParseTagUnmarshalType(unmarshalTag unmarshalType) OptionFunc[parseTagOption]

func PoolableEvictFunc

func PoolableEvictFunc[T any](fn func(obj T) bool) OptionFunc[poolableOption[T]]

func SkipGlobs

func SkipGlobs(patterns ...string) OptionFunc[getCallerOption]

func SkipKnownDepth

func SkipKnownDepth(minimumCallerDepth int) OptionFunc[getCallerOption]

func SkipRegexps

func SkipRegexps(patterns ...string) OptionFunc[getCallerOption]

func TimeoutWg

func TimeoutWg(wg *sync.WaitGroup) OptionFunc[timeoutOption]

type Poolable

type Poolable[T any] interface {
	Get(initialized any) (T, func())
	Put(obj T)
}

func NewPool

func NewPool[T any](newFn func() T, opts ...OptionExtender) Poolable[T]

type Set

type Set[T comparable] struct {
	// contains filtered or unexported fields
}

func NewSet

func NewSet[T comparable](arr ...T) (s *Set[T])

func (*Set[T]) Clone

func (s *Set[T]) Clone() (r *Set[T])

func (*Set[T]) Contains

func (s *Set[T]) Contains(val T) bool

func (*Set[T]) Copy added in v1.1.11

func (s *Set[T]) Copy() (r *Set[T])

func (*Set[T]) Equals

func (s *Set[T]) Equals(o *Set[T]) bool

func (*Set[T]) Filter

func (s *Set[T]) Filter(fn func(T) bool) *Set[T]

func (*Set[T]) Insert

func (s *Set[T]) Insert(val ...T) *Set[T]

func (*Set[T]) IntersectsWith

func (s *Set[T]) IntersectsWith(set *Set[T]) bool

func (*Set[T]) IsSubsetOf

func (s *Set[T]) IsSubsetOf(set *Set[T]) bool

func (*Set[T]) Items

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

func (*Set[T]) Reject

func (s *Set[T]) Reject(fn func(T) bool) *Set[T]

func (*Set[T]) Remove

func (s *Set[T]) Remove(val ...T) *Set[T]

func (*Set[T]) Size

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

Directories

Path Synopsis
Package clone provides functions to deep clone any Go data.
Package clone provides functions to deep clone any Go data.
dsl
Package sqlparser fork from github.com/longbridgeapp/sqlparser@v0.3.1
Package sqlparser fork from github.com/longbridgeapp/sqlparser@v0.3.1

Jump to

Keyboard shortcuts

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