abstract

package module
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2025 License: MIT Imports: 31 Imported by: 2

README

abstract

Go Version GoDoc Build GoReport

abstract provides a suite of generic data structures to focus on the core business logic and avoid unnecessary boilerplate

go get -u github.com/maxbolgarin/abstract

Overview

abstract package provides a suite of generic data structures to enhance code organization, concurrency safety, and utility in Go. The package aims to simplify and abstract the working processes with generic and concurrent data structures such as maps, stacks, sets, and pairs.

Key Features
  • Generic Data Structures: Includes Map, Orderer, Stack, Set, and their thread-safe counterparts.
  • Clean Code: Using of this package allowes you to focus on the core business logic and avoid unnecessary complexity.
  • Concurrency Safety: Thread-safe structures provided for concurrent access across multiple goroutines.
  • Ease of Use: Designed to integrate seamlessly and abstract away complex operations into simple APIs.
Cons
  • Complexity: Abstraction layers might add complexity for simpler use cases.
  • Performance Overhead: Concurrency safety through mutexes can add overhead.
  • Learning Curve: Understanding generics and constraints may require additional learning.
Data Structures and Safe Alternatives
Data Structure Description Safe Alternative Key Methods
Map Generic map for key-value pairs. SafeMap Get, Set, Delete, Keys, Values
EntityMap Map of entities, providing ordering features. SafeEntityMap Set, Delete, AllOrdered
Set Stores keys uniquely without associated values. SafeSet Add, Remove, Has
Slice Generic slice implementation. SafeSlice Append, Get, Pop, Delete
Stack Generic stack implementation. SafeStack Push, Pop, Last
UniqueStack Stack without duplicates. SafeUniqueStack Push, Pop, Last
LinkedList Generic doubly linked list implementation. SafeLinkedList Front, Back
OrderedPairs Maintains order of key-value pairs. SafeOrderedPairs Add, Get, Keys, Rand

Usage Examples

Using Map and SafeMap
package main

import (
	"fmt"
	"github.com/maxbolgarin/abstract"
)

func main() {
	// Example using Map
	m := abstract.NewMap[string, int]()
	m.Set("apple", 5)
	fmt.Println(m.Get("apple")) // Output: 5

	// Example using SafeMap
	sm := abstract.NewSafeMap[string, int]()
	sm.Set("banana", 10)
	fmt.Println(sm.Get("banana")) // Output: 10
}
Using Stack and SafeStack
package main

import (
	"fmt"
	"abstract"
)

func main() {
	// Example using Stack
	s := abstract.NewStack[int]()
	s.Push(10)
	fmt.Println(s.Pop()) // Output: 10

	// Example using SafeStack
	ss := abstract.NewSafeStack[int]()
	ss.Push(20)
	fmt.Println(ss.Pop()) // Output: 20
}
Using EntityMap and SafeEntityMap
package main

import (
	"fmt"
	"abstract"
)

// Define a simple Entity type
type MyEntity struct {
	id    string
	name  string
	order int
}

func (e MyEntity) ID() string    { return e.id }
func (e MyEntity) Name() string  { return e.name }
func (e MyEntity) Order() int    { return e.order }
func (e MyEntity) SetOrder(o int) abstract.Entity[string] {
	return MyEntity{id: e.id, name: e.name, order: o}
}

func main() {
	eMap := abstract.NewEntityMap[string, MyEntity]()
	eMap.Set(MyEntity{id: "1", name: "entity1", order: 0})
	foundEntity, ok := eMap.LookupByName("entity1")
	if ok {
		fmt.Println(foundEntity.Name()) // Output: entity1
	}
}

Contributions and Issues

Feel free to contribute to this package or report issues you encounter during usage

License

This project is licensed under the terms of the MIT License.

Documentation

Overview

Package abstract provides abstract objects to make work easier and simplify code.

Copy paste from https://github.com/gtank/cryptopasta/tree/master

Index

Constants

This section is empty.

Variables

View Source
var ErrTimeout = errors.New("timeout")

Functions

func Abs added in v1.5.0

func Abs[T Number](x T) T

Abs returns the absolute value of the provided value.

func Atoi added in v1.5.0

func Atoi[T Number](s string) (T, error)

Atoi converts a string to an integer.

func CheckHMAC added in v1.11.0

func CheckHMAC(data, suppliedMAC []byte, key *[32]byte) bool

CheckHMAC securely checks the supplied MAC against a message using the shared secret key.

func DecodePrivateKey added in v1.11.0

func DecodePrivateKey(encodedKey []byte) (*ecdsa.PrivateKey, error)

DecodePrivateKey decodes a PEM-encoded ECDSA private key.

func DecodePublicKey added in v1.11.0

func DecodePublicKey(encodedKey []byte) (*ecdsa.PublicKey, error)

DecodePublicKey decodes a PEM-encoded ECDSA public key.

func DecodeSignatureJWT added in v1.11.0

func DecodeSignatureJWT(b64sig string) ([]byte, error)

Decodes an ECDSA signature according to https://tools.ietf.org/html/rfc7515#appendix-A.3.1

func DecryptAES added in v1.11.0

func DecryptAES(ciphertext []byte, key *[32]byte) (plaintext []byte, err error)

DecryptAES decrypts data using 256-bit AES-GCM. This both hides the content of the data and provides a check that it hasn't been altered. Expects input form nonce|ciphertext|tag where '|' indicates concatenation.

func EncodePrivateKey added in v1.11.0

func EncodePrivateKey(key *ecdsa.PrivateKey) ([]byte, error)

EncodePrivateKey encodes an ECDSA private key to PEM format.

func EncodePublicKey added in v1.11.0

func EncodePublicKey(key *ecdsa.PublicKey) ([]byte, error)

EncodePublicKey encodes an ECDSA public key to PEM format.

func EncodeSignatureJWT added in v1.11.0

func EncodeSignatureJWT(sig []byte) string

Encodes an ECDSA signature according to https://tools.ietf.org/html/rfc7515#appendix-A.3.1

func EncryptAES added in v1.11.0

func EncryptAES(plaintext []byte, key *[32]byte) (ciphertext []byte, err error)

EncryptAES encrypts data using 256-bit AES-GCM. This both hides the content of the data and provides a check that it hasn't been altered. Output takes the form nonce|ciphertext|tag where '|' indicates concatenation.

func FromID added in v1.10.1

func FromID(id string, t EntityType) string

FromID changes entity type for the provided ID.

func GenerateHMAC added in v1.11.0

func GenerateHMAC(data []byte, key *[32]byte) []byte

GenerateHMAC produces a symmetric signature using a shared secret key.

func GetRandListenAddress

func GetRandListenAddress() (port string)

GetRandListenAddress generates a random port number between 10000 and 63000.

func GetRandomBytes

func GetRandomBytes(n int) []byte

GetRandomBytes returns a random bytes of length n contains letters from hex.

func GetRandomString

func GetRandomString(n int) string

GetRandomString returns a random string of length n contains letters from hex.

func HashHMAC added in v1.11.0

func HashHMAC(tag string, data []byte) []byte

HashHMAC generates a hash of data using HMAC-SHA-512/256. The tag is intended to be a natural-language string describing the purpose of the hash, such as "hash file for lookup key" or "master secret to client secret". It serves as an HMAC "key" and ensures that different purposes will have different hash output. This function is NOT suitable for hashing passwords.

func Itoa added in v1.5.0

func Itoa[T Number](i T) string

Itoa converts an integer to a string.

func Max added in v1.5.0

func Max[T Number](xs ...T) T

Max returns the maximum value from the provided values.

func Min added in v1.5.0

func Min[T Number](xs ...T) T

Min returns the minimum value from the provided values.

func NewEncryptionKey added in v1.11.0

func NewEncryptionKey() *[32]byte

NewEncryptionKey generates a random 256-bit key for Encrypt() and Decrypt(). It panics if the source of randomness fails.

func NewHMACKey added in v1.11.0

func NewHMACKey() *[32]byte

NewHMACKey generates a random 256-bit secret key for HMAC use. Because key generation is critical, it panics if the source of randomness fails.

func NewID added in v1.10.1

func NewID(entityType EntityType) string

NewID is used to generate a new ID based on provided entity type.

func NewSigningKey added in v1.11.0

func NewSigningKey() (*ecdsa.PrivateKey, error)

NewSigningKey generates a random P-256 ECDSA private key.

func NewTestID added in v1.10.1

func NewTestID() string

NewTestID is used to generate a new ID based on Test entity type.

func Pow added in v1.5.0

func Pow[T1, T2 Number](x T1, y T2) T1

Pow returns the value raised to the provided power.

func Round added in v1.5.0

func Round[T Number](f T) T

Round returns the nearest integer, rounding half away from zero.

func SetEntitySize added in v1.10.0

func SetEntitySize(size int)

func SignData added in v1.11.0

func SignData(data []byte, privkey *ecdsa.PrivateKey) ([]byte, error)

SignData signs arbitrary data using ECDSA.

func StartCycle added in v1.7.0

func StartCycle(ctx context.Context, l lang.Logger, f func())

StartCycle starts a new panicsafe goroutine. It runs the provided function in a loop until the context is canceled.

func StartCycleWithChan added in v1.7.0

func StartCycleWithChan[T any](ctx context.Context, l lang.Logger, c <-chan T, f func(T))

StartCycleWithChan starts a new panicsafe goroutine. It runs the provided function for each value from the provided channel. It stops the goroutine when the context is canceled or the provided channel is closed.

func StartCycleWithChanAndShutdown added in v1.7.0

func StartCycleWithChanAndShutdown[T any](ctx context.Context, l lang.Logger, c <-chan T, shutdown <-chan struct{}, f func(T))

StartCycleWithChanAndShutdown starts a new panicsafe goroutine. It runs the provided function for each value from the provided channel. It stops the goroutine when the context is canceled or the provided shutdown channel is closed.

func StartCycleWithShutdown added in v1.7.0

func StartCycleWithShutdown(ctx context.Context, l lang.Logger, shutdown <-chan struct{}, f func())

StartCycleWithShutdown starts a new panicsafe goroutine. It runs the provided function in a loop until the context is canceled or the provided shutdown channel is closed.

func StartUpdater

func StartUpdater(ctx context.Context, interval time.Duration, l lang.Logger, f func())

StartUpdater starts a new panicsafe goroutine. It runs the provided function one time per the interval. It stops the goroutine when the context is canceled.

func StartUpdaterNow

func StartUpdaterNow(ctx context.Context, interval time.Duration, l lang.Logger, f func())

StartUpdaterNow starts a new panicsafe goroutine. It runs the provided function right now and then one time per the interval. It stops the goroutine when the context is canceled.

func StartUpdaterWithShutdown

func StartUpdaterWithShutdown(ctx context.Context, interval time.Duration, l lang.Logger, f func(), shutdown func())

StartUpdaterWithShutdown starts a new panicsafe goroutine. It runs the provided function one time per the interval. It runs the shutdown function and stops the goroutine when the context is canceled.

func StartUpdaterWithShutdownChan

func StartUpdaterWithShutdownChan(ctx context.Context, interval time.Duration, l lang.Logger, c chan struct{}, f func())

StartUpdaterWithShutdownChan starts a new panicsafe goroutine. It runs the provided function one time per the interval. It stops the goroutine when the context is canceled or the provided channel is closed.

func VerifySign added in v1.11.0

func VerifySign(data, signature []byte, pubkey *ecdsa.PublicKey) bool

VerifySign checks a raw ECDSA signature. Returns true if it's valid and false if not.

Types

type Builder added in v1.10.0

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

func WithEntityType added in v1.10.1

func WithEntityType(t EntityType) Builder

func (Builder) NewID added in v1.10.1

func (b Builder) NewID() string

type CSVTable added in v1.11.0

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

CSVTable represents a table of data from a CSV file where the first column is used as the ID for each row, and the remaining columns are stored as key-value pairs.

func NewCSVTable added in v1.11.0

func NewCSVTable(records [][]string) *CSVTable

NewCSVTable creates a new CSVTable from the given records. The first row is considered the header row, and the first column is used as the ID for each row. Each row's data is stored as a map of column name to value. If the records are empty or if there are not enough headers (< 2), returns an empty table.

func NewCSVTableFromFilePath added in v1.11.0

func NewCSVTableFromFilePath(path string) (*CSVTable, error)

NewCSVTableFromFilePath creates a new CSVTable from a file at the given path. Returns an error if the file cannot be opened or parsed.

func NewCSVTableFromReader added in v1.11.0

func NewCSVTableFromReader(reader io.Reader) (*CSVTable, error)

NewCSVTableFromReader creates a new CSVTable from any io.Reader that contains CSV data. Returns an error if the CSV data cannot be parsed.

func (*CSVTable) AddRow added in v1.11.0

func (t *CSVTable) AddRow(id string, row map[string]string)

AddRow adds a new row to the table with the given ID and data. If the row has no data, it will not be added.

func (*CSVTable) All added in v1.11.0

func (t *CSVTable) All() map[string]map[string]string

All returns all rows in the table as a map of ID to row data. WARNING: The returned maps are direct references, not copies. Modifying the returned maps will modify the internal state of the CSVTable, which is generally not recommended. Use Copy() if you need to modify the data.

func (*CSVTable) AllIDs added in v1.11.0

func (t *CSVTable) AllIDs() []string

AllIDs returns a slice of all row IDs in the table.

func (*CSVTable) AllRows added in v1.11.0

func (t *CSVTable) AllRows() []map[string]string

AllRows returns all rows in the table as a slice of row data maps. WARNING: The returned maps are direct references, not copies. Modifying the returned maps will modify the internal state of the CSVTable, which is generally not recommended. Use Copy() if you need to modify the data.

func (*CSVTable) AppendColumn added in v1.11.0

func (t *CSVTable) AppendColumn(column string, values []string)

AppendColumn adds a new column to the table with the given name and values. Values are assigned to rows in order. If there are more rows than values, the remaining rows will not have a value for this column.

func (*CSVTable) Bytes added in v1.11.0

func (t *CSVTable) Bytes() []byte

Bytes returns the table as a CSV-formatted byte slice.

func (*CSVTable) Copy added in v1.11.0

func (t *CSVTable) Copy() *CSVTable

Copy creates a deep copy of the CSVTable. This is useful if you need to modify the data without affecting the original.

func (*CSVTable) DeleteColumns added in v1.11.0

func (t *CSVTable) DeleteColumns(columns ...string)

DeleteColumns removes the specified columns from the table. This affects both the headers and the data in each row.

func (*CSVTable) Has added in v1.11.0

func (t *CSVTable) Has(slug string) bool

Has returns true if a row with the given ID exists in the table.

func (*CSVTable) Headers added in v1.11.0

func (t *CSVTable) Headers() []string

Headers returns a copy of the headers for the table.

func (*CSVTable) LookupRow added in v1.11.0

func (t *CSVTable) LookupRow(slug string) (map[string]string, bool)

LookupRow returns the data for the row with the given ID and a boolean indicating if the row exists. WARNING: The returned map is a direct reference, not a copy. Modifying the returned map will modify the internal state of the CSVTable, which is generally not recommended. Use Copy() if you need to modify the data.

func (*CSVTable) Row added in v1.11.0

func (t *CSVTable) Row(slug string) map[string]string

Row returns the data for the row with the given ID. If no row with that ID exists, returns an empty map. WARNING: The returned map is a direct reference, not a copy. Modifying the returned map will modify the internal state of the CSVTable, which is generally not recommended. Use Copy() if you need to modify the data.

func (*CSVTable) Value added in v1.11.0

func (t *CSVTable) Value(slug, key string) string

Value returns the value for the given ID and key. If no row with that ID exists, or if the key doesn't exist in that row, returns an empty string.

type CSVTableSafe added in v1.11.0

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

CSVTableSafe is a thread-safe wrapper around CSVTable that provides synchronized access to the underlying data using a mutex.

func NewCSVTableSafe added in v1.11.0

func NewCSVTableSafe(records [][]string) *CSVTableSafe

NewCSVTableSafe creates a new thread-safe CSVTable from records.

func NewCSVTableSafeFromFilePath added in v1.11.0

func NewCSVTableSafeFromFilePath(path string) (*CSVTableSafe, error)

NewCSVTableSafeFromFilePath creates a new thread-safe CSVTable from a file path.

func NewCSVTableSafeFromReader added in v1.11.0

func NewCSVTableSafeFromReader(reader io.Reader) (*CSVTableSafe, error)

NewCSVTableSafeFromReader creates a new thread-safe CSVTable from a reader.

func (*CSVTableSafe) AddRow added in v1.11.0

func (t *CSVTableSafe) AddRow(id string, row map[string]string)

AddRow adds a new row to the table in a thread-safe manner.

func (*CSVTableSafe) All added in v1.11.0

func (t *CSVTableSafe) All() map[string]map[string]string

All returns a deep copy of all rows in the table.

func (*CSVTableSafe) AllIDs added in v1.11.0

func (t *CSVTableSafe) AllIDs() []string

AllIDs returns a copy of all row IDs in the table.

func (*CSVTableSafe) AllRows added in v1.11.0

func (t *CSVTableSafe) AllRows() []map[string]string

AllRows returns a deep copy of all rows as a slice of maps.

func (*CSVTableSafe) AppendColumn added in v1.11.0

func (t *CSVTableSafe) AppendColumn(column string, values []string)

AppendColumn adds a new column to the table in a thread-safe manner.

func (*CSVTableSafe) Bytes added in v1.11.0

func (t *CSVTableSafe) Bytes() []byte

Bytes returns the table as a CSV-formatted byte slice.

func (*CSVTableSafe) Copy added in v1.11.0

func (t *CSVTableSafe) Copy() *CSVTableSafe

Copy creates a deep copy of the CSVTableSafe, including its internal table.

func (*CSVTableSafe) DeleteColumns added in v1.11.0

func (t *CSVTableSafe) DeleteColumns(columns ...string)

DeleteColumns removes the specified columns from the table.

func (*CSVTableSafe) Has added in v1.11.0

func (t *CSVTableSafe) Has(slug string) bool

Has returns true if a row with the given ID exists in the table.

func (*CSVTableSafe) Headers added in v1.11.0

func (t *CSVTableSafe) Headers() []string

Headers returns a copy of the headers for the table.

func (*CSVTableSafe) LookupRow added in v1.11.0

func (t *CSVTableSafe) LookupRow(slug string) (map[string]string, bool)

LookupRow returns a copy of the row with the given ID and whether it exists.

func (*CSVTableSafe) Row added in v1.11.0

func (t *CSVTableSafe) Row(slug string) map[string]string

Row returns a copy of the row with the given ID to avoid concurrent modification issues.

func (*CSVTableSafe) Unwrap added in v1.11.0

func (t *CSVTableSafe) Unwrap() *CSVTable

Unwrap returns the underlying CSVTable. WARNING: This breaks thread safety. Only use when you're sure no other goroutines are accessing the table.

func (*CSVTableSafe) Value added in v1.11.0

func (t *CSVTableSafe) Value(slug, key string) string

Value returns the value for the given ID and key.

type Complex

type Complex interface {
	~complex64 | ~complex128
}

Complex is a constraint that permits any complex numeric type. If future releases of Go add new predeclared complex numeric types, this constraint will be modified to include them.

type Entity

type Entity[K comparable] interface {
	GetID() K
	GetName() string
	GetOrder() int
	SetOrder(int) Entity[K]
}

Entity is an interface for an object that has an ID, a name, and an order.

type EntityMap

type EntityMap[K comparable, T Entity[K]] struct {
	*Map[K, T]
}

EntityMap is a map of entities. It has all methods of Map with some new ones. It is not safe for concurrent/parallel, use SafeEntityMap if you need it.

func NewEntityMap

func NewEntityMap[K comparable, T Entity[K]](raw ...map[K]T) *EntityMap[K, T]

NewEntityMap returns a new EntityMap from the provided map.

func NewEntityMapWithSize

func NewEntityMapWithSize[K comparable, T Entity[K]](size int) *EntityMap[K, T]

NewEntityMapWithSize returns a new EntityMap with the provided size.

func (*EntityMap[K, T]) AllOrdered

func (s *EntityMap[K, T]) AllOrdered() []T

AllOrdered returns all values in order.

func (*EntityMap[K, T]) ChangeOrder

func (s *EntityMap[K, T]) ChangeOrder(draft map[K]int)

ChangeOrder changes the order of the values.

func (*EntityMap[K, T]) Delete

func (s *EntityMap[K, T]) Delete(keys ...K) (deleted bool)

Delete deletes values for the provided keys. It reorders all remaining values.

func (*EntityMap[K, T]) LookupByName

func (s *EntityMap[K, T]) LookupByName(name string) (T, bool)

LookupByName returns the value for the provided name. It is not case-sensetive according to name.

func (*EntityMap[K, T]) NextOrder

func (s *EntityMap[K, T]) NextOrder() int

NextOrder returns the next order.

func (*EntityMap[K, T]) Set

func (s *EntityMap[K, T]) Set(info T) int

Set sets the value for the provided key. It sets last order to the entity's order, so it adds to the end of the list. It sets the same order of existing entity in case of conflict. It returns the order of the entity.

func (*EntityMap[K, T]) SetManualOrder added in v1.4.0

func (s *EntityMap[K, T]) SetManualOrder(info T) int

SetManualOrder sets the value for the provided key. Better to use EntityMap.Set to prevent from order errors. It returns the order of the entity.

type EntityType added in v1.10.0

type EntityType string
const (
	TestIDEntity EntityType = "00x0"
)

func FetchEntityType added in v1.10.0

func FetchEntityType(id string) EntityType

FetchEntityType is used to extract entity type from provided ID.

func RegisterEntityType added in v1.10.0

func RegisterEntityType(entityType string) EntityType

func (EntityType) String added in v1.10.0

func (e EntityType) String() string

type Float

type Float interface {
	~float32 | ~float64
}

Float is a constraint that permits any floating-point type. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.

type Future

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

Future is used for running a function in a separate goroutine with returning the result.

How to use:

f1 := abstract.NewFuture(ctx, slog.Default(), func(context.Context) (string, error) {
	// TODO: some code
	return "some result", nil
})

result, err := f1.Get(ctx)

func NewFuture

func NewFuture[T any](ctx context.Context, l lang.Logger, foo func(ctx context.Context) (T, error)) *Future[T]

NewFuture returns a new started future, it creates a goroutine that will run the passed function and remember it's result and error.

func (*Future[T]) Get

func (f *Future[T]) Get(ctx context.Context) (T, error)

Get will wait for the result of the underlying future or returns without it if the context is canceled.

func (*Future[T]) GetWithTimeout

func (f *Future[T]) GetWithTimeout(ctx context.Context, timeout time.Duration) (T, error)

GetWithTimeout will wait for the result of the underlying future or returns without it if the context is canceled, it also wait for the result for the provided timeout.

type Integer

type Integer interface {
	Signed | Unsigned
}

Integer is a constraint that permits any integer type. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.

type LinkedList

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

LinkedList is an implementation of a generic doubly linked list.

func NewLinkedList

func NewLinkedList[T any]() *LinkedList[T]

NewLinkedList creates a new linked list.

func (*LinkedList[T]) Back

func (l *LinkedList[T]) Back() (T, bool)

Back returns the last element of the linked list.

func (*LinkedList[T]) Front

func (l *LinkedList[T]) Front() (T, bool)

Front returns the first element of the linked list.

func (*LinkedList[T]) Len

func (l *LinkedList[T]) Len() int

Len returns the number of elements in the linked list.

func (*LinkedList[T]) PopBack

func (l *LinkedList[T]) PopBack() (T, bool)

PopBack removes an element from the back of the linked list and returns it.

func (*LinkedList[T]) PopFront

func (l *LinkedList[T]) PopFront() (T, bool)

PopFront removes an element from the front of the linked list and returns it.

func (*LinkedList[T]) PushBack added in v1.1.0

func (l *LinkedList[T]) PushBack(data T)

PushBack adds an element to the back of the linked list.

func (*LinkedList[T]) PushFront added in v1.1.0

func (l *LinkedList[T]) PushFront(data T)

PushFront adds an element to the front of the linked list.

type Map

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

Map is used like a common map.

func NewMap

func NewMap[K comparable, V any](raw ...map[K]V) *Map[K, V]

NewMap returns a Map with an empty map.

func NewMapFromPairs

func NewMapFromPairs[K comparable, V any](pairs ...any) *Map[K, V]

NewMapFromPairs returns a Map with a map inited using the provided pairs.

func NewMapWithSize

func NewMapWithSize[K comparable, V any](size int) *Map[K, V]

NewMapWithSize returns a Map with a map inited using the provided size.

func (*Map[K, V]) Change added in v1.7.0

func (m *Map[K, V]) Change(key K, f func(K, V) V)

Change changes the value for the provided key using provided function.

func (*Map[K, V]) Clear added in v1.9.0

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

Clear creates a new map using make without size.

func (*Map[K, V]) Copy

func (m *Map[K, V]) Copy() map[K]V

Copy returns another map that is a copy of the underlying map.

func (*Map[K, V]) Delete

func (m *Map[K, V]) Delete(keys ...K) (deleted bool)

Delete removes keys and associated values from the map, does nothing if the key is not present in the map, returns true if the key was deleted

func (*Map[K, V]) Get

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

Get returns the value for the provided key or the default type value if the key is not present in the map.

func (*Map[K, V]) Has

func (m *Map[K, V]) Has(key K) bool

Has returns true if the key is present in the map, false otherwise.

func (*Map[K, V]) IsEmpty

func (m *Map[K, V]) IsEmpty() bool

IsEmpty returns true if the map is empty. It is safe for concurrent/parallel use.

func (*Map[K, V]) Iter added in v1.9.0

func (m *Map[K, V]) Iter() iter.Seq2[K, V]

Iter returns an iterator over the map.

func (*Map[K, V]) IterKeys added in v1.9.0

func (m *Map[K, V]) IterKeys() iter.Seq[K]

IterKeys returns an iterator over the map keys.

func (*Map[K, V]) IterValues added in v1.9.0

func (m *Map[K, V]) IterValues() iter.Seq[V]

IterValues returns an iterator over the map values.

func (*Map[K, V]) Keys

func (m *Map[K, V]) Keys() []K

Keys returns a slice of keys of the map.

func (*Map[K, V]) Len

func (m *Map[K, V]) Len() int

Len returns the length of the map.

func (*Map[K, V]) Lookup

func (m *Map[K, V]) Lookup(key K) (V, bool)

Lookup returns the value for the provided key and true if the key is present in the map, the default value and false otherwise.

func (*Map[K, V]) Pop

func (m *Map[K, V]) Pop(key K) V

Pop returns the value for the provided key and deletes it from map or default type value if key is not present.

func (*Map[K, V]) Range

func (m *Map[K, V]) Range(f func(K, V) bool) bool

Range calls the provided function for each key-value pair in the map.

func (*Map[K, V]) Raw added in v1.8.0

func (m *Map[K, V]) Raw() map[K]V

Raw returns the underlying map.

func (*Map[K, V]) Set

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

Set sets the value to the map.

func (*Map[K, V]) SetIfNotPresent

func (m *Map[K, V]) SetIfNotPresent(key K, value V) V

SetIfNotPresent sets the value to the map if the key is not present, returns the old value if the key was set, new value otherwise.

func (*Map[K, V]) Swap

func (m *Map[K, V]) Swap(key K, value V) V

Swap swaps the values for the provided keys and returns the old value.

func (*Map[K, V]) Transform

func (m *Map[K, V]) Transform(f func(K, V) V)

Transform transforms all values of the map using provided function.

func (*Map[K, V]) Values

func (m *Map[K, V]) Values() []V

Values returns a slice of values of the map.

type Memorizer

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

Memorizer is a struct that holds a single item.

func NewMemorizer

func NewMemorizer[T any]() *Memorizer[T]

NewMemorizer returns a new Memorizer.

func (*Memorizer[T]) Get

func (m *Memorizer[T]) Get() (T, bool)

Get returns the value from the Memorizer.

func (*Memorizer[T]) Pop

func (m *Memorizer[T]) Pop() (T, bool)

Pop returns the value for the provided key and deletes it from map or default type value if key is not present.

func (*Memorizer[T]) Set

func (m *Memorizer[T]) Set(c T)

Set sets the value to the Memorizer.

type Number

type Number interface {
	Integer | Float
}

Number is a constraint that permits any numeric type.

type Ordered

type Ordered interface {
	Integer | Float | ~string
}

Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.

type OrderedPairs

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

OrderedPairs is a data structure that behaves like a map but remembers the order in which the items were added. It is also possible to get a random value or key from the structure. It allows duplicate keys. It is NOT safe for concurrent/parallel use.

The type parameter K must implement the Ordered interface.

func NewOrderedPairs

func NewOrderedPairs[K Ordered, V any](pairs ...any) *OrderedPairs[K, V]

NewOrderedPairs creates a new OrderedPairs from the provided pairs. It allows duplicate keys.

func (*OrderedPairs[K, V]) Add

func (m *OrderedPairs[K, V]) Add(key K, value V)

Add adds a key-value pair to the structure. It allows duplicate keys.

func (*OrderedPairs[K, V]) Get

func (m *OrderedPairs[K, V]) Get(key K) (res V)

Get returns the value associated with the key.

func (*OrderedPairs[K, V]) Keys

func (m *OrderedPairs[K, V]) Keys() []K

Keys returns a slice of all keys in the structure.

func (*OrderedPairs[K, V]) Rand

func (m *OrderedPairs[K, V]) Rand() V

Rand returns a random value from the structure.

func (*OrderedPairs[K, V]) RandKey

func (m *OrderedPairs[K, V]) RandKey() K

RandKey returns a random key from the structure.

type Orderer

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

Orderer is a struct that holds an order of comparable items.

func NewOrderer

func NewOrderer[T comparable](f func(order map[T]int)) *Orderer[T]

NewOrderer returns a new orderer.

func (*Orderer[T]) Add

func (m *Orderer[T]) Add(id T)

Add adds an item to the orderer.

func (*Orderer[T]) Apply

func (m *Orderer[T]) Apply()

Apply applies the order using the callback.

func (*Orderer[T]) Clear

func (m *Orderer[T]) Clear()

Clear clears the orderer.

func (*Orderer[T]) Get

func (m *Orderer[T]) Get() map[T]int

Get returns the current order.

type RateProcessor added in v1.6.0

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

RateProcessor manages a pool of workers to process tasks with a rate limit.

func NewRateProcessor added in v1.6.0

func NewRateProcessor(ctx context.Context, maxPerSecond int) *RateProcessor

NewRateProcessor initializes a new RateProcessor, that manages a pool of workers to process tasks with a rate limit.

func (*RateProcessor) AddTask added in v1.6.0

func (p *RateProcessor) AddTask(task func(context.Context) error)

AddTask adds a task to the worker pool's task queue.

func (*RateProcessor) Wait added in v1.6.0

func (p *RateProcessor) Wait() []error

Wait closes down the worker pool and waits for all workers to complete. It returns a slice of errors that occurred during task execution.

type Result added in v1.11.0

type Result struct {
	Value any
	Err   error
}

Result represents the outcome of a task execution.

type SafeEntityMap

type SafeEntityMap[K comparable, T Entity[K]] struct {
	*SafeMap[K, T]
}

SafeEntityMap is a thread-safe map of entities. It is safe for concurrent/parallel use.

func NewSafeEntityMap

func NewSafeEntityMap[K comparable, T Entity[K]](raw ...map[K]T) *SafeEntityMap[K, T]

NewSafeEntityMap returns a new SafeEntityMap from the provided map.

func NewSafeEntityMapWithSize

func NewSafeEntityMapWithSize[K comparable, T Entity[K]](size int) *SafeEntityMap[K, T]

NewSafeEntityMapWithSize returns a new SafeEntityMap with the provided size.

func (*SafeEntityMap[K, T]) AllOrdered

func (s *SafeEntityMap[K, T]) AllOrdered() []T

AllOrdered returns all values in the map sorted by their order. It is safe for concurrent/parallel use.

func (*SafeEntityMap[K, T]) ChangeOrder

func (s *SafeEntityMap[K, T]) ChangeOrder(draft map[K]int)

ChangeOrder changes the order of the values in the map based on the provided map. It is safe for concurrent/parallel use.

func (*SafeEntityMap[K, T]) Delete

func (s *SafeEntityMap[K, T]) Delete(keys ...K) (deleted bool)

Delete deletes values for the provided keys. It reorders all remaining values. It is safe for concurrent/parallel use.

func (*SafeEntityMap[K, T]) LookupByName

func (s *SafeEntityMap[K, T]) LookupByName(name string) (T, bool)

LookupByName returns the value for the provided name. It is safe for concurrent/parallel use.

func (*SafeEntityMap[K, T]) NextOrder

func (s *SafeEntityMap[K, T]) NextOrder() int

NextOrder returns the next order number. It is safe for concurrent/parallel use.

func (*SafeEntityMap[K, T]) Set

func (s *SafeEntityMap[K, T]) Set(info T) int

Set sets the value for the provided key. If the key is not present in the map, it will be added. It sets last order to the entity's order. It sets the same order of existing entity in case of conflict. It returns the order of the entity. It is safe for concurrent/parallel use.

func (*SafeEntityMap[K, T]) SetManualOrder added in v1.4.0

func (s *SafeEntityMap[K, T]) SetManualOrder(info T) int

SetManualOrder sets the value for the provided key. Better to use SafeEntityMap.Set to prevent from order errors. It returns the order of the entity. It is safe for concurrent/parallel use.

type SafeLinkedList

type SafeLinkedList[T any] struct {
	*LinkedList[T]
	// contains filtered or unexported fields
}

SafeLinkedList is a thread-safe variant of the LinkedList type. It uses a mutex to protect the underlying structure.

func NewSafeLinkedList

func NewSafeLinkedList[T any]() *SafeLinkedList[T]

NewSafeLinkedList creates a new SafeLinkedList.

func (*SafeLinkedList[T]) Back

func (l *SafeLinkedList[T]) Back() (T, bool)

Back returns the last element of the linked list. It is safe for concurrent/parallel use.

func (*SafeLinkedList[T]) Front

func (l *SafeLinkedList[T]) Front() (T, bool)

Front returns the first element of the linked list. It is safe for concurrent/parallel use.

func (*SafeLinkedList[T]) Len

func (l *SafeLinkedList[T]) Len() int

Len returns the number of elements in the linked list. It is safe for concurrent/parallel use.

func (*SafeLinkedList[T]) PopBack

func (l *SafeLinkedList[T]) PopBack() (T, bool)

PopBack removes an element from the back of the linked list and returns it. It is safe for concurrent/parallel use.

func (*SafeLinkedList[T]) PopFront

func (l *SafeLinkedList[T]) PopFront() (T, bool)

PopFront removes an element from the front of the linked list and returns it. It is safe for concurrent/parallel use.

func (*SafeLinkedList[T]) PushBack added in v1.1.0

func (l *SafeLinkedList[T]) PushBack(data T)

PushBack adds an element to the back of the linked list. It is safe for concurrent/parallel use.

func (*SafeLinkedList[T]) PushFront added in v1.1.0

func (l *SafeLinkedList[T]) PushFront(data T)

PushFront adds an element to the front of the linked list. It is safe for concurrent/parallel use.

type SafeMap

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

SafeMap is used like a common map, but it is protected with RW mutex, so it can be used in many goroutines.

func NewSafeMap

func NewSafeMap[K comparable, V any](raw ...map[K]V) *SafeMap[K, V]

NewSafeMap returns a new SafeMap with empty map.

func NewSafeMapFromPairs

func NewSafeMapFromPairs[K comparable, V any](pairs ...any) *SafeMap[K, V]

NewSafeMapFromPairs returns a SafeMap with a map inited using the provided pairs.

func NewSafeMapWithSize

func NewSafeMapWithSize[K comparable, V any](size int) *SafeMap[K, V]

NewSafeMapWithSize returns a new SafeMap with map inited using provided size.

func (*SafeMap[K, V]) Change added in v1.7.0

func (m *SafeMap[K, V]) Change(key K, f func(K, V) V)

Change changes the value for the provided key using provided function. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Clear

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

Clear creates a new map using make without size.

func (*SafeMap[K, V]) Copy

func (m *SafeMap[K, V]) Copy() map[K]V

Copy returns a new map that is a copy of the underlying map. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Delete

func (m *SafeMap[K, V]) Delete(keys ...K) (deleted bool)

Delete removes keys and associated values from map, does nothing if key is not present in map, returns true if key was deleted. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Get

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

Get returns the value for the provided key or default type value if key is not present in the map. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Has

func (m *SafeMap[K, V]) Has(key K) bool

Has returns true if key is present in the map, false otherwise. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) IsEmpty

func (m *SafeMap[K, V]) IsEmpty() bool

IsEmpty returns true if the map is empty. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Iter added in v1.9.0

func (m *SafeMap[K, V]) Iter() iter.Seq2[K, V]

Iter returns an iterator over the map. It is safe for concurrent/parallel use. DON'T USE SAFE MAP METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!

func (*SafeMap[K, V]) IterKeys added in v1.9.0

func (m *SafeMap[K, V]) IterKeys() iter.Seq[K]

IterKeys returns an iterator over the map keys. It is safe for concurrent/parallel use. DON'T USE SAFE MAP METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!

func (*SafeMap[K, V]) IterValues added in v1.9.0

func (m *SafeMap[K, V]) IterValues() iter.Seq[V]

IterValues returns an iterator over the map values. It is safe for concurrent/parallel use. DON'T USE SAFE MAP METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!

func (*SafeMap[K, V]) Keys

func (m *SafeMap[K, V]) Keys() []K

Keys returns a slice of keys of the map. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Len

func (m *SafeMap[K, V]) Len() int

Len returns the length of the map. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Lookup

func (m *SafeMap[K, V]) Lookup(key K) (V, bool)

Lookup returns the value for the provided key and true if key is present in the map, default value and false otherwise. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Pop

func (m *SafeMap[K, V]) Pop(key K) V

Pop returns the value for the provided key and deletes it from map or default type value if key is not present. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Range

func (m *SafeMap[K, V]) Range(f func(K, V) bool) bool

Range calls the provided function for each key-value pair in the map. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Raw added in v1.8.0

func (m *SafeMap[K, V]) Raw() map[K]V

Raw returns the underlying map.

func (*SafeMap[K, V]) Refill

func (m *SafeMap[K, V]) Refill(raw map[K]V)

Refill creates a new map with values from the provided one.

func (*SafeMap[K, V]) Set

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

Set sets the value to the map. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) SetIfNotPresent

func (m *SafeMap[K, V]) SetIfNotPresent(key K, value V) V

SetIfNotPresent sets the value to the map if the key is not present, returns the old value if the key was set, new value otherwise. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Swap

func (m *SafeMap[K, V]) Swap(key K, value V) V

Swap swaps the values for the provided keys and returns the old value. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Transform

func (m *SafeMap[K, V]) Transform(upd func(K, V) V)

Update updates the map using provided function. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Values

func (m *SafeMap[K, V]) Values() []V

Values returns a slice of values of the map. It is safe for concurrent/parallel use.

type SafeOrderedPairs

type SafeOrderedPairs[K Ordered, V any] struct {
	*OrderedPairs[K, V]
	// contains filtered or unexported fields
}

SafeOrderedPairs is a thread-safe variant of the OrderedPairs type. It uses a RW mutex to protect the underlying structure.

The type parameter K must implement the Ordered interface.

func NewSafeOrderedPairs

func NewSafeOrderedPairs[K Ordered, V any](pairs ...any) *SafeOrderedPairs[K, V]

NewSafeOrderedPairs returns a new SafeOrderedPairs from the provided pairs. It is a thread-safe variant of the NewOrderedPairs function.

func (*SafeOrderedPairs[K, V]) Add

func (s *SafeOrderedPairs[K, V]) Add(key K, value V)

Add adds a key-value pair to the structure. It allows duplicate keys. It is a thread-safe variant of the Add method.

func (*SafeOrderedPairs[K, V]) Get

func (s *SafeOrderedPairs[K, V]) Get(key K) (res V)

Get returns the value associated with the key. It is a thread-safe variant of the Get method.

func (*SafeOrderedPairs[K, V]) Rand

func (s *SafeOrderedPairs[K, V]) Rand() V

Rand returns a random value from the structure. It is a thread-safe variant of the Rand method.

func (*SafeOrderedPairs[K, V]) RandKey

func (s *SafeOrderedPairs[K, V]) RandKey() K

RandKey returns a random key from the structure. It is a thread-safe variant of the RandKey method.

type SafeSet

type SafeSet[K comparable] struct {
	// contains filtered or unexported fields
}

SafeSet is used like a set, but it is protected with RW mutex, so it can be used in many goroutines.

func NewSafeSet

func NewSafeSet[K comparable](data ...[]K) *SafeSet[K]

NewSafeSet returns a new SafeSet with empty set.

func NewSafeSetFromItems added in v1.3.0

func NewSafeSetFromItems[K comparable](data ...K) *SafeSet[K]

NewSafeSetFromItems returns a new SafeSet with empty set.

func NewSafeSetWithSize

func NewSafeSetWithSize[K comparable](size int) *SafeSet[K]

NewSafeSetWithSize returns a new SafeSet with empty set.

func (*SafeSet[K]) Add

func (m *SafeSet[K]) Add(key ...K)

Add adds keys to the set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Clear

func (m *SafeSet[K]) Clear()

Clear removes all keys from the set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Copy added in v1.9.0

func (m *SafeSet[K]) Copy() map[K]struct{}

Copy returns a copy of the set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Delete

func (m *SafeSet[K]) Delete(keys ...K) (deleted bool)

Delete removes keys from the set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Difference added in v1.9.0

func (m *SafeSet[K]) Difference(set map[K]struct{}) *Set[K]

Difference returns a new set with the difference of the current set and the provided set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Has

func (m *SafeSet[K]) Has(key K) bool

Has returns true if key is present in the set, false otherwise. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Intersection added in v1.9.0

func (m *SafeSet[K]) Intersection(set map[K]struct{}) *Set[K]

Intersection returns a new set with the intersection of the current set and the provided set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) IsEmpty

func (m *SafeSet[K]) IsEmpty() bool

Empty returns true if the set is empty. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Iter added in v1.9.0

func (m *SafeSet[K]) Iter() iter.Seq[K]

Iter returns a channel that yields each key in the set. It is safe for concurrent/parallel use. DON'T USE SAFE SET METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!

func (*SafeSet[K]) Len

func (m *SafeSet[K]) Len() int

Len returns the number of keys in set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Range

func (m *SafeSet[K]) Range(f func(K) bool) bool

Range calls the provided function for each key in the set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Raw added in v1.9.0

func (m *SafeSet[K]) Raw() map[K]struct{}

Raw returns the underlying map.

func (*SafeSet[K]) SymmetricDifference added in v1.9.0

func (m *SafeSet[K]) SymmetricDifference(set map[K]struct{}) *Set[K]

SymmetricDifference returns a new set with the symmetric difference of the current set and the provided set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Transform

func (m *SafeSet[K]) Transform(f func(K) K)

Transform transforms all values of the set using provided function. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Union added in v1.9.0

func (m *SafeSet[K]) Union(set map[K]struct{}) *Set[K]

Union returns a new set with the union of the current set and the provided set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Values

func (m *SafeSet[K]) Values() []K

Values returns a slice of values of the set. It is safe for concurrent/parallel use.

type SafeSlice

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

SafeSlice is used like a common slice, but it is protected with RW mutex, so it can be used in many goroutines.

func NewSafeSlice

func NewSafeSlice[T any](data ...[]T) *SafeSlice[T]

NewSafeSlice returns a new SafeSlice with empty slice.

func NewSafeSliceFromItems added in v1.3.0

func NewSafeSliceFromItems[T any](data ...T) *SafeSlice[T]

NewSafeSliceFromItems returns a new SafeSlice with the provided items.

func NewSafeSliceWithSize

func NewSafeSliceWithSize[T any](size int) *SafeSlice[T]

NewSafeSliceWithSize returns a new SafeSlice with slice inited using the provided size.

func (*SafeSlice[T]) AddFront added in v1.9.0

func (s *SafeSlice[T]) AddFront(v ...T)

AddFront adds a new elements to the front of the slice.

func (*SafeSlice[T]) Append

func (s *SafeSlice[T]) Append(v ...T)

Append adds a new element to the end of the slice.

func (*SafeSlice[T]) Change added in v1.7.0

func (s *SafeSlice[T]) Change(index int, f func(T) T)

Change changes the value for the provided key using provided function.

func (*SafeSlice[T]) Clear

func (s *SafeSlice[T]) Clear()

Clear creates a new slice using make without size.

func (*SafeSlice[T]) Copy

func (s *SafeSlice[T]) Copy() []T

Copy returns a copy of the slice.

func (*SafeSlice[T]) Delete

func (s *SafeSlice[T]) Delete(index int) bool

Delete removes the key and associated value from the slice, does nothing if the key is not present in the slice, returns true if the key was deleted.

func (*SafeSlice[T]) Get

func (s *SafeSlice[T]) Get(index int) T

Get returns the value for the provided key or the default type value if the key is not present in the slice.

func (*SafeSlice[T]) IsEmpty

func (s *SafeSlice[T]) IsEmpty() bool

IsEmpty returns true if the slice is empty. It is safe for concurrent/parallel use.

func (*SafeSlice[T]) Iter added in v1.9.0

func (s *SafeSlice[T]) Iter() iter.Seq[T]

Iter returns an iterator over the slice values. It is safe for concurrent/parallel use. DON'T USE SAFE SLICE METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!

func (*SafeSlice[T]) Iter2 added in v1.9.0

func (s *SafeSlice[T]) Iter2() iter.Seq2[int, T]

Iter2 returns an iterator over the slice values and their indexes. It is safe for concurrent/parallel use. DON'T USE SAFE SLICE METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!

func (*SafeSlice[T]) Len

func (s *SafeSlice[T]) Len() int

Len returns the length of the slice. It is safe for concurrent/parallel use.

func (*SafeSlice[T]) Pop

func (s *SafeSlice[T]) Pop() T

Pop removes the last element of the slice and returns it.

func (*SafeSlice[T]) Range

func (s *SafeSlice[T]) Range(f func(T) bool) bool

Range calls the provided function for each element in the slice.

func (*SafeSlice[T]) Raw added in v1.8.0

func (s *SafeSlice[T]) Raw() []T

Raw returns the underlying slice.

func (*SafeSlice[T]) Transform

func (s *SafeSlice[T]) Transform(f func(T) T)

Transform transforms all values of the slice using provided function.

func (*SafeSlice[T]) Truncate

func (s *SafeSlice[T]) Truncate(size int)

Truncate truncates the slice to the provided size.

type SafeStack

type SafeStack[T any] struct {
	*Stack[T]
	sync.Mutex
}

SafeStack is a simple stack data structure that is thread-safe.

func NewSafeStack

func NewSafeStack[T any](data ...[]T) *SafeStack[T]

NewSafeStack creates a new SafeStack.

func NewSafeStackWithCapacity

func NewSafeStackWithCapacity[T any](capacity int) *SafeStack[T]

NewSafeStackWithCapacity creates a new SafeStack with a specified capacity.

func (*SafeStack[T]) Clear

func (s *SafeStack[T]) Clear()

Clear removes all items from the stack.

func (*SafeStack[T]) IsEmpty

func (s *SafeStack[T]) IsEmpty() bool

IsEmpty returns true if the stack is empty.

func (*SafeStack[T]) Last

func (s *SafeStack[T]) Last() T

Last returns the last item in the stack.

func (*SafeStack[T]) Len

func (s *SafeStack[T]) Len() int

Len returns the number of items in the stack.

func (*SafeStack[T]) Pop

func (s *SafeStack[T]) Pop() T

Pop removes and returns the top item from the stack.

func (*SafeStack[T]) PopOK

func (s *SafeStack[T]) PopOK() (T, bool)

PopOK is like Pop but also returns a boolean indicating if the operation was successful.

func (*SafeStack[T]) Push

func (s *SafeStack[T]) Push(item T)

Push adds an item to the top of the stack.

func (*SafeStack[T]) Raw

func (s *SafeStack[T]) Raw() []T

Raw returns the underlying slice of the stack.

type SafeUniqueStack

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

SafeUniqueStack is a thread-safe UniqueStack.

func NewSafeUniqueStack

func NewSafeUniqueStack[T comparable](data ...[]T) *SafeUniqueStack[T]

NewSafeUniqueStack creates a new SafeUniqueStack.

func NewSafeUniqueStackWithCapacity

func NewSafeUniqueStackWithCapacity[T comparable](cap int) *SafeUniqueStack[T]

NewSafeUniqueStackWithCapacity creates a new SafeUniqueStack with a specified capacity.

func (*SafeUniqueStack[T]) Clear

func (ss *SafeUniqueStack[T]) Clear()

Clear removes all items from the stack.

func (*SafeUniqueStack[T]) IsEmpty

func (ss *SafeUniqueStack[T]) IsEmpty() bool

IsEmpty checks if the stack is empty.

func (*SafeUniqueStack[T]) Last

func (ss *SafeUniqueStack[T]) Last() T

Last returns the last item in the stack without removing it.

func (*SafeUniqueStack[T]) Len

func (ss *SafeUniqueStack[T]) Len() int

Len returns the number of items in the stack.

func (*SafeUniqueStack[T]) Pop

func (ss *SafeUniqueStack[T]) Pop() T

Pop removes and returns the last item from the stack.

func (*SafeUniqueStack[T]) PopOK

func (ss *SafeUniqueStack[T]) PopOK() (T, bool)

PopOK is like Pop but also returns a boolean indicating if the operation was successful.

func (*SafeUniqueStack[T]) Push

func (ss *SafeUniqueStack[T]) Push(item T)

Push adds an item to the stack if it is not already present.

func (*SafeUniqueStack[T]) Raw

func (ss *SafeUniqueStack[T]) Raw() []T

Raw returns a copy of the underlying data slice (non-concurrent safe operation).

func (*SafeUniqueStack[T]) Remove

func (ss *SafeUniqueStack[T]) Remove(item T) bool

Remove deletes a specific item from the stack, if it exists.

type SafeWorkerPool added in v1.11.0

type SafeWorkerPool struct {
	*WorkerPool
	// contains filtered or unexported fields
}

SafeWorkerPool is a thread-safe variant of WorkerPool.

func NewSafeWorkerPool added in v1.11.0

func NewSafeWorkerPool(workers, queueCapacity int) *SafeWorkerPool

NewSafeWorkerPool creates a new SafeWorkerPool.

func (*SafeWorkerPool) IsStopped added in v1.11.0

func (p *SafeWorkerPool) IsStopped() bool

IsStopped returns true if the worker pool has been stopped in a thread-safe manner.

func (*SafeWorkerPool) RunningWorkers added in v1.11.0

func (p *SafeWorkerPool) RunningWorkers() int

RunningWorkers returns the number of worker goroutines in a thread-safe manner.

func (*SafeWorkerPool) Start added in v1.11.0

func (p *SafeWorkerPool) Start()

Start launches the worker goroutines in a thread-safe manner.

func (*SafeWorkerPool) Stop added in v1.11.0

func (p *SafeWorkerPool) Stop()

Stop signals all workers to stop in a thread-safe manner.

func (*SafeWorkerPool) StopAndWait added in v1.11.0

func (p *SafeWorkerPool) StopAndWait(timeout time.Duration) bool

StopAndWait stops the worker pool and waits for all workers to complete in a thread-safe manner.

func (*SafeWorkerPool) Submit added in v1.11.0

func (p *SafeWorkerPool) Submit(task Task, timeout time.Duration) bool

Submit adds a task to the pool in a thread-safe manner.

func (*SafeWorkerPool) SubmitWait added in v1.11.0

func (p *SafeWorkerPool) SubmitWait(task Task, timeout time.Duration) (interface{}, error)

SubmitWait adds a task to the pool and waits for its completion in a thread-safe manner.

type Set

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

Set represents a data structure that behaves like a common map but is more lightweight. It is used to store unique keys without associated values.

func NewSet

func NewSet[K comparable](data ...[]K) *Set[K]

NewSet returns a Set inited using the provided data.

func NewSetFromItems added in v1.3.0

func NewSetFromItems[K comparable](data ...K) *Set[K]

NewSetFromItems returns a Set inited using the provided data.

func NewSetWithSize

func NewSetWithSize[K comparable](size int) *Set[K]

NewSetWithSize returns a Set with a map inited using the provided size.

func (*Set[K]) Add

func (m *Set[K]) Add(key ...K)

Add adds keys to the set.

func (*Set[K]) Clear

func (m *Set[K]) Clear()

Clear creates a new map using make without size.

func (*Set[K]) Copy added in v1.9.0

func (m *Set[K]) Copy() map[K]struct{}

Copy returns a copy of the set.

func (*Set[K]) Delete

func (m *Set[K]) Delete(keys ...K) (deleted bool)

Delete removes the keys from the set, does nothing if the key is not present in the set.

func (*Set[K]) Difference added in v1.9.0

func (m *Set[K]) Difference(set map[K]struct{}) *Set[K]

Difference returns a new set with the difference of the current set and the provided set.

func (*Set[K]) Has

func (m *Set[K]) Has(key K) bool

Has returns true if the key is present in the set, false otherwise.

func (*Set[K]) Intersection added in v1.9.0

func (m *Set[K]) Intersection(set map[K]struct{}) *Set[K]

Intersection returns a new set with the intersection of the current set and the provided set.

func (*Set[K]) IsEmpty

func (m *Set[K]) IsEmpty() bool

IsEmpty returns true if the set is empty. It is safe for concurrent/parallel use.

func (*Set[K]) Iter added in v1.9.0

func (m *Set[K]) Iter() iter.Seq[K]

Iter returns a channel that yields each key in the set.

func (*Set[K]) Len

func (m *Set[K]) Len() int

Len returns the length of the set.

func (*Set[K]) Range

func (m *Set[K]) Range(f func(K) bool) bool

Range calls the provided function for each key in the set.

func (*Set[K]) Raw added in v1.9.0

func (m *Set[K]) Raw() map[K]struct{}

Raw returns the underlying map.

func (*Set[K]) SymmetricDifference added in v1.9.0

func (m *Set[K]) SymmetricDifference(set map[K]struct{}) *Set[K]

SymmetricDifference returns a new set with the symmetric difference of the current set and the provided set.

func (*Set[K]) Transform

func (m *Set[K]) Transform(f func(K) K)

Transform transforms all values of the set using provided function.

func (*Set[K]) Union added in v1.9.0

func (m *Set[K]) Union(set map[K]struct{}) *Set[K]

Union returns a new set with the union of the current set and the provided set.

func (*Set[K]) Values

func (m *Set[K]) Values() []K

Keys returns a slice of keys of the set.

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

Signed is a constraint that permits any signed integer type. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.

type Slice

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

Slice is used like a common slice.

func NewSlice

func NewSlice[T any](data ...[]T) *Slice[T]

NewSlice returns a new Slice with empty slice.

func NewSliceFromItems added in v1.3.0

func NewSliceFromItems[T any](data ...T) *Slice[T]

NewSliceFromItems returns a new Slice with the provided items.

func NewSliceWithSize

func NewSliceWithSize[T any](size int) *Slice[T]

NewSliceWithSize returns a new Slice with slice inited using the provided size.

func (*Slice[T]) AddFront added in v1.9.0

func (s *Slice[T]) AddFront(v ...T)

AddFront adds a new elements to the front of the slice.

func (*Slice[T]) Append

func (s *Slice[T]) Append(v ...T)

Append adds a new element to the end of the slice.

func (*Slice[T]) Change added in v1.7.0

func (s *Slice[T]) Change(index int, f func(T) T)

Change changes the value for the provided key using provided function.

func (*Slice[T]) Clear

func (s *Slice[T]) Clear()

Clear creates a new slice using make without size.

func (*Slice[T]) Copy

func (s *Slice[T]) Copy() []T

Copy returns a copy of the slice.

func (*Slice[T]) Delete

func (s *Slice[T]) Delete(index int) bool

Delete removes the key and associated value from the slice, does nothing if the key is not present in the slice, returns true if the key was deleted.

func (*Slice[T]) Get

func (s *Slice[T]) Get(index int) T

Get returns the value for the provided key or the default type value if the key is not present in the slice.

func (*Slice[T]) IsEmpty

func (s *Slice[T]) IsEmpty() bool

IsEmpty returns true if the slice is empty. It is safe for concurrent/parallel use.

func (*Slice[T]) Iter added in v1.9.0

func (s *Slice[T]) Iter() iter.Seq[T]

Iter returns an iterator over the slice values.

func (*Slice[T]) Iter2 added in v1.9.0

func (s *Slice[T]) Iter2() iter.Seq2[int, T]

Iter2 returns an iterator over the slice values and their indexes.

func (*Slice[T]) Len

func (s *Slice[T]) Len() int

Len returns the length of the slice.

func (*Slice[T]) Pop

func (s *Slice[T]) Pop() T

Pop removes the last element of the slice and returns it.

func (*Slice[T]) Range

func (s *Slice[T]) Range(f func(T) bool) bool

Range calls the provided function for each element in the slice.

func (*Slice[T]) Raw added in v1.8.0

func (s *Slice[T]) Raw() []T

Raw returns the underlying slice.

func (*Slice[T]) Transform

func (s *Slice[T]) Transform(f func(T) T)

Transform transforms all values of the slice using provided function.

func (*Slice[T]) Truncate

func (s *Slice[T]) Truncate(size int)

Truncate truncates the slice to the provided size.

type Stack

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

Stack is a simple stack data structure.

func NewStack

func NewStack[T any](data ...[]T) *Stack[T]

NewStack creates a new Stack.

func NewStackWithCapacity

func NewStackWithCapacity[T any](capacity int) *Stack[T]

NewStackWithCapacity creates a new Stack with a specified capacity.

func (*Stack[T]) Clear

func (s *Stack[T]) Clear()

Clear removes all items from the stack.

func (*Stack[T]) IsEmpty

func (s *Stack[T]) IsEmpty() bool

IsEmpty returns true if the stack is empty.

func (*Stack[T]) Last

func (s *Stack[T]) Last() T

Last returns the last item in the stack.

func (*Stack[T]) Len

func (s *Stack[T]) Len() int

Len returns the number of items in the stack.

func (*Stack[T]) Pop

func (s *Stack[T]) Pop() T

Pop removes and returns the top item from the stack.

func (*Stack[T]) PopOK

func (s *Stack[T]) PopOK() (T, bool)

PopOK is like Pop but also returns a boolean indicating if the operation was successful.

func (*Stack[T]) Push

func (s *Stack[T]) Push(item T)

Push adds an item to the top of the stack.

func (*Stack[T]) Raw

func (s *Stack[T]) Raw() []T

Raw returns the underlying slice of the stack.

type Task added in v1.11.0

type Task func() (any, error)

Task represents a function that can be executed by workers in the pool.

type Timer

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

Timer is used to calculate time intervals.

func Deadline added in v1.11.0

func Deadline(duration time.Duration) Timer

Deadline creates a new timer with a deadline set to the specified duration from now.

func StartTimer

func StartTimer() Timer

StartTimer starts a new Timer at the current moment of time.

func (Timer) ElapsedHours added in v1.11.0

func (t Timer) ElapsedHours() float64

ElapsedHours returns the time interval since Timer starting, accounting for any paused time.

func (Timer) ElapsedMicroseconds added in v1.11.0

func (t Timer) ElapsedMicroseconds() int64

ElapsedMicroseconds returns the time interval since Timer starting, accounting for any paused time.

func (Timer) ElapsedMilliseconds added in v1.11.0

func (t Timer) ElapsedMilliseconds() int64

ElapsedMilliseconds returns the time interval since Timer starting, accounting for any paused time.

func (Timer) ElapsedMinutes added in v1.11.0

func (t Timer) ElapsedMinutes() float64

ElapsedMinutes returns the time interval since Timer starting, accounting for any paused time.

func (Timer) ElapsedNanoseconds added in v1.11.0

func (t Timer) ElapsedNanoseconds() int64

ElapsedNanoseconds returns the time interval since Timer starting, accounting for any paused time.

func (Timer) ElapsedSeconds added in v1.11.0

func (t Timer) ElapsedSeconds() float64

ElapsedSeconds returns the time interval since Timer starting, accounting for any paused time.

func (Timer) ElapsedTime

func (t Timer) ElapsedTime() time.Duration

ElapsedTime returns the time interval since Timer starting, accounting for any paused time.

func (Timer) Format added in v1.11.0

func (t Timer) Format(layout string) string

Format returns the elapsed time formatted according to the given layout. Common layouts: "15:04:05", "04:05.000", etc.

func (Timer) FormatShort added in v1.11.0

func (t Timer) FormatShort() string

FormatShort returns a human-readable string representation of the elapsed time.

func (Timer) HasElapsed added in v1.11.0

func (t Timer) HasElapsed(duration time.Duration) bool

HasElapsed checks if the specified duration has elapsed since the timer started.

func (Timer) IsExpired added in v1.11.0

func (t Timer) IsExpired() bool

IsExpired returns true if the deadline has passed. If no deadline is set, it returns false.

func (Timer) IsPaused added in v1.11.0

func (t Timer) IsPaused() bool

IsPaused returns whether the timer is currently paused.

func (*Timer) Lap added in v1.11.0

func (t *Timer) Lap() time.Duration

Lap records the current time as a lap and returns the lap duration.

func (Timer) LapDurations added in v1.11.0

func (t Timer) LapDurations() []time.Duration

LapDurations returns the durations between consecutive laps. The first duration is measured from the start time.

func (Timer) Laps added in v1.11.0

func (t Timer) Laps() []time.Time

Laps returns all recorded lap times.

func (*Timer) Pause added in v1.11.0

func (t *Timer) Pause() bool

Pause pauses the timer. Subsequent calls to ElapsedTime will not include time after the pause. Returns false if the timer is already paused.

func (*Timer) Reset added in v1.11.0

func (t *Timer) Reset()

Reset resets the timer to the current time and clears all laps and pause history.

func (*Timer) Resume added in v1.11.0

func (t *Timer) Resume() bool

Resume resumes the timer if it was paused. Returns false if the timer was not paused.

func (*Timer) SetDeadline added in v1.11.0

func (t *Timer) SetDeadline(deadline time.Time)

SetDeadline sets a deadline for the timer.

func (*Timer) SetDeadlineDuration added in v1.11.0

func (t *Timer) SetDeadlineDuration(duration time.Duration)

SetDeadlineDuration sets a deadline relative to the current time.

func (Timer) Time

func (t Timer) Time() time.Time

Time returns the startup time.

func (Timer) TimeRemaining added in v1.11.0

func (t Timer) TimeRemaining() time.Duration

TimeRemaining returns the time remaining until the deadline. If no deadline is set or the deadline has passed, it returns zero duration.

type UniqueStack

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

UniqueStack is a stack that doesn't allow duplicates.

func NewUniqueStack

func NewUniqueStack[T comparable](data ...[]T) *UniqueStack[T]

NewUniqueStack creates a new UniqueStack.

func NewUniqueStackWithCapacity

func NewUniqueStackWithCapacity[T comparable](cap int) *UniqueStack[T]

NewUniqueStackWithCapacity creates a new UniqueStack with a specified capacity.

func (*UniqueStack[T]) Clear

func (s *UniqueStack[T]) Clear()

Clear removes all items from the stack.

func (*UniqueStack[T]) IsEmpty

func (s *UniqueStack[T]) IsEmpty() bool

IsEmpty returns true if the stack is empty.

func (*UniqueStack[T]) Last

func (s *UniqueStack[T]) Last() T

Last returns the last item in the stack.

func (*UniqueStack[T]) Len

func (s *UniqueStack[T]) Len() int

Len returns the number of items in the stack.

func (*UniqueStack[T]) Pop

func (s *UniqueStack[T]) Pop() T

Pop removes the last item from the stack and returns it.

func (*UniqueStack[T]) PopOK

func (s *UniqueStack[T]) PopOK() (T, bool)

PopOK is like Pop, but returns a boolean indicating whether the stack was empty.

func (*UniqueStack[T]) Push

func (s *UniqueStack[T]) Push(item T)

Push adds an item to the stack. If the item is already present in the stack, it moves it to the top of the stack.

func (*UniqueStack[T]) Raw

func (s *UniqueStack[T]) Raw() []T

Raw returns the underlying slice of the stack.

func (*UniqueStack[T]) Remove

func (s *UniqueStack[T]) Remove(item T) bool

Remove removes an item from the stack.

type Unsigned

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Unsigned is a constraint that permits any unsigned integer type. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.

type Waiter

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

Waiter is used for running a function in a separate goroutine with returning the error.

How to use:

w := abstract.NewWaiter(ctx, slog.Default(), func(context.Context) error {
	// TODO: some code
	return nil
})

err := w.Await(ctx)

func NewWaiter

func NewWaiter(ctx context.Context, l lang.Logger, foo func(context.Context) error) *Waiter

NewFutureVoid returns a new started void future, it creates a goroutine that will run the passed function and remember it's error.

func (*Waiter) Await

func (f *Waiter) Await(ctx context.Context) error

Await will wait for the result of the underlying future or returns without it if the context is canceled.

func (*Waiter) AwaitWithTimeout

func (f *Waiter) AwaitWithTimeout(ctx context.Context, timeout time.Duration) error

AwaitWithTimeout will wait for the result of the underlying future or returns without it if the context is canceled, it also wait for the result for the provided timeout.

type WaiterSet

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

WaiterSet is used for running many functions, each in a separate goroutine with returning a combined error.

How to use:

ws := abstract.NewWaiterSet(slog.Default())
ws.Add(ctx, func(context.Context) error {
	// TODO: some code 1
	return nil
})
ws.Add(ctx, func(context.Context) error {
	// TODO: some code 2
	return nil
})

err := ws.Await(ctx) // Wait for completion of all added functions

func NewWaiterSet

func NewWaiterSet(l lang.Logger, ws ...*Waiter) *WaiterSet

NewWaiterSet returns new WaiterSet with added Waiter, that were started earlier.

func (*WaiterSet) Add

func (s *WaiterSet) Add(ctx context.Context, foo func(ctx context.Context) error)

Add adds a new Waiter to the WaiterSet and starts it in a separate goroutine.

func (*WaiterSet) Await

func (s *WaiterSet) Await(ctx context.Context) error

Await will wait for the result of all underlying functions or returns without it if the context is canceled.

func (*WaiterSet) AwaitWithTimeout

func (s *WaiterSet) AwaitWithTimeout(ctx context.Context, timeout time.Duration) error

AwaitWithTimeout will wait for the result of all underlying functions or returns without it if the context is canceled, it also wait for the result for the provided timeout.

type WorkerPool added in v1.11.0

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

WorkerPool manages a pool of workers that process tasks concurrently.

func NewWorkerPool added in v1.11.0

func NewWorkerPool(workers, queueCapacity int) *WorkerPool

NewWorkerPool creates a new worker pool with the specified number of workers and task queue capacity.

func (*WorkerPool) IsStopped added in v1.11.0

func (p *WorkerPool) IsStopped() bool

IsStopped returns true if the worker pool has been stopped.

func (*WorkerPool) Results added in v1.11.0

func (p *WorkerPool) Results() <-chan Result

Results returns the channel that receives results from completed tasks.

func (*WorkerPool) RunningWorkers added in v1.11.0

func (p *WorkerPool) RunningWorkers() int

RunningWorkers returns the number of worker goroutines.

func (*WorkerPool) Start added in v1.11.0

func (p *WorkerPool) Start()

Start launches the worker goroutines.

func (*WorkerPool) Stop added in v1.11.0

func (p *WorkerPool) Stop()

Stop signals all workers to stop after completing their current tasks. It does not wait for them to complete.

func (*WorkerPool) StopAndWait added in v1.11.0

func (p *WorkerPool) StopAndWait(timeout time.Duration) bool

StopAndWait stops the worker pool and waits for all workers to complete. It returns true if workers completed within the timeout, false otherwise.

func (*WorkerPool) Submit added in v1.11.0

func (p *WorkerPool) Submit(task Task, timeout time.Duration) bool

Submit adds a task to the pool and returns true if the task was accepted. Returns false if the pool is stopped or the task queue is full and the timeout is reached.

func (*WorkerPool) SubmitWait added in v1.11.0

func (p *WorkerPool) SubmitWait(task Task, timeout time.Duration) (any, error)

SubmitWait adds a task to the pool and waits for its completion, returning the result. If the timeout is reached before the task can be submitted or completed, it returns an error.

func (*WorkerPool) Wait added in v1.11.0

func (p *WorkerPool) Wait()

Wait blocks until all workers have completed their tasks. This should only be called after Stop() or when all tasks have been submitted.

Jump to

Keyboard shortcuts

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