generics

package module
v0.0.0-...-ec24cc8 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2023 License: Apache-2.0 Imports: 20 Imported by: 0

README

Generics playground

This repository should not be used at all. It just contains my experiments with generics.

Notes:

"Do you want slow programmers, slow compilers and bloated binaries, or slow execution times?" (Russ Cox)

Let's say result is nil, then you will have to write : is.Equal(result, []int(nil)).

Sometimes, you need to return ugly things like return *new(T), false, just because you are passing strings to your generic functions.

You have to deref results when your generic function has to return pointers, like in the pattern (*T, error).

There is no way to both support predeclared types AND support user defined types.

It would be great to have:

type Swapper[T comparable] interface {
    Swap(i, j int)
}

type Ordered[T comparable] interface {
  constraints.Ordered | Swapper[T]
}

Implementation restriction: A union (with more than one term) cannot contain the predeclared identifier comparable or interfaces that specify methods, or embed comparable or interfaces that specify methods.

And the conclusions from here

Documentation

Overview

Example
bus := NewPubSub[greetingMessage](DefaultPublishChannelBufferSize) // the topic with a type which you want to publish and subscribe.

ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})

go func() {
	if err := bus.Start(ctx); err != nil { // Start the topic. This call of Start blocks until the context is canceled.
		println(err)
		return
	}

	done <- struct{}{}
}()

if err := bus.Dispatch(greetingMessage{greeting: "Hello, Badu!"}); err != nil { // Dispatch a message to the topic. This call of Dispatch is non-blocking.
	println(err)
	return
}

// Listen the topic. This call of Listen is non-blocking.
err := bus.Listen(DefaultSubscribeChannelBufferSize, func(message greetingMessage) {
	println(message.greeting)
})
if err != nil {
	println(err)
	return
}

cancel()
<-done
Output:

Index

Examples

Constants

View Source
const (
	NeverExpire   time.Duration = -1
	DefaultExpire time.Duration = 0
)
View Source
const (
	DefaultPublishChannelBufferSize   = 100
	DefaultSubscribeChannelBufferSize = 100
)

Variables

View Source
var (
	ErrAlreadyStarted = errors.New("this topic has been already started")
	ErrNotRunning     = errors.New("this topic has been already closed")
)
View Source
var ErrNotDone = errors.New("not done")

Functions

func Common

func Common[T comparable](source1 []T, source2 []T) []T

Common returns the intersection between two slices.

func Count

func Count[T comparable](source []T, value T) (count int)

Count counts the number of elements in the slice that compare equal to value.

func CountWhere

func CountWhere[T any](source []T, fn func(T) bool) (count int)

CountWhere counts the number of elements in the slice for which callback is true.

func DelayedInvoke

func DelayedInvoke(times int, delay time.Duration, fn func(int, time.Duration) error) (int, time.Duration, error)

DelayedInvoke invokes a function N times until it returns valid output, with a pause between each call. Returning either the caught error or nil. When first argument is less than `1`, the function runs until a successful response is returned.

func Diff

func Diff[T comparable](source1 []T, source2 []T) ([]T, []T)

Diff returns the difference between two slices. The first return is the slice of elements absent of source1. The second return is the slice of elements absent of source2.

func Drop

func Drop[T any](source []T, n int) []T

Drop drops n elements from the beginning of a slice or slice.

func DropRight

func DropRight[T any](source []T, n int) []T

DropRight drops n elements from the end of a slice or slice.

func DropRightWhile

func DropRightWhile[T any](source []T, fn func(T) bool) []T

DropRightWhile drops elements from the end of a slice or slice while the callback returns true.

func DropWhile

func DropWhile[T any](source []T, fn func(T) bool) []T

DropWhile drops elements from the beginning of a slice or slice while the callback returns true.

func Fill

func Fill[T Clonable[T]](source []T, defaults T) []T

Fill fills elements of slice with `defaults` values.

func Filter

func Filter[V any](source []V, fn func(V, int) bool) []V

Filter iterates over elements of slice, returning a slice of all elements callback returns truthy for.

func FilterMap

func FilterMap[K comparable, V any](source map[K]V, fn func(K, V) bool) map[K]V

FilterMap returns same map type filtered by given callback.

func FilterWhereKeys

func FilterWhereKeys[K comparable, V any](source map[K]V, keys []K) map[K]V

FilterWhereKeys returns same map type filtered by given keys.

func FilterWhereValues

func FilterWhereValues[K comparable, V comparable](source map[K]V, values []V) map[K]V

FilterWhereValues returns same map type filtered by given values.

func Find

func Find[T comparable](source []*T, fn func(*T) bool) (*T, bool)

Find search an element in a slice based on a callback. It returns element and true if element was found.

func FindString

func FindString[T comparable](source []T, fn func(T) bool) (T, bool)

FindString search an element in a slice based on a callback. It returns element and true if element was found.

func FirstIndexOf

func FirstIndexOf[T comparable](source []*T, el T) int

FirstIndexOf returns the index at which the first occurrence of a value is found in a slice or return -1 if the value cannot be found.

func FlatMap

func FlatMap[T, R any](source []T, fn func(T, int) []R) []R

FlatMap manipulates a slice and transforms and flattens it.

func Flatten

func Flatten[T any](source [][]T) []T

Flatten returns a slice a single level deep.

func FromEntries

func FromEntries[K comparable, V any](source []Entry[K, V]) map[K]V

FromEntries transforms an array of key/value pairs into a map.

func GroupWhere

func GroupWhere[T any, U comparable](source []T, fn func(T) U) map[U][]T

GroupWhere returns an object composed of keys generated from the results of running each element of slice.

func Has

func Has[T comparable](slice []T, element T) bool

Has returns true if an element is present in a slice.

func HasWhere

func HasWhere[T any](slice []T, fn func(T) bool) bool

HasWhere returns true if callback function return true.

func Hash

func Hash[T comparable](value T) uint32

Hash returns a 32 bit unsigned integer hash for any value passed in

func HashBytes

func HashBytes(b []byte) uint32

HashBytes returns a 32 bit unsigned integer hash of the passed byte slice

func Included

func Included[T comparable](slice []T, other []T) bool

Included returns true if all elements of a subset are contained into a slice or if the subset is empty.

func IncludedWhere

func IncludedWhere[V any](slice []V, fn func(V) bool) bool

IncludedWhere returns true if the callback returns true for all of the elements in the slice or if the slice is empty.

func IncludesOne

func IncludesOne[T comparable](slice []T, other []T) bool

IncludesOne returns true if at least 1 element of a subset is contained into a slice.

func IncludesOneWhere

func IncludesOneWhere[V any](slice []V, fn func(V) bool) bool

IncludesOneWhere returns true if the callback returns true for any of the elements in the slice.

func Indexes

func Indexes[T comparable](source []*T, el T) []int

Indexes returns the indexes at which the last occurrence of a value is found in a slice

func Invoke

func Invoke(times int, fn func(int) error) (int, error)

Invoke invokes a function N times until it returns valid output. Returning either the caught error or nil. When first argument is less than `1`, the function runs until a successful response is returned.

func KeyWhere

func KeyWhere[K comparable, V any](source []V, fn func(V) K) map[K]V

KeyWhere transforms a slice or a slice of structs to a map based on a pivot callback.

func Keys

func Keys[K comparable, V any](source map[K]V) []K

Keys creates an array of the map keys.

func LastIndexOf

func LastIndexOf[T comparable](source []*T, el T) int

LastIndexOf returns the index at which the last occurrence of a value is found in a slice or return -1 if the value cannot be found.

func Map

func Map[T, R any](source []T, fn func(T, int) R) []R

Map manipulates a slice and transforms it to a slice of another type.

func MapKeys

func MapKeys[K comparable, V any, R comparable](source map[K]V, fn func(V, K) R) map[R]V

MapKeys manipulates a map keys and transforms it to a map of another type.

func MapValues

func MapValues[K comparable, V any, R any](source map[K]V, fn func(V, K) R) map[K]R

MapValues manipulates a map values and transforms it to a map of another type.

func MapWhere

func MapWhere[T, R any](source []T, fn func(T, int) (R, bool)) []R

MapWhere returns a slice which obtained after both filtering and mapping using the given callback function.

func Max

func Max[T constraints.Ordered](source []T) T

Max searches the maximum value of a slice.

func MaxWhere

func MaxWhere[T any](source []T, fn func(T, T) bool) T

MaxWhere search the maximum value of a slice using the given comparison function. If several values of the slice are equal to the greatest value, returns the first such value.

func Merge

func Merge[K comparable, V any](sources ...map[K]V) map[K]V

Merge merges multiple maps from left to right.

func Min

func Min[T constraints.Ordered](source []T) T

Min search the minimum value of a slice.

func MinWhere

func MinWhere[T any](source []T, fn func(T, T) bool) T

MinWhere search the minimum value of a slice using the given comparison function. If several values of the slice are equal to the smallest value, returns the first such value.

func NewDebounce

func NewDebounce(delay time.Duration, fns ...func()) (func(), func())

NewDebounce creates a debounced instance that delays invoking functions given until after wait milliseconds have elapsed.

func NotIncludes

func NotIncludes[V comparable](slice []V, subset []V) bool

NotIncludes returns true if no element of a subset are contained into a slice or if the subset is empty.

func NotIncludesWhere

func NotIncludesWhere[V any](slice []V, fn func(V) bool) bool

NotIncludesWhere returns true if the callback returns true for none of the elements in the slice or if the slice is empty.

func NumericFirstIndexOf

func NumericFirstIndexOf[T comparable](source []T, el T) int

NumericFirstIndexOf returns the index at which the first occurrence of a value is found in a slice or return -1 if the value cannot be found.

func NumericIndexes

func NumericIndexes[T comparable](source []T, el T) []int

NumericIndexes returns the indexes at which the last occurrence of a value is found in a slice

func NumericLastIndexOf

func NumericLastIndexOf[T comparable](source []T, el T) int

NumericLastIndexOf returns the index at which the last occurrence of a value is found in a slice or return -1 if the value cannot be found.

func ParallelDo

func ParallelDo[T any](count int, fn func(int) T) []T

ParallelDo invokes the callback n times, returning a slice of the results of each invocation.

func ParallelForEach

func ParallelForEach[T any](slice []T, fn func(T, int))

ParallelForEach iterates over elements of slice and invokes callback for each element.

func ParallelGroupWhere

func ParallelGroupWhere[T any, U comparable](slice []T, fn func(T) U) map[U][]T

ParallelGroupWhere returns an object composed of keys generated from the results of running each element of slice through callback.

func ParallelMap

func ParallelMap[T any, R any](collection []T, iteratee func(T, int) R) []R

ParallelMap manipulates a slice and transforms it to a slice of another type. `iteratee` is call in parallel. Resolve keep the same order.

func ParallelPartitionWhere

func ParallelPartitionWhere[T any, K comparable](slice []T, fn func(x T) K) [][]T

ParallelPartitionWhere returns a slice of elements split into groups. The order of grouped values is determined by the order they occur in slice. The grouping is generated from the results of running each element of slice through callback. `callback` is call in parallel.

func Partition

func Partition[T any](source []T, size int) ([][]T, error)

Partition returns a slice of elements split into groups the length of size. If slice can't be split evenly, the final chunk will be the remaining elements.

func PartitionWhere

func PartitionWhere[T any, K comparable](source []T, fn func(x T) K) [][]T

PartitionWhere returns a slice of elements split into groups. The order of grouped values is determined by the order they occur in slice. The grouping is generated from the results of running each element of slice through callback.

func Permutations

func Permutations[T any](source []T) ([][]T, error)

Permutations returns all permutations of the slice's elements.

func Produce

func Produce[T any](count int, fn func(int) T) []T

Produce invokes the callback n times, returning a slice of the results of each invocation.

func Reduce

func Reduce[T comparable, R any](source []T, fn func(R, T, int) R, result R) R

Reduce reduces slice to a value which is the accumulated result of running each element in slice through a function, where each successive invocation is supplied the return value of the previous.

func Reject

func Reject[V any](source []V, fn func(V, int) bool) []V

Reject is the opposite of Filter, this method returns the elements of slice that callback does not return truthy for.

func Repeat

func Repeat[T Clonable[T]](count int, initial T) []T

Repeat builds a slice with N copies of initial value.

func RepeatWhere

func RepeatWhere[T any](count int, fn func(int) T) []T

RepeatWhere builds a slice with values returned by N calls of callback.

func Replace

func Replace[T comparable](source []T, old T, new T, n int) []T

Replace returns a copy of the slice with the first n non-overlapping instances of old replaced by new.

func ReplaceAll

func ReplaceAll[T comparable](source []T, old T, new T) []T

ReplaceAll returns a copy of the slice with all non-overlapping instances of old replaced by new.

func Reverse

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

Reverse reverses slice so that the first element becomes the last, the second element becomes the second to last, and so on.

func Shuffle

func Shuffle[T any](source []T) []T

Shuffle returns a slice of shuffled values. Uses the Fisher-Yates shuffle algorithm.

func Subset

func Subset[T any](source []T, offset int, length uint) []T

Subset return part of a slice.

func SwapKeyValue

func SwapKeyValue[K comparable, V comparable](source map[K]V) map[V]K

SwapKeyValue creates a map composed of the inverted keys and values. If map contains duplicate values, of course, subsequent values will overwrite property assignments of previous values.

func Union

func Union[T comparable](source1, source2 []T) []T

Union returns all distinct elements from both slices. Resolve DOES NOT change the order of elements relatively.

func Unique

func Unique[T comparable](source []T) []T

Unique returns a duplicate-free version of a slice, in which only the first occurrence of each element is kept, while preserving the order in which they occur in the slice.

func UniqueWhere

func UniqueWhere[T any, U comparable](source []T, fn func(T) U) []T

UniqueWhere returns a duplicate-free version of a slice, in which only the FIRST occurrence of each element is kept, while preserving the order in which they occur in the slice.

func Value

func Value[T any](ctx context.Context) (T, bool)

func Values

func Values[K comparable, V any](source map[K]V) []V

Values creates an array of the map values.

func Wait

func Wait(ws ...Waiter) error

func WhereElse

func WhereElse[T any](source []T, fallback T, fn func(T) bool) *T

WhereElse search an element in a slice based on a callback. It returns the element if found or a given fallback value otherwise.

func WhereFirst

func WhereFirst[T any](source []T, fn func(T) bool) (T, int, bool)

WhereFirst searches an element in a slice based on a callback and returns the index and true. It returns -1 and false if the element is not found.

func WhereLast

func WhereLast[T any](source []T, fn func(T) bool) (*T, int, bool)

WhereLast searches last element in a slice based on a callback and returns the index and true. It returns -1 and false if the element is not found.

func WithValue

func WithValue[T any](ctx context.Context, value T) context.Context

Types

type BinaryHeap

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

BinaryHeap is the main heap type.

func NewBinaryHeap

func NewBinaryHeap[T comparable](predicate func(a, b T) bool, capacity ...int) BinaryHeap[T]

NewBinaryHeap is used to create a new heap. The passed function is a predicate that returns true if the first parameter is greater than the second. This predicate defines the sorting order between the heap items and is called during insertion and extraction.

func (*BinaryHeap[T]) Clear

func (b *BinaryHeap[T]) Clear()

Clear empties the entire heap.

func (*BinaryHeap[T]) Count

func (b *BinaryHeap[T]) Count() int

Count returns the amount of entries in the heap.

func (*BinaryHeap[T]) Empty

func (b *BinaryHeap[T]) Empty() bool

Empty returns true if the heap is empty, false if not.

func (*BinaryHeap[T]) ForEach

func (b *BinaryHeap[T]) ForEach(predicate func(val T))

ForEach iterates over the dataset within the heap, calling the passed function for each value.

func (*BinaryHeap[T]) Has

func (b *BinaryHeap[T]) Has(val T) bool

Has returns true if the value exists in the heap, false if not.

func (*BinaryHeap[T]) Peek

func (b *BinaryHeap[T]) Peek() T

Peek returns the first value at the top of the heap.

func (*BinaryHeap[T]) Pop

func (b *BinaryHeap[T]) Pop() *T

Pop returns and removes the first value from the heap.

func (*BinaryHeap[T]) Push

func (b *BinaryHeap[T]) Push(val T)

Push inserts a new value into the heap.

type Cache

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

func NewCache

func NewCache[T any](expiration, cleanup time.Duration) *Cache[T]

func NewCacheFrom

func NewCacheFrom[T any](defaultExpiration, cleanupInterval time.Duration, objectsMap map[string]CacheObject[T]) *Cache[T]

func (Cache) CleanExpired

func (c Cache) CleanExpired()

CleanExpired all expired objects from the cache.

func (Cache) Delete

func (c Cache) Delete(key string)

Delete an object from the cache. Does nothing if the key is not in the cache.

func (Cache) Flush

func (c Cache) Flush()

Flush flushes the cache

func (Cache) GetWithExpiration

func (c Cache) GetWithExpiration(key string) (T, time.Time, bool)

GetWithExpiration returns an object and its expiration time from the cache. It returns the object or nil, the expiration time if one is set (if the object never expires a zero value for time.Time is returned), and a bool indicating whether the key was found.

func (Cache) Load

func (c Cache) Load(r io.Reader) error

Load fills the cache from io.Reader

func (Cache) LoadFile

func (c Cache) LoadFile(filename string) error

LoadFile fills the cache from a file

func (Cache) Objects

func (c Cache) Objects() map[string]CacheObject[T]

Objects lists all objects in the cache

func (Cache) ObjectsCount

func (c Cache) ObjectsCount() int

ObjectsCount returns the number of cached objects

func (Cache) OnBeforeDeletion

func (c Cache) OnBeforeDeletion(hook func(string, T))

OnBeforeDeletion registers a function to be called before eviction

func (Cache) Read

func (c Cache) Read(key string) (T, bool)

Read an object from the cache. Returns the item or nil, and a bool indicating whether the key was found.

func (Cache) Replace

func (c Cache) Replace(key string, object T, d time.Duration) error

Replace a new value for the cache key only if it already exists, and the existing object hasn't expired. Returns an error otherwise.

func (Cache) Save

func (c Cache) Save(w io.Writer) error

Save everything in cache to an io.Writer, in gob encoding format

func (Cache) SaveFile

func (c Cache) SaveFile(filename string) error

SaveFile saves cache content to a file

func (Cache) Set

func (c Cache) Set(key string, object T, defaultExpiration time.Duration)

Set an object to the cache, replacing any existing object

func (Cache) SetWithDefault

func (c Cache) SetWithDefault(key string, object T)

SetWithDefault adds an object to the cache, replacing any existing item, using the default expiration value.

func (Cache) Store

func (c Cache) Store(key string, object T, d time.Duration) error

Store an object to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. Returns an error otherwise.

type CacheObject

type CacheObject[T any] struct {
	Expiration int64
	Value      T
}

func (*CacheObject[T]) Expired

func (item *CacheObject[T]) Expired() bool

type Clonable

type Clonable[T any] interface {
	Clone() T
}

Clonable defines a constraint of types having Clone() T method.

type Entry

type Entry[K comparable, V any] struct {
	Key   K
	Value V
}

Entry defines a key/value pairs.

func ToEntries

func ToEntries[K comparable, V any](source map[K]V) []Entry[K, V]

ToEntries transforms a map into array of key/value pairs.

type HashMap

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

HashMap is the main hash map type.

func NewHashMap

func NewHashMap[K, V comparable]() HashMap[K, V]

NewHashMap is used to create a new map.

func (*HashMap[K, V]) Clear

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

Clear empties the entire hash map.

func (*HashMap[K, V]) ContainsKey

func (m *HashMap[K, V]) ContainsKey(key K) bool

ContainsKey returns true if the passed key is present, false if not.

func (*HashMap[K, V]) ContainsValue

func (m *HashMap[K, V]) ContainsValue(val V) bool

ContainsValue returns true if the passed value is present, false if not.

func (*HashMap[K, V]) Count

func (m *HashMap[K, V]) Count() int

Count returns the amount of entries in the map.

func (*HashMap[K, V]) Empty

func (m *HashMap[K, V]) Empty() bool

Empty returns true if the map is empty, false if not.

func (*HashMap[K, V]) ForEach

func (m *HashMap[K, V]) ForEach(f func(key K, val V))

ForEach iterates over the dataset within the hash map, calling the passed function for each value.

func (*HashMap[K, V]) Get

func (m *HashMap[K, V]) Get(key K) (val V, ok bool)

Get gets a value from the hash map relating to the passed key.

func (*HashMap[K, V]) Put

func (m *HashMap[K, V]) Put(key K, val V)

Put adds a value to the hash map relating to the passed key.

func (*HashMap[K, V]) Remove

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

Remove deletes a value from the hash map relating to the passed key.

type Hasher

type Hasher interface {
	Hash() uint32
}

Hasher is an interface primarily for structs to provide a hash of their contents

type KV

type KV[V any] struct {
	Key   string
	Value V
}

func (KV[V]) MarshalJSON

func (kv KV[V]) MarshalJSON() ([]byte, error)

type LinkedList

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

LinkedList is the main linked list type.

func NewLinkedList

func NewLinkedList[T comparable]() LinkedList[T]

NewLinkedList is used to create a new linked list.

func (*LinkedList[T]) AddAt

func (l *LinkedList[T]) AddAt(value T, index int) error

AddAt inserts a value at the specified index.

func (*LinkedList[T]) Bottom

func (l *LinkedList[T]) Bottom() *T

Bottom returns the value at the end of the linked list.

func (*LinkedList[T]) Clear

func (l *LinkedList[T]) Clear()

Clear empties the entire linked list.

func (*LinkedList[T]) Count

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

Count returns the amount of entries in the linked list.

func (*LinkedList[T]) Empty

func (l *LinkedList[T]) Empty() bool

Empty returns true if the linked list is empty, false if not.

func (*LinkedList[T]) ForEach

func (l *LinkedList[T]) ForEach(f func(i int, val T))

ForEach iterates over the dataset within the linked list, calling the passed function for each value.

func (*LinkedList[T]) Get

func (l *LinkedList[T]) Get(index int) *T

Get gets a value at the specified index.

func (*LinkedList[T]) Has

func (l *LinkedList[T]) Has(value T) bool

Has returns true if the value exists in the linked list, false if not.

func (*LinkedList[T]) PopBottom

func (l *LinkedList[T]) PopBottom()

PopBottom removes the last value in the linked list.

func (*LinkedList[T]) PopTop

func (l *LinkedList[T]) PopTop()

PopTop removes the first value in the linked list.

func (*LinkedList[T]) PutOnBottom

func (l *LinkedList[T]) PutOnBottom(val T)

PutOnBottom inserts a value at the end of the linked list.

func (*LinkedList[T]) PutOnTop

func (l *LinkedList[T]) PutOnTop(value T)

PutOnTop inserts a value at the beginning of the linked list.

func (*LinkedList[T]) Remove

func (l *LinkedList[T]) Remove(index int)

Remove removes a value at the specified index.

func (*LinkedList[T]) Top

func (l *LinkedList[T]) Top() *T

Top returns the value at the beginning of the linked list.

func (*LinkedList[T]) Update

func (l *LinkedList[T]) Update(index int, val T)

Update updates a value at the specified index.

type Promise

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

func Go

func Go[T, U any](ctx context.Context, t T, fn Promising[T, U]) *Promise[U]

func Then

func Then[T, U any](ctx context.Context, p *Promise[T], fn Promising[T, U]) *Promise[U]

func (*Promise[T]) Resolve

func (p *Promise[T]) Resolve() (T, error)

func (*Promise[T]) Try

func (p *Promise[T]) Try() (T, error)

func (*Promise[T]) Wait

func (p *Promise[T]) Wait() error

type Promising

type Promising[T, U any] func(context.Context, T) (U, error)

func WithCancel

func WithCancel[T, U any](fn Promising[T, U]) Promising[T, U]

type Queue

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

Queue is the main queue type.

func NewQueue

func NewQueue[T comparable](capacity ...int) Queue[T]

NewQueue is used to create a new queue.

func (*Queue[T]) Clear

func (q *Queue[T]) Clear()

Clear empties the entire queue.

func (*Queue[T]) Contains

func (q *Queue[T]) Contains(val T) bool

Contains returns true if the value exists in the queue, false if not.

func (*Queue[T]) Count

func (q *Queue[T]) Count() int

Count returns the amount of entries in the queue.

func (*Queue[T]) Dequeue

func (q *Queue[T]) Dequeue() *T

Dequeue returns the first value and removes it.

func (*Queue[T]) Empty

func (q *Queue[T]) Empty() bool

Empty returns true if the queue is empty, false if not.

func (*Queue[T]) Enqueue

func (q *Queue[T]) Enqueue(val T)

Enqueue add a value to the queue.

func (*Queue[T]) ForEach

func (q *Queue[T]) ForEach(predicate func(val T))

ForEach iterates over the dataset within the queue, calling the passed function for each value.

func (*Queue[T]) Peek

func (q *Queue[T]) Peek() T

Peek returns the first value.

type SortedMap

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

func NewSortedMap

func NewSortedMap[K ordered, V any]() *SortedMap[K, V]

func (*SortedMap[K, V]) Get

func (m *SortedMap[K, V]) Get(k K) V

func (*SortedMap[K, V]) Keys

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

func (*SortedMap[K, V]) Set

func (m *SortedMap[K, V]) Set(k K, v V)

func (*SortedMap[K, V]) String

func (m *SortedMap[K, V]) String() string

type Stack

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

Stack is the main stack type.

func NewStack

func NewStack[T comparable]() Stack[T]

NewStack is used to create a new stack.

func (*Stack[T]) Clear

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

Clear empties the entire stack.

func (*Stack[T]) Contains

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

Contains returns true if the value exists in the stack, false if not.

func (*Stack[T]) Count

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

Count returns the amount of entries in the stack.

func (*Stack[T]) Empty

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

Empty returns true if the stack is empty, false if not.

func (*Stack[T]) ForEach

func (s *Stack[T]) ForEach(f func(val T))

ForEach iterates over the dataset within the stack, calling the passed function for each value.

func (*Stack[T]) Peek

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

Peek returns the first value.

func (*Stack[T]) Pop

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

Pop returns the first value and removes it.

func (*Stack[T]) Push

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

Push adds a value to the stack.

type StringKeyOrderedMap

type StringKeyOrderedMap[V any] struct {
	// contains filtered or unexported fields
}

func NewStringKeyOrderedMap

func NewStringKeyOrderedMap[V any](kvList ...*KV[V]) *StringKeyOrderedMap[V]

func (*StringKeyOrderedMap[V]) Append

func (m *StringKeyOrderedMap[V]) Append(newOm *StringKeyOrderedMap[V], overwrite bool) *StringKeyOrderedMap[V]

func (*StringKeyOrderedMap[V]) Delete

func (m *StringKeyOrderedMap[V]) Delete(key string)

func (*StringKeyOrderedMap[V]) Exists

func (m *StringKeyOrderedMap[V]) Exists(key string) bool

func (*StringKeyOrderedMap[V]) Get

func (m *StringKeyOrderedMap[V]) Get(key string) V

func (*StringKeyOrderedMap[V]) GetKeys

func (m *StringKeyOrderedMap[V]) GetKeys() []string

func (*StringKeyOrderedMap[V]) GetList

func (m *StringKeyOrderedMap[V]) GetList() []KV[V]

func (*StringKeyOrderedMap[V]) Len

func (m *StringKeyOrderedMap[V]) Len() int

func (*StringKeyOrderedMap[V]) MarshalJSON

func (m *StringKeyOrderedMap[V]) MarshalJSON() ([]byte, error)

func (*StringKeyOrderedMap[V]) Set

func (m *StringKeyOrderedMap[V]) Set(key string, value V) *StringKeyOrderedMap[V]

func (*StringKeyOrderedMap[V]) String

func (m *StringKeyOrderedMap[V]) String() string

type Topiq

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

Topiq is a publish-subscribe topic.

func NewPubSub

func NewPubSub[T any](bufferSize int) *Topiq[T]

NewPubSub creates a new Topiq.

func (*Topiq[T]) Dispatch

func (t *Topiq[T]) Dispatch(message T) error

Dispatch publishes a message to the Topiq. This method is non-blocking and concurrent-safe. Returns ErrNotRunning if the Topiq has been already closed.

func (*Topiq[T]) Listen

func (t *Topiq[T]) Listen(bufferSize int, subscriber func(message T)) error

Listen registers the passed function as a subscriber to the Topiq. This method is non-blocking and concurrent-safe. Function passed to Listen is called when a message is published to the Topiq, obviously. Returns ErrNotRunning if the Topiq has been already closed.

func (*Topiq[T]) Start

func (t *Topiq[T]) Start(ctx context.Context) error

Start starts the Topiq and blocks until the context is canceled. When the passed context is canceled, Start waits for all published messages to be processed by all subscribers. Once Start is called, then Start returns ErrAlreadyStarted.

type Waiter

type Waiter interface {
	Wait() error
}

Directories

Path Synopsis
Package timsort provides fast stable sort, uses external comparator.
Package timsort provides fast stable sort, uses external comparator.

Jump to

Keyboard shortcuts

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