gox

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: MIT Imports: 16 Imported by: 0

README

GoX - Go Extended Library

Go package extending the standard library of utilities with additional useful types and functions.

Installation

go get -u github.com/maple-tech/gox

Documentation

Overview

Package Gox provides useful utilities to extend the standard Go library.

Index

Constants

This section is empty.

Variables

View Source
var (
	INT_SIZE  = unsafe.Sizeof(int(0))
	UINT_SIZE = unsafe.Sizeof(uint(0))

	MIN_INT   int   = -1 << (INT_SIZE - 1)
	MIN_INT8  int8  = -1 << 7
	MIN_INT16 int16 = -1 << 15
	MIN_INT32 int32 = -1 << 31
	MIN_INT64 int64 = -1 << 63

	MIN_FLOAT32 float32 = -1 << 31
	MIN_FLOAT64 float64 = -1 << 63

	MAX_INT   int   = 1<<(INT_SIZE-1) - 1
	MAX_INT8  int8  = 1<<7 - 1
	MAX_INT16 int16 = 1<<15 - 1
	MAX_INT32 int32 = 1<<31 - 1
	MAX_INT64 int64 = 1<<63 - 1

	MAX_UINT   uint   = 1<<(UINT_SIZE-1) - 1
	MAX_UINT8  uint8  = 1<<7 - 1
	MAX_UINT16 uint16 = 1<<15 - 1
	MAX_UINT32 uint32 = 1<<31 - 1
	MAX_UINT64 uint64 = 1<<63 - 1

	MAX_FLOAT32 float32 = 1<<31 - 1
	MAX_FLOAT64 float64 = 1<<63 - 1
)
View Source
var JSONMarshaler = json.Marshal

Provides a way to declare the JSON marshaling function for the entire library. It defaults to the STD json.Marshal.

View Source
var JSONUnmarshaler = json.Unmarshal

Provides a way to declare the JSON unmarshal-ing function for the entire library. it defaults to the STD json.Unmarshal.

View Source
var TimeZero = time.Time{}

TimeZero is a zero-value time.Time object, which should be epoch start.

Functions

func After

func After(str, sub string) string

AfterRune returns everything after the last instance of the given substring. If the rune does not exist, the string is returned unchanged.

func AllMatchNil

func AllMatchNil(opts ...any) bool

AllMatchNil returns true if the nil-ability of all the given variadic arguments matches. Basically this is a way to say "if any of these are not nil, they must all be not nil", and the inverse of that statement, "if any of these are nil, they must all be nil".

func AllNil

func AllNil(opts ...any) bool

AllNil returns true if all the variadic arguments are nil.

func AllNotNil

func AllNotNil(opts ...any) bool

AllNotNil returns true if all the variadic arguments are NOT nil.

func AllOptionalAndValid

func AllOptionalAndValid(objs ...Validable) bool

AllOptionalAndValid runs OptionalAndValid on variadic arguments to check that all objects are either [Valid] or nil.

func AllPresentAndValid

func AllPresentAndValid(objs ...Validable) bool

AllPresentAndValid runs PresentAndValid on variadic arguments to check that all objects are not-nil and pass the [Valid] check.

func AnyNil

func AnyNil(opts ...any) bool

AnyNil returns true if any of the variadic arguments is nil

func AnyNotNil

func AnyNotNil(opts ...any) bool

AnyNotNil returns true if any item in the variadic arguments is NOT nil.

func CopyMap

func CopyMap[Key comparable, Value any](target map[Key]Value) (ret map[Key]Value)

CopyMap deeply copies a given map by reconstructing it over iteration.

func CopySlice

func CopySlice[Type any](slice []Type) []Type

CopySlice returns a copy of the given slice

func FilterSlice

func FilterSlice[Type any](slice []Type, matcher func(v Type) bool) (ret []Type)

FilterSlice returns a new slice by running a matcher on all values in the provided slice. If the matcher returns true, it is added to the new return slice.

func FlattenMap

func FlattenMap[Key comparable, Value any](target map[Key]Value) (ret []any)

FlattenMap takes a map and turns it into a slice by laying out keys and values in order. Due to generic limitations it returns as any.

func ForceCast

func ForceCast[Type any](value any) Type

ForceCast is a DANGEROUS function. It uses unsafe to force cast the incoming value to the provided generic one. Very bad, no good, last resort.

func IsPrimitive

func IsPrimitive(typ reflect.Type) bool

func JoinMaps

func JoinMaps[Key comparable, Value any](maps ...map[Key]Value) (ret map[Key]Value)

JoinMaps takes a variadic amount of maps and joins them into a new one. They are processed in order, and any conflicting keys are overridden.

func JoinSlices

func JoinSlices[Value any](slices ...[]Value) (ret []Value)

JoinSlices combines all the values in each slice together.

func MakeAny

func MakeAny[T any]() T

MakeAny takes a generic argument and makes one, it does this by dereferencing the "new" results using the type.

func MapKeys

func MapKeys[Key comparable, Value any](target map[Key]Value) (ret []Key)

MapKeys extracts all the keys of a map as a slice

func MapValues

func MapValues[Key comparable, Value any](target map[Key]Value) (ret []Value)

MapValues extracts all the values of a map as a slice

func MatchLTreeSegments

func MatchLTreeSegments(ltree []string, query []string) bool

MatchLTreeSegments checks if the given L-Tree segments match against the given query segments. This is a low-level function for custom iterators.

func Max

func Max[Type Number](vals ...Type) Type

func MaxValue

func MaxValue[Type Number]() Type

MaxValue returns the maximum value for the given numeric type, this is the largest the memory will allow.

func Min

func Min[Type Number](vals ...Type) Type

func MinValue

func MinValue[Type Number]() Type

MinValue returns the minimum value for the given numeric type, this is the smallest the memory will allow.

func MustAssert

func MustAssert[T any](obj any) T

MustAssert runs the assertion operation on the given object and panics if the results are false.

func NumberMatcher

func NumberMatcher[T Number](test T) func(v T) bool

func OptionalAndValid

func OptionalAndValid(obj Validable) bool

OptionalAndValid returns true if the given object is nil, if it is not it returns the [Valid] results.

func PeekSlice

func PeekSlice[Type any](slice []Type, count int) []Type

PeekSlice safely returns the [count] of items at the end of the array without modifying the original. The returned slice is a copy from the original and should not be tied by reference to the original.

func PeekSliceOldest

func PeekSliceOldest[Type any](slice []Type, count int) []Type

PeekSliceOldest safely returns the [count] of items at the beginning of the slice without modifying the original. The returned slice is a copy from the original and should not be tied by reference to the original.

func PopMultipleFromSlice

func PopMultipleFromSlice[Type any](slice []Type, count int) (remaining []Type, elements []Type)

func PopSlice

func PopSlice[Type any](slice []Type) (remaining []Type, element Type)

PopSlice removes the last element in the slice and returns it. If the slice is empty, it returns a zero value.

func PresentAndValid

func PresentAndValid(obj Validable) bool

PresentAndValid returns true if the given object is not-nil and passes the [Valid] check.

func ProcessVar

func ProcessVar[Type Primitive](name string, defValue Type) Type

ProcessVar is a self-initializing variable which looks for it's value in multiple places at the time of instantiation. In other words, it's for those cases where you want to have over-writable variables on startup such as ENV, arguments, default, etc.

Order of operations for finding the value is: - Default Value - Environment variable - Command line argument

func RandomCode

func RandomCode(n uint8) string

RandomCode returns a randomly generated Base62 code which includes only alpha-numeric characters. It uses the crypto random reader.

Note: It uses a modulus operator so the resulting characters may not be weighted perfectly flat (gaussian). But for low-security purposes this is probably fine.

func RandomUpperCode

func RandomUpperCode(n uint8) string

RandomUpperCode returns a randomly generated code using digits and upper-case latin characters. It uses the crypto random reader.

Note: It uses a modulus operator so the resulting characters may not be weighted perfectly flat (gaussian). But for low-security purposes this is probably fine.

func ResizeSlice

func ResizeSlice[Type any](slice []Type, capacity int) []Type

func SetProcessVarEnvPrefix

func SetProcessVarEnvPrefix(str string)

func ShiftMultipleFromSlice

func ShiftMultipleFromSlice[Type any](slice []Type, count int) (remaining []Type, elements []Type)

ShiftMultipleFromSlice removes the given [count] of elements from the front of the slice and returns them. It also returns the modified slice of the remaining elements. If the slice was empty, it returns an empty slice.

func ShiftSlice

func ShiftSlice[Type any](slice []Type) (remaining []Type, element Type)

ShiftSlice shifts the contents of the given slice left removing the first element and returning it. If the slice is empty, it returns a zero value.

func SliceAny

func SliceAny[Type any](slice []Type, matcher func(v Type) bool) bool

SliceAny returns true if any element in the given slice passes the matcher function provided.

func SliceContains

func SliceContains[Type any](slice []Type, matcher func(v Type) bool) bool

SliceContains runs a matcher on all values of a slice and returns true when the matching function does.

func SliceEvery

func SliceEvery[Type any](slice []Type, matcher func(v Type) bool) bool

SliceEvery returns true if every element in the given slice passes the matcher function provided.

func SliceFindFirst

func SliceFindFirst[Type any](slice []Type, matcher func(v Type) bool) (*Type, bool)

SliceFindFirst runs a matcher on all values of a slice and returns the value that responds with true.

func SliceFindIndex

func SliceFindIndex[Type any](slice []Type, matcher func(v Type) bool) int

func SplitKeyValue

func SplitKeyValue[Key comparable, Value any](target map[Key]Value) (keys []Key, vals []Value)

SplitKeyValue takes a map and splits the keys and values into two separate slices and returns them.

func SplitSlice

func SplitSlice[Type any](slice []Type, matcher func(v Type) bool) (falses []Type, trues []Type)

SplitSlice runs a matcher on every entry in the supplied slice. When the matcher returns true it is added to a "trues" slice, when false to a "falses" slice. Both slices are returned.

func SplitStringByRune

func SplitStringByRune(str string, run rune) []string

SplitStringByRune splits up the string by searching for the given rune. It does not consume the rune in the parts provided. Remaining tail after the last rune is included.

func SplitStringsToMap

func SplitStringsToMap(strs []string, sep string) (ret map[string]string)

SplitStringsToMap runs the strings.Cut function on a slice of strings and for each entry it sets a map entry. Everything before the [sep] is placed as the key, everything after is the value.

If any of the entries only return 1 string, then an empty value is set for the key placement.

func StringMatcher

func StringMatcher(test string) func(v string) bool

func StructProcessVar

func StructProcessVar[Type any](prefix string, defValue Type) Type

StructProcessVar is a self-initializing variable which looks for it's value in multiple places at the time of instantiation. This version targets a struct and it's fields. If the struct contains exported fields it will search both the environment and command line arguments for a value. It finds these by prefixing both the env, and cli lookups with the given prefix to prevent global crowding.

Order of operations for finding the value is: - Default Value - Environment variable - Command line argument

func Ternary

func Ternary[Type any](cond bool, t Type, f Type) Type

Ternary is a helper to do ternary type operations where you just want to return one or the other value based on a condition without needing to set a var in the scope block.

Basically, if you ever went for a ternary to set a value and thought "damn, why doesn't go have ternaries again?", then just use this.

func TransformMapKeys

func TransformMapKeys[Key comparable, Value any](target map[Key]Value, transform func(Key) Key) (ret map[Key]Value)

TransformMapKeys returns a new map with each key of the [target] map ran through the transform function.

It does not edit in-place in order to protect against clashing key overwrites.

func TransformMapValues

func TransformMapValues[Key comparable, Value any](target map[Key]Value, transform func(Value) Value) map[Key]Value

TransformMapValues returns the same map with each value of the [target] map ran through the transform function.

This operates in-place for the map since the keys are the same.

func UniquifyString

func UniquifyString(str string) (string, error)

UniquifyString makes a string "unique"-ish for conflict checking by normalizing the text to ASCII lower-case.

Types

type Date

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

Date masks a time.Time to only marshal and unmarshal the date portion. For strings it chooses the ISO/RFC format of "2006-01-02"

func DateFromTime

func DateFromTime(t time.Time) Date

DateFromTime returns a new Date object using the given time

func DateNow

func DateNow() Date

DateNow returns a new Date object set to now via time.Now.

func ParseDate

func ParseDate(str string) (Date, error)

ParseDate accepts a string that is RFC3339 date-only such as "2006-01-02" and parses it into a new Date object.

func (Date) Add

func (d Date) Add(dur time.Duration) Date

func (Date) After

func (d Date) After(other Date) bool

After returns true if THIS date is after the given other.

func (Date) Age

func (d Date) Age() int

Age returns the number of years since the given date, probably.

func (Date) Before

func (d Date) Before(other Date) bool

Before returns true if THIS date is before the given other.

func (Date) Compare

func (d Date) Compare(other Date) (dif int)

Compare returns -1 if THIS date is before the given other, 1 if THIS date is AFTER the given other, and 0 if they are equal.

func (Date) Day

func (d Date) Day() int

func (Date) DurationBetween

func (d Date) DurationBetween(other Date) time.Duration

DurationBetween may or may not work. It subtracts the other date from this date and truncates the resulting duration to 24 hours.

func (Date) Equal

func (d Date) Equal(other Date) bool

func (Date) IsZero

func (d Date) IsZero() bool

IsZero returns true if this Date is a zero-value.

func (Date) MarshalJSON

func (d Date) MarshalJSON() ([]byte, error)

func (Date) MarshalText

func (d Date) MarshalText() ([]byte, error)

func (Date) Month

func (d Date) Month() int

func (*Date) Parse

func (d *Date) Parse(str string) (err error)

Parse accepts a string that is RFC3339 date-only such as "2006-01-02" and parses it into this value. If an error occurs it is returned.

func (*Date) Scan

func (d *Date) Scan(src any) error

func (Date) String

func (d Date) String() string

func (Date) Time

func (d Date) Time() *time.Time

func (*Date) UnmarshalJSON

func (d *Date) UnmarshalJSON(src []byte) error

func (*Date) UnmarshalText

func (d *Date) UnmarshalText(src []byte) error

func (Date) Value

func (d Date) Value() (driver.Value, error)

func (Date) Year

func (d Date) Year() int

type EventManager

type EventManager[Payload any] struct {
	// contains filtered or unexported fields
}

EventManager is a simple thread-safe dispatcher for managing callbacks in the case of events.

Any listener that returns true when called will remove itself. This is good for one-shot event listeners.

func NewEventManager

func NewEventManager[Payload any]() EventManager[Payload]

func (*EventManager[Payload]) Add

func (e *EventManager[Payload]) Add(cb func(payload Payload) bool) uint

Add adds a new listener to the event manager with the given callback. It returns the ID for the listener so that it can be removed later with [Remove]

func (*EventManager[Payload]) Dispatch

func (e *EventManager[Payload]) Dispatch(payload Payload)

Dispatch sends the payload to all the listeners in the list. If any of the listeners return true, then they will be removed from the manager.

func (*EventManager[Payload]) Remove

func (e *EventManager[Payload]) Remove(id uint)

Remove removes the listener with the given ID

type FixedArray

type FixedArray[Type any] struct {
	// contains filtered or unexported fields
}

FixedArray is a data structure for holding a fixed amount of elements. Any new elements pushed will evict the older elements.

There is no mutexes here as that is up to your implementation. The oldest element will be at index 0.

func NewFixedArray

func NewFixedArray[Type any](size int, elems ...Type) FixedArray[Type]

NewFixedArray creates an instantiates a new FixedArray of the given size.

func (FixedArray[Type]) Copy

func (a FixedArray[Type]) Copy() (ret FixedArray[Type])

func (FixedArray[Type]) Count

func (a FixedArray[Type]) Count() int

Count returns the current size of the array as it is filled and will never exceed [Size].

func (FixedArray[Type]) Elements

func (a FixedArray[Type]) Elements() (ret []Type)

Elements copies the internal array and returns it as a slice.

func (FixedArray[Type]) IsFull

func (a FixedArray[Type]) IsFull() bool

IsFull returns true if the array is considered full

func (FixedArray[Type]) MarshalJSON

func (a FixedArray[Type]) MarshalJSON() ([]byte, error)

func (FixedArray[Type]) Oldest

func (a FixedArray[Type]) Oldest() *Type

Oldest returns the first element being the oldest in the array

func (*FixedArray[Type]) Push

func (a *FixedArray[Type]) Push(elems ...Type)

Push adds new elements on-top of this array. They are added in the order they are provided.

NOTE: An optimization can be made to pre-shift the whole array to the number of elements being added instead of individually.

func (*FixedArray[Type]) Reset

func (a *FixedArray[Type]) Reset()

Reset clears the array

func (FixedArray[Type]) Size

func (a FixedArray[Type]) Size() int

Size returns the maximum size of the array

func (FixedArray[Type]) Youngest

func (a FixedArray[Type]) Youngest() *Type

Youngest returns the last element being the youngest in the array

type Float

type Float interface {
	float32 | float64
}

type Integer

type Integer interface {
	int | int8 | int16 | int32 | int64 | byte
}

type LTree

type LTree string

LTree is a type of string which features dot-delimitated portions declaring a scope in order from widest, to narrowest. They are good for searching scoped tags that can be held as human-readable text.

The LTree segments should be case-insensitive leaning towards lower-case favored.

func NewLTree

func NewLTree(segments ...string) LTree

NewLTree joins the given segments with the "." deliminator to form a new L-Tree string. This normalizes the string to lowercase

func (LTree) Match

func (t LTree) Match(str string) bool

Match checks if the given query string matches against this L-Tree. This is a very basic implementation and allows only for the '*' operator to use as a wildcard for a whole segment. Otherwise, each part is matched in order.

func (LTree) Postfix

func (t LTree) Postfix(segments ...string) LTree

func (LTree) Prefix

func (t LTree) Prefix(segments ...string) LTree

func (LTree) Segments

func (t LTree) Segments() []string

func (LTree) String

func (t LTree) String() string

type Number

type Number interface {
	Integer | Uinteger | Float
}

type Primitive

type Primitive interface {
	bool | Number | string
}

type PriorityQueue

type PriorityQueue[Type any] struct {
	// contains filtered or unexported fields
}

PriorityQueue is a queue type backed by a slice and mutex locks that takes new items in and adds them to the end of the queue. It features a limited size that when exceeded will trim the contents and shift the queue to make room for new items. I didn't have a better name, but basically it "prioritizes" incoming items over older indices by shifting the slice left. It is considered FIFO in that the oldest items are returned first when accessing.

func NewPriorityQueue

func NewPriorityQueue[Type any](capacity int) PriorityQueue[Type]

NewPriorityQueue constructs a new PriorityQueue using the given capacity. This capacity is used to allocate the internal slice's capacity at creation time.

func (*PriorityQueue[Type]) Capacity

func (q *PriorityQueue[Type]) Capacity() int

Capacity returns the maximum capacity of the slice

func (*PriorityQueue[Type]) Length

func (q *PriorityQueue[Type]) Length() int

Length returns the current length of the internal queue slice. This is thread safe.

func (*PriorityQueue[Type]) Peek

func (q *PriorityQueue[Type]) Peek(count int) []Type

Peek returns the elements (up to [count] number) of the oldest elements in the queue.

func (*PriorityQueue[Type]) Pop

func (q *PriorityQueue[Type]) Pop(count int) []Type

Pop returns the elements (up to [count] number) of the oldest elements in the queue. It adjusts the queue by removing the items chosen and shifting the newer ones down.

func (*PriorityQueue[Type]) Push

func (q *PriorityQueue[Type]) Push(items ...Type) int

Push adds items to the end of the queue. If the capacity is exceeded it shifts the oldest items out to make room for the new items. It returns the number of displaced items (if any). If more items are pushed than there is capacity for, then the items being pushed are also trimmed to the [Capacity] limit of oldest items.

func (*PriorityQueue[Type]) Slice

func (q *PriorityQueue[Type]) Slice() []Type

Slice returns a copy of the internal slice. This is thread-safe.

type Uinteger

type Uinteger interface {
	uint | uint8 | uint16 | uint32 | uint64
}

type Validable

type Validable interface {
	// Valid returns true if this object is considered valid, and false otherwise.
	Valid() bool
}

Validable is an interface describing a type that can be checked for boolean validity.

Jump to

Keyboard shortcuts

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