generic

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 15 Imported by: 21

Documentation

Overview

This package provides generic helper functions for generic container types, as well as "generic" utility functions (the other meaning of generic).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddExitCleanup added in v0.1.2

func AddExitCleanup(fn func())

func AllocAppend

func AllocAppend[T any](list *[]T) *T

AllocAppend appends a zero item to the list and returns a pointer to the added item

func Append

func Append[T any](list *[]T, items ...T) int

Append adds an element to the list and returns its index. It takes a pointer to the list and a bunch of items to append. The idea is to replace the common but inconvenient pattern of `list = append(list, item)`

func Assert

func Assert(cond bool, msg string)

func CappedLength

func CappedLength[T any](slice []T, maxLen int, slack int) []T

CappedLength

func Clamp

func Clamp[T numeric](start T, item *T, end T)

func Cleanup added in v0.1.2

func Cleanup()

func Clone

func Clone[T any](s []T) []T

func EnsureMapNotNil

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

EnsureMapNotNil will make the map if it's nil

func EnsureSliceNotNil

func EnsureSliceNotNil[T any](m *[]T)

EnsureSliceNotNil will make the slice of it's nil

func ExitWithCleanup added in v0.1.2

func ExitWithCleanup(code int)

func FindPtr added in v0.1.4

func FindPtr[T any](list []T, check func(*T) bool) *T

func GenerateId added in v0.1.3

func GenerateId(size int) string

func GrowSlice

func GrowSlice[T any](m *[]T, length int)

GrowSlice increase the size of the slice and fills the new slots with the zero value. Does nothing if slice's length is already equal or greater than the requested size

func HasKey added in v0.1.3

func HasKey[K comparable, V any](m map[K]V, key K) bool
func Head(input string, sep string) (head string, tail string)

func IndexOf

func IndexOf[T comparable](list []T, item T) int

func InitMap

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

InitMap is short hand for `m = make(map[K]V)` so you don't have to type out the full types. Just call `generic.InitMap(&m)`

func InitSlice

func InitSlice[T any](m *[]T)

InitSlice is short hand for `list = make(list[T])` so you don't have to type out the full type. Just call `generic.InitSlice(&list)`

func InsertAt

func InsertAt[T any](list *[]T, idx int, items ...T)

InsertAt is a generic function to insert an item (or multiple items) at a certain position in the list

func IntAbs

func IntAbs[T int_enum](a T) int

func IsBetween

func IsBetween[T numeric](start, item, end T) bool

is `item` in the range [start, end)

func IsZero added in v0.1.4

func IsZero[T comparable](v T) bool

func IsZeroBytes added in v0.1.4

func IsZeroBytes[T any](v T) bool

func JSONify added in v0.1.2

func JSONify(obj any, indent string) string

func JoinToString

func JoinToString[T any](list []T, sep string, stringer func(T) string) string

func Last

func Last[T any](list []T) T

Last returns the last element from the list

func LogError

func LogError(e error)

func LogWarningf

func LogWarningf(format string, v ...any)

func MapEntry

func MapEntry[K comparable, V any](m map[K]V, key K, fn func(k K) V) V

Get a map entry with a function to create it if not existing

func Max

func Max[T numeric](a T, b T) T

func Min

func Min[T numeric](a T, b T) T

func MulDiv

func MulDiv[T Inty](a, b, c T) T

(a * b) / c

func MulF

func MulF[T Inty, F Floaty](n T, f F) T

func Must

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

func MustNotNil

func MustNotNil[T any](p *T) *T

func MustOK

func MustOK(err error)

func MustTrue

func MustTrue(b bool, msg error)

func OneOf

func OneOf[T comparable](item T, list []T) bool

OneOf checks whether an item is present in the list by iterating the list and returning true as soon as it finds the item

func ReadFromJSONFile added in v0.1.1

func ReadFromJSONFile[T any](filepath string, obj *T) error

ReadFromJSONFile fills in an object with data from the json provied by the file specified

func RemoveAt

func RemoveAt[T any](list *[]T, idx int, count int)

RemoveAt removes 1 or more items at a specific index in a list

func Reset

func Reset[T any](ptr *T)

Reset a thing to its zero value

func ResetSlice

func ResetSlice[T any](list *[]T)

ResetSlice shrinks a slice to a zero size

func Reverse

func Reverse[T any](a []T)

func SetsEqual

func SetsEqual[T comparable](s1 *Set[T], s2 *Set[T]) bool

func SetupSigTermCleanup added in v0.1.2

func SetupSigTermCleanup()

SetupSigTermCleanup runs ExitWithCleanup on SIGINT/SIGTERM/SIGQUIT/SIGABRT. No-op on platforms without these signals (see exit_signal_js.go).

func SharedPrefix

func SharedPrefix(str1, str2 string) string

SharedPrefix Extracts the shared prefix from two strings. Generated by ChatGPT

func SharedSuffix

func SharedSuffix(str1, str2 string) string

SharedSuffix extracts the shared suffix from two strings. Generated by ChatGPT

func ShrinkTo

func ShrinkTo[T any](list *[]T, toLen int)

ShrinkTo is a safe version of `list = list[:toLen]` in that it would not would panic if toLen is > len(list)

func Slice

func Slice[T any](items ...T) []T

Slice simplifies the syntax of the slice literal by removing the ugly curly braces. Instead of `[]int{1, 2, 3}` you can call `generic.Slice(1, 2, 3)`

func SliceAddUniq added in v0.1.3

func SliceAddUniq[T comparable](list *[]T, v T)

func SliceRemove added in v0.1.3

func SliceRemove[T comparable](list *[]T, v T)

func SlicesEqual

func SlicesEqual[T comparable](list1 []T, list2 []T) bool

func TestExpect

func TestExpect(t *testing.T, cond bool, msg string) bool

func TestExpectf

func TestExpectf(t *testing.T, cond bool, format string, args ...any) bool

func TimeStamp3Format

func TimeStamp3Format(now time.Time, roundToMinutes int) string

TimeStamp3Format takes a time and formats it as yyyy-mmdd-hhmm with the option to round to a multiple of minutes. For example, if you pass "2024-05-28 14:33" and round to 10 minutes, you get "2024-0528-1430"

func TrimSpace

func TrimSpace(s *string)

func TryAndLog

func TryAndLog[T any](value T, err error) T

func UnsafeRawBytes

func UnsafeRawBytes[T any](v *T) []byte

UnsafeRawBytes returns the raw bytes behind the object

func UnsafeRawBytesOffset

func UnsafeRawBytesOffset[T, S any](v *T, memberPtr *S) []byte

UnsafeRawBytesOffset returns the raw bytes behind an object, skipping the first few fields

func UnsafeSliceBytes

func UnsafeSliceBytes[T any](v []T) []byte

UnsafeSliceBytes takes a slice of any type and reinterprets it as a slice of bytes

func UnsafeString

func UnsafeString(b []byte) string

UnsafeString converts a byte slice to a string without copying

func UnsafeStringBytes

func UnsafeStringBytes(s string) []byte

UnsafeStringBytes converts a string to a byte slice without copying

func WaitGroupGo added in v0.1.4

func WaitGroupGo(wg *sync.WaitGroup, fn func())

func WithLock added in v0.1.4

func WithLock(lock *sync.Mutex, fn func())

func WithReadLock added in v0.1.4

func WithReadLock(lock *sync.RWMutex, fn func())

func WithTryWriteLock added in v0.1.4

func WithTryWriteLock(lock *sync.RWMutex, fn func())

will try to do the thing if the lock is available

func WithWriteLock added in v0.1.4

func WithWriteLock(lock *sync.RWMutex, fn func())

Types

type Floaty

type Floaty interface {
	~float32 | ~float64
}

type Handle added in v0.1.5

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

type Inty

type Inty interface {
	~int | ~int64 | ~int32 | ~int16 | ~int8 | ~uint64 | ~uint32 | ~uint16 | ~uint8
}

type Job added in v0.1.5

type Job = func()

type JobQueue added in v0.1.5

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

func MakeJobQueue added in v0.1.5

func MakeJobQueue(workerCount int) *JobQueue

func (*JobQueue) Submit added in v0.1.5

func (jq *JobQueue) Submit(job Job)

type Manager added in v0.1.5

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

func MakeManager added in v0.1.5

func MakeManager[T any]() *Manager[T]

func (*Manager[T]) Create added in v0.1.5

func (m *Manager[T]) Create() (itemPtr *T, handle Handle[T])

func (*Manager[T]) Delete added in v0.1.5

func (m *Manager[T]) Delete(handle Handle[T])

func (*Manager[T]) GetItem added in v0.1.5

func (m *Manager[T]) GetItem(handle Handle[T]) *T

func (*Manager[T]) Reset added in v0.1.5

func (m *Manager[T]) Reset()

type Set

type Set[T comparable] struct {
	Map map[T]bool
}

func NewSet

func NewSet[T comparable]() *Set[T]

func NewSetFrom

func NewSetFrom[T comparable](items []T) *Set[T]

func (*Set[T]) Add

func (s *Set[T]) Add(items ...T)

func (*Set[T]) Has

func (s *Set[T]) Has(item T) bool

func (*Set[T]) Remove

func (s *Set[T]) Remove(item T)

type SyncMap added in v0.1.6

type SyncMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewSyncMap added in v0.1.6

func NewSyncMap[K comparable, V any]() *SyncMap[K, V]

func (*SyncMap[K, V]) Clear added in v0.1.6

func (m *SyncMap[K, V]) Clear()

func (*SyncMap[K, V]) Get added in v0.1.6

func (m *SyncMap[K, V]) Get(key K) (V, bool)

func (*SyncMap[K, V]) Init added in v0.1.7

func (m *SyncMap[K, V]) Init()

func (*SyncMap[K, V]) LoadOrStore added in v0.1.7

func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool)

LoadOrStore inserts value if key is absent. Returns the map value and whether it was already present (true = loaded existing, false = stored value).

func (*SyncMap[K, V]) Remove added in v0.1.7

func (m *SyncMap[K, V]) Remove(key K)

func (*SyncMap[K, V]) Set added in v0.1.6

func (m *SyncMap[K, V]) Set(key K, value V)

type SyncOrderedSet added in v0.1.3

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

SyncOrderedSet uses a list and a lock and checks item duplication before adding them

func (*SyncOrderedSet[T]) Add added in v0.1.3

func (s *SyncOrderedSet[T]) Add(item T)

func (*SyncOrderedSet[T]) Has added in v0.1.3

func (s *SyncOrderedSet[T]) Has(item T) bool

func (*SyncOrderedSet[T]) Init added in v0.1.7

func (s *SyncOrderedSet[T]) Init()

func (*SyncOrderedSet[T]) List added in v0.1.3

func (s *SyncOrderedSet[T]) List() []T

func (*SyncOrderedSet[T]) Remove added in v0.1.3

func (s *SyncOrderedSet[T]) Remove(item T)

func (*SyncOrderedSet[T]) Replace added in v0.1.3

func (s *SyncOrderedSet[T]) Replace(items []T)

Caller must ensure no duplicates! (though they don't really hurt)

type Throttler added in v0.1.3

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

func NewThrottler added in v0.1.3

func NewThrottler(delay time.Duration, fn func()) *Throttler

func (*Throttler) ThrottledCall added in v0.1.3

func (t *Throttler) ThrottledCall()

type TypedArena

type TypedArena[T any] struct {
	First   *TypedBucket[T]
	Current *TypedBucket[T]
}

func NewTypedArena

func NewTypedArena[T any]() *TypedArena[T]

func (*TypedArena[T]) Allocate

func (a *TypedArena[T]) Allocate() *T

func (*TypedArena[T]) Iterate

func (a *TypedArena[T]) Iterate(visitFn func(index int, item *T) bool)

func (*TypedArena[T]) IterateBuckets

func (a *TypedArena[T]) IterateBuckets(visitFn func(items []T))

type TypedBucket

type TypedBucket[T any] struct {
	Items      [4 * 1024]T
	Next       int
	NextBucket *TypedBucket[T]
}

Jump to

Keyboard shortcuts

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