easy

package
v2.7.2 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2023 License: MIT Imports: 24 Imported by: 3

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Caller

func Caller(skip int) (name, file string, line int)

Caller returns function name, filename, and the line number of the caller. The argument skip is the number of stack frames to ascend, with 0 identifying the caller of Caller.

func CallerName

func CallerName() string

CallerName returns the function name of the direct caller. This is a convenient wrapper around Caller.

func Clip

func Clip[S ~[]E, E any](s S) S

Clip removes unused capacity from the slice, returning s[:len(s):len(s)].

func Concat

func Concat[S ~[]E, E any](slices ...S) S

Concat concatenates given slices into a single slice.

func ConvInts

func ConvInts[T1, T2 constraints.Integer](slice []T1) []T2

ConvInts converts slice of integers of type T1 to a new slice of integers of type T2. The input data must be convertable to T2.

func Copy added in v2.7.0

func Copy[S ~[]E, E any](s S, optionalCap ...int) S

Copy copies a slice to be a new one. optionalCap optionally specifies the capacity of the new slice.

func Count

func Count[S ~[]E, E any](predicate func(elem E) bool, slices ...S) int

Count iterates slices, it calls predicate(elem) for each elem in the slices and returns the count of elements for which predicate(elem) returns true.

func Diff

func Diff[S ~[]E, E comparable](slice S, others ...S) S

Diff allocates and returns a new slice which contains the values which present in slice, but not present in others.

If length of slice is zero, it returns nil.

func DiffInplace

func DiffInplace[S ~[]E, E comparable](slice S, others ...S) S

DiffInplace returns a slice which contains the values which present in slice, but not present in others. It does not allocate new memory, but modifies slice in-place.

If length of slice is zero, it returns nil.

func DiffInt32s deprecated

func DiffInt32s(a []int32, b []int32) []int32

DiffInt32s returns a new int32 slice containing the values which present in slice a but not present in slice b.

Deprecated: the generic function Diff is favored over this.

func DiffInt64s deprecated

func DiffInt64s(a []int64, b []int64) []int64

DiffInt64s returns a new int64 slice containing the values which present in slice a but not present in slice b.

Deprecated: the generic function Diff is favored over this.

func DiffMaps

func DiffMaps[M ~map[K]V, K comparable, V any](m M, others ...M) M

DiffMaps returns a new map which contains elements which present in m, but not present in others.

If length of m is zero, it returns nil.

func DiffMapsInplace

func DiffMapsInplace[M ~map[K]V, K comparable, V any](m M, others ...M) M

DiffMapsInplace removes elements that present in others from m.

func DiffStrings deprecated

func DiffStrings(a []string, b []string) []string

DiffStrings returns a new string slice containing the values which present in slice a but not present in slice b.

Deprecated: the generic function Diff is favored over this.

func DoRequest deprecated

func DoRequest(req *Request) (header http.Header, respContent []byte, status int, err error)

DoRequest is a convenient function to send request and control redirect and debug options.

Deprecated: this function has been moved to sub-package ezhttp, please use ezhttp.Do instead of this.

func EnsureError

func EnsureError(v any) error

EnsureError ensures the given value (should be non-nil) is an error. If it's not an error, `fmt.Errorf("%v", v)` will be used to convert it.

func Filter

func Filter[S ~[]E, E any](predicate func(i int, elem E) bool, slices ...S) S

Filter iterates the given slices, it calls predicate(i, elem) for each elem in the slices and returns a new slice of elements for which predicate(i, elem) returns true.

func FilterInt32s deprecated

func FilterInt32s(slice []int32, predicate func(i int) bool) []int32

FilterInt32s iterates the given slice, it calls predicate(i) for i in range [0, n), where n is the length of the slice. It returns a new slice of elements for which predicate(i) returns true.

Deprecated: the generic function Filter is favored over this.

func FilterInt64s deprecated

func FilterInt64s(slice []int64, predicate func(i int) bool) []int64

FilterInt64s iterates the given slice, it calls predicate(i) for i in range [0, n), where n is the length of the slice. It returns a new slice of elements for which predicate(i) returns true.

Deprecated: the generic function Filter is favored over this.

func FilterMaps

func FilterMaps[M ~map[K]V, K comparable, V any](predicate func(k K, v V) bool, maps ...M) M

FilterMaps iterates the given maps, it calls predicate(k, v) for each key value in the maps and returns a new map of key value pairs for which predicate(k, v) returns true.

func FilterStrings deprecated

func FilterStrings(slice []string, predicate func(i int) bool) []string

FilterStrings iterates the given slice, it calls predicate(i) for i in range [0, n), where n is the length of the slice. It returns a new slice of elements for which predicate(i) returns true.

Deprecated: the generic function Filter is favored over this.

func FormatInts

func FormatInts[T constraints.Integer](slice []T, base int) []string

FormatInts converts slice of integers to a slice of strings. It returns nil if there is no element in given slice.

func GetOutboundIP

func GetOutboundIP() (net.IP, error)

GetOutboundIP returns the preferred outbound ip of this machine.

func Glob added in v2.1.0

func Glob(pattern string) (matches []string, err error)

Glob adds double-star support to the std library's path/filepath.Glob. It's useful when your pattern might have double-stars.

func IdentifyPanic

func IdentifyPanic() string

IdentifyPanic reports the panic location when a panic happens. It should be called directly after `recover()`, not wrapped by another function, else it returns incorrect location. Use IdentifyPanicSkip for wrapping.

func IdentifyPanicSkip added in v2.3.5

func IdentifyPanicSkip(skip int) string

IdentifyPanicSkip is similar to IdentifyPanic, except that it accepts a param skip for wrapping usecase.

func InInt32s

func InInt32s(slice []int32, elem int32) bool

InInt32s tells whether the int32 value elem is in the slice.

func InInt64s

func InInt64s(slice []int64, elem int64) bool

InInt64s tells whether the int64 value elem is in the slice.

func InSlice added in v2.5.1

func InSlice[E comparable](slice []E, elem E) bool

InSlice tells whether the value elem is in the slice.

func InStrings

func InStrings(slice []string, elem string) bool

InStrings tells whether the string value elem is in the slice.

func Index

func Index[S ~[]E, E comparable](s S, v E) int

Index returns the index of the first occurrence of v in s, or -1 if not present.

func IndexFunc

func IndexFunc[E any](slice []E, predicate func(i int) bool) int

IndexFunc iterates the given slice, it calls predicate(i) for i in range [0, n) where n is the length of the slice. When predicate(i) returns true, it stops and returns the index i.

func IntKeys deprecated

func IntKeys[M ~map[K]V, K constraints.Integer, V any](m M) (keys []int64)

IntKeys returns a int64 slice containing all the keys present in the map, in an indeterminate order.

Deprecated: the generic function Keys is favored over this.

func IntValues deprecated

func IntValues[M ~map[K]V, K comparable, V constraints.Integer](m M) (values []int64)

IntValues returns a int64 slice containing all the values present in the map, in an indeterminate order.

Deprecated: the generic function Values is favored over this.

func JSON

func JSON(v any) string

JSON converts given object to a json string, it never returns error. The marshalling method used here does not escape HTML characters, and map keys are sorted, which helps human reading.

func Keys

func Keys[M ~map[K]V, K comparable, V any](m M, filter ...func(K, V) bool) []K

Keys returns the keys of the map m. The keys will be in an indeterminate order.

Optionally, a filter function can be given to make it returning only keys for which filter(k, v) returns true.

func LastIndex added in v2.3.2

func LastIndex[S ~[]E, E comparable](s S, v E) int

LastIndex returns the index of the last instance of v in s, or -1 if v is not present in s.

func LastIndexFunc

func LastIndexFunc[E any](slice []E, predicate func(i int) bool) int

LastIndexFunc iterates the given slice, it calls predicate(i) for i in range [0, n) in descending order, where n is the length of the slice. When predicate(i) returns true, it stops and returns the index i.

func LazyJSON added in v2.1.0

func LazyJSON(v any) fmt.Stringer

LazyJSON returns a lazy object which wraps v, and it marshals v to JSON when it's String method is called. This helps to avoid unnecessary marshaling in some use case, such as leveled logging.

func MapKeys deprecated

func MapKeys[M ~map[K]V, K comparable, V any](m M) any

MapKeys returns the keys of the map m. The keys will be in an indeterminate order.

Deprecated: the generic function Keys is favored over this.

func MapValues deprecated

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

MapValues returns the values of the map m. The values will be in an indeterminate order.

Deprecated: the generic function Values is favored over this.

func MatchGroups

func MatchGroups(re *regexp.Regexp, str []byte) map[string][]byte

MatchGroups returns the matched named capturing groups. A returned value of nil indicates no match.

func MatchStringGroups

func MatchStringGroups(re *regexp.Regexp, str string) map[string]string

MatchStringGroups returns the matched named capturing groups. A returned value of nil indicates no match.

func MergeMaps

func MergeMaps[M ~map[K]V, K comparable, V any](maps ...M) M

MergeMaps returns a new map containing all key values present in given maps.

func MergeMapsTo

func MergeMapsTo[M ~map[K]V, K comparable, V any](dst M, others ...M) M

MergeMapsTo adds key values present in others to the dst map. If dst is a nil map, it creates a new map and returns it.

func MergeMapsToPtr added in v2.5.0

func MergeMapsToPtr[M ~map[K]V, K comparable, V any](dst *M, others ...M)

MergeMapsToPtr is similar to MergeMapsTo, but it accepts a pointer as dst, if dst points to a nil map, it creates a new map and assigns it to dst. If dst is a nil pointer, it panics.

func PanicOnError

func PanicOnError(args ...any)

PanicOnError fires a panic if any of the args is non-nil error.

func ParseHTMLTemplates

func ParseHTMLTemplates(rootDir string, rePattern string, funcMap ht.FuncMap) (*ht.Template, error)

ParseHTMLTemplates parses files under `rootDir` which matches the regular expression `rePattern`. Optionally a `funcMap` can be specified to use with the parsed templates.

The returned Template holds the parsed templates under the root directory, template can be retrieved using Template.Lookup(name), where name is the file path relative to rootDir, without leading "./".

func ParseInts

func ParseInts[T constraints.Integer](slice []string, base int) []T

ParseInts converts slice of strings to a slice of integers. It returns nil if there is no element in given slice.

Note that if the input data contains non-integer strings, the errors returned from strconv.ParseInt are ignored, and the returned slice will have less elements than the input slice.

func ParseTextTemplates

func ParseTextTemplates(rootDir string, rePattern string, funcMap tt.FuncMap) (*tt.Template, error)

ParseTextTemplates parses files under `rootDir` which matches the regular expression `rePattern`. Optionally a `funcMap` can be specified to use with the parsed templates.

The returned Template holds the parsed templates under the root directory, template can be retrieved using Template.Lookup(name), where name is the file path relative to rootDir, without leading "./".

func Pretty

func Pretty(v any) string

Pretty converts given object to a pretty formatted json string. If the input is a json string, it will be formatted using json.Indent with four space characters as indent.

func Pretty2

func Pretty2(v any) string

Pretty2 is like Pretty, but it uses two space characters as indent, instead of four.

func Recover

func Recover(f func(ctx context.Context, panicErr *PanicError)) func(ctx context.Context)

Recover returns a function which can be used to recover panics. It accepts a panicErr handler function which may be used to log the panic error and context information.

Note that the returned function should not be wrapped by another function, instead it should be called directly by the `defer` statement, else it won't work as you may expect.

func Repeat

func Repeat[S ~[]E, E any](s S, count int) S

Repeat returns a new slice consisting of count copies of the slice s.

It panics if count is zero or negative or if the result of (len(s) * count) overflows.

func Reverse

func Reverse[S ~[]E, E any](s S, inplace bool) S

Reverse returns a slice of the elements in reversed order. When inplace is true, it does not allocate new memory, but the slice is reversed in place.

func ReverseInt32s deprecated

func ReverseInt32s(slice []int32, inplace bool) []int32

ReverseInt32s returns a new slice of the elements in reversed order.

When inplace is true, the slice is reversed in place, it does not create a new slice, but returns the original slice with reversed order.

Deprecated: the generic function Reverse is favored over this.

func ReverseInt64s deprecated

func ReverseInt64s(slice []int64, inplace bool) []int64

ReverseInt64s returns a new slice of the elements in reversed order.

When inplace is true, the slice is reversed in place, it does not create a new slice, but returns the original slice with reversed order.

Deprecated: the generic function Reverse is favored over this.

func ReverseStrings deprecated

func ReverseStrings(slice []string, inplace bool) []string

ReverseStrings returns a new slice of the elements in reversed order.

When inplace is true, the slice is reversed in place, it does not create a new slice, but returns the original slice with reversed order.

Deprecated: the generic function Reverse is favored over this.

func Safe

func Safe(f func()) func() error

Safe returns an wrapped function with panic recover.

Note that if panic happens, the wrapped function does not log messages, instead it will be returned as a `*PanicError`, the caller take responsibility to log the panic messages.

func Safe1

func Safe1(f func() error) func() error

Safe1 returns an wrapped function with panic recover.

Note that if panic or error happens, the wrapped function does not log messages, instead it will be returned as an error, the caller take responsibility to log the panic or error messages.

func SetDefault

func SetDefault(dst any, value ...any)

SetDefault checks whether dst points to a zero value, if yes, it sets the first non-zero value to dst. dst must be a pointer to same type as value, else it panics.

func SingleJoin

func SingleJoin(sep string, text ...string) string

SingleJoin joins the given text segments using sep. No matter whether a segment begins or ends with sep or not, it guarantees that only one sep appears between two segments.

func SlashJoin

func SlashJoin(path ...string) string

SlashJoin joins the given path segments using "/". No matter whether a segment begins or ends with "/" or not, it guarantees that only one "/" appears between two segments.

func Sort

func Sort[S ~[]E, E constraints.Ordered](s S) S

Sort sorts the given slice ascending and returns it.

func SortDesc

func SortDesc[S ~[]E, E constraints.Ordered](s S) S

SortDesc sorts the given slice descending and returns it.

func Split

func Split[S ~[]E, E any](slice S, batch int) []S

Split splits a large slice []T to batches, it returns a slice of type [][]T whose elements are sub slices of slice.

func SplitInt32s

func SplitInt32s(slice []int32, batch int) [][]int32

SplitInt32s splits a large int32 slice to batches.

func SplitInt64s

func SplitInt64s(slice []int64, batch int) [][]int64

SplitInt64s splits a large int64 slice to batches.

func SplitMap added in v2.3.5

func SplitMap[M ~map[K]V, K comparable, V any](m M, batchSize int) []M

SplitMap splits a large map to batches, it returns a slice of type []M whose elements are subset of the given map.

func SplitSlice deprecated

func SplitSlice[S ~[]E, E any](slice S, batch int) any

SplitSlice splits a large slice []T to batches, it returns a slice of type [][]T whose elements are sub slices of slice.

Deprecated: the generic function Split is favored over this.

func SplitStrings

func SplitStrings(slice []string, batch int) [][]string

SplitStrings splits a large string slice to batches.

func StringKeys deprecated

func StringKeys[M ~map[K]V, K ~string, V any](m M) (keys []string)

StringKeys returns a string slice containing all the keys present in the map, in an indeterminate order.

Deprecated: the generic function Keys is favored over this.

func StringValues deprecated

func StringValues[M ~map[K]V, K comparable, V ~string](m M) (values []string)

StringValues returns a string slice containing all the values present in the map, in an indeterminate order.

Deprecated: the generic function Values is favored over this.

func Sum

func Sum[T constraints.Integer](slice []T) int64

Sum returns the sum value of the elements in the given slice.

func SumFloat added in v2.4.0

func SumFloat[T constraints.RealNumber](slice []T) float64

SumFloat returns the sum value of the elements in the given slice, as a float64 value.

func ToBoolMap added in v2.3.2

func ToBoolMap[S ~[]E, E comparable](slice S) map[E]bool

ToBoolMap converts the given slice to a hash set, using elements from the slice as keys and true as values.

func ToInterfaceSlice

func ToInterfaceSlice[S ~[]E, E any](slice S) []any

ToInterfaceSlice returns a []interface{} containing elements from slice.

func ToMap

func ToMap[S ~[]E, E any, K comparable, V any](slice S, f func(E) (K, V)) map[K]V

ToMap converts the given slice to a map, it calls f for each element in slice to get key values to construct the returned map.

func Unique

func Unique[S ~[]E, E comparable](s S, inplace bool) S

Unique returns a slice containing the elements of the given slice in same order, but removes duplicate values. When inplace is true, it does not allocate new memory, the unique values will be written to the input slice from the beginning.

Given different input, the duplication rate may be varying, for large input, this function does not assume any specific workload type, it allocates initial memory of size `len(s)/2`, thus for slice that most elements are duplicate, it allocates memory more than need, but for slice that no value is duplicate, it triggers memory allocation more than once. For large slice in performance critical use-case, user is recommended to write a custom function that is fine-tuned for specific workload to get the best performance.

func UniqueFunc added in v2.4.1

func UniqueFunc[S ~[]E, E any, C comparable](s S, inplace bool, f func(E) C) S

UniqueFunc returns a slice containing the elements of the given slice in same order, but removes deduplicate values, it calls f for each element and uses the returned value to check duplication. When inplace is true, it does not allocate new memory, the unique values will be written to the input slice from the beginning.

Given different input, the duplication rate may be varying, for large input, this function does not assume any specific workload type, it allocates initial memory of size `len(s)/2`, thus for slice that most elements are duplicate, it allocates memory more than need, but for slice that no value is duplicate, it triggers memory allocation more than once. For large slice in performance critical use-case, user is recommended to write a custom function that is fine-tuned for specific workload to get the best performance.

func UniqueInt32s deprecated

func UniqueInt32s(slice []int32, inplace bool) []int32

UniqueInt32s returns a new slice containing the elements of the given slice in same order, but filter out duplicate values.

When inplace is true, it does not create a new slice, the unique values will be written to the input slice from the beginning.

Deprecated: the generic function Unique is favored over this.

func UniqueInt64s deprecated

func UniqueInt64s(slice []int64, inplace bool) []int64

UniqueInt64s returns a new slice containing the elements of the given slice in same order, but filter out duplicate values.

When inplace is true, it does not create a new slice, the unique values will be written to the input slice from the beginning.

Deprecated: the generic function Unique is favored over this.

func UniqueStrings deprecated

func UniqueStrings(slice []string, inplace bool) []string

UniqueStrings returns a new slice containing the elements of the given slice in same order, but filter out duplicate values.

When inplace is true, it does not create a new slice, the unique values will be written to the input slice from the beginning.

Deprecated: the generic function Unique is favored over this.

func Values

func Values[M ~map[K]V, K comparable, V any](m M, filter ...func(K, V) bool) []V

Values returns the values of the map m. The values will be in an indeterminate order.

Optionally, a filter function can be given to make it returning only values for which filter(k, v) returns true.

Types

type IJ

type IJ struct{ I, J int }

IJ represents a batch index of i, j.

func SplitBatch

func SplitBatch(total, batch int) []IJ

SplitBatch splits a large number to batch, it's mainly designed to help operations with large slice, such as inserting lots of records into database, or logging lots of identifiers, etc.

type Map deprecated

type Map = ezmap.Map

Map is a map of string key and any value. It provides many useful methods to work with map[string]any.

Deprecated: this type has been moved to sub-package ezmap, please use ezmap.Map directly, this alias name will be removed in future releases.

func NewMap deprecated

func NewMap() Map

NewMap returns a new initialized Map.

Deprecated: please use ezmap.NewMap directly, this alias name will be removed in future releases.

type PanicError

type PanicError struct {
	Exception  any
	Location   string
	Stacktrace []byte
}

PanicError represents an captured panic error.

func (*PanicError) Error

func (p *PanicError) Error() string

func (*PanicError) Format

func (p *PanicError) Format(f fmt.State, c rune)

type Request deprecated

type Request = ezhttp.Request

Request represents a request and options to send with the Do function.

Deprecated: this type has been moved to sub-package ezhttp, please use ezhttp.Request instead of this.

type SafeMap deprecated

type SafeMap = ezmap.SafeMap

SafeMap wraps Map with a RWMutex, user can acquire the lock before accessing to the map to get concurrent safety.

Deprecated: this type has been moved to sub-package ezmap, please use ezmap.SafeMap directly, this alias name will be removed in future releases.

func NewSafeMap deprecated

func NewSafeMap() *SafeMap

NewSafeMap returns a new initialized SafeMap.

Deprecated: please use ezmap.NewSafeMap directly, this alias name will be removed in future releases.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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