ds

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

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

Go to latest
Published: Dec 16, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

go-board/ds

A comprehensive, high-performance generic data structures library for Go 1.24+

Overview

go-board/ds is a feature-rich data structures library for Go that leverages the power of Go 1.24's generics to provide type-safe, efficient implementations of common and advanced data structures. This library is designed to be both performant and developer-friendly, with a consistent API design across all implementations.

Features

  • Full Generic Support: Leverage Go 1.24 generics for type-safe data structures
  • Comprehensive Data Structure Collection: Linked lists, deques, maps, sets, priority queues, and more
  • Performance-Optimized Implementations: Each data structure is carefully optimized for its specific use cases
  • Consistent API Design: Familiar interfaces across all data structures
  • Flexible Hashing Strategies: Customizable hashers for any type
  • Complete Iterator Support: Multiple iteration patterns for easy data processing

Installation

go get github.com/go-board/ds

Quick Start

Here's a simple example demonstrating some of the library's capabilities:

package main

import (
	"fmt"

	"github.com/go-board/ds"
)

func main() {
	// Create a new hash map
	m := ds.NewHashMap[string, int](ds.DefaultHasher[string]{})
	m.Insert("apple", 5)
	m.Insert("banana", 3)
	m.Insert("cherry", 7)

	// Retrieve a value
	if val, found := m.Get("banana"); found {
		fmt.Printf("Banana count: %d\n", val)
	}

	// Create a linked list
	list := ds.NewLinkedList[int]()
	list.PushBack(10)
	list.PushBack(20)
	list.PushFront(5)

	// Iterate through the list
	fmt.Println("Linked list elements:")
	for val := range list.Iter() {
		fmt.Printf("%d ", val)
	}
	fmt.Println()
}

Data Structure Capabilities

The following table shows the core capabilities supported by each data structure:

  • ✅ Indicates the data structure supports this function
  • ❌ Indicates the data structure does not support this function
Function LinkedList ArrayDeque HashMap HashSet BTree BTreeMap BTreeSet SkipMap SkipSet TrieMap PriorityQueue
Basic Operations
Clear
Len
IsEmpty
Compact
Access & Modification
Get
GetMut
Insert
Remove
List/Queue Operations
PushFront
PopFront
PushBack
PopBack
Front
Back
Set Operations
Contains
ContainsKey
Ordered Data Operations
First
Last
Range
PopFirst
PopLast
Iterators
Iter
IterMut
Collection Operations
Extend
Difference
Union
Intersection
IsSubset
IsSuperset
SymmetricDifference
Equal
Priority Queue Operations
Push
Pop
Peek

Core Data Structures

Linked List
// Create a new linked list
list := ds.NewLinkedList[int]()

// Add elements
list.PushBack(1)
list.PushFront(0)
list.PushBack(2)

// Remove elements
value, _ := list.PopFront()  // 0
value, _ = list.PopBack()    // 2

// Iterate
for val := range list.Iter() {
    fmt.Println(val)  // 1
}
Hash Map
// Create a new hash map with default hasher
m := ds.NewHashMap[string, int](ds.DefaultHasher[string]{})

// Insert key-value pairs
m.Insert("one", 1)
m.Insert("two", 2)

// Retrieve values
value, found := m.Get("one")

// Update values
oldValue, updated := m.Insert("one", 10)

// Iterate through all key-value pairs
for key, val := range m.Iter() {
    fmt.Printf("%s: %d\n", key, val)
}
Priority Queue
// Create a min-heap (sorts by age ascending)
minHeap := ds.NewMinPriorityQueue[Person](func(a, b Person) int {
    return a.Age - b.Age
})

// Add elements
minHeap.Push(Person{Name: "Alice", Age: 30})
minHeap.Push(Person{Name: "Bob", Age: 25})

// Get highest priority element
person, _ := minHeap.Pop()  // Bob

// Peek at the highest priority element without removing
person, _ = minHeap.Peek()  // Alice
BTreeMap
// Create an ordered BTreeMap for ordered types
m := ds.NewOrderedBTreeMap[string, int]()

// Insert key-value pairs
m.Insert("apple", 5)
m.Insert("banana", 3)
m.Insert("cherry", 7)

// Get first and last elements
first, _ := m.First()      // apple: 5
last, _ := m.Last()        // cherry: 7

// Range query
m.Range(func(key string, value int) bool {
    fmt.Printf("%s: %d\n", key, value)

### TrieMap

```go
// Create a new TrieMap
m := ds.NewTrieMap[string, int]()

// Insert key-value pairs
m.Insert("apple", 5)
m.Insert("app", 3)
m.Insert("banana", 7)

// Get values
value, found := m.Get("apple")  // 5, true

// Check if key exists
value, found = m.Get("ap")      // 0, false (key not found)

// Remove a key
m.Remove("app")

// Iterate through all key-value pairs
for key, val := range m.Iter() {
    fmt.Printf("%s: %d\n", key, val)
}

## Custom Hashing

For complex types or custom hashing behavior, implement your own `Hasher`:

```go
// Custom struct
type Point struct {
    X, Y int
}

// Custom hasher
type PointHasher struct{}

func (PointHasher) Equal(p1, p2 Point) bool {
    return p1.X == p2.X && p1.Y == p2.Y
}

func (PointHasher) Hash(h *maphash.Hash, p Point) {
    maphash.WriteInt(h, p.X)
    maphash.WriteInt(h, p.Y)
}

// Usage
pointMap := ds.NewHashMap[Point, string](PointHasher{})
pointMap.Insert(Point{X: 1, Y: 2}, "Start point")

Requirements

  • Go 1.24 or higher (for full generics support)
  • No external dependencies

Testing

Run the test suite:

go test ./... -v

Contributing

Contributions are welcome! Please follow these guidelines:

  1. Ensure your code follows Go's standard formatting
  2. Add appropriate test cases for any new functionality
  3. Update documentation as needed
  4. Maintain consistency with existing API design

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Overview

Package ds provides common interfaces and implementations for various data structures. This file defines the Map interface, which is the basic abstraction for all key-value mapping implementations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ArrayDeque

type ArrayDeque[T any] = arraydeque.ArrayDeque[T]

ArrayDeque is an alias for arraydeque.ArrayDeque, providing slice-based double-ended queue functionality.

func NewArrayDeque

func NewArrayDeque[T any]() *ArrayDeque[T]

NewArrayDeque creates a new slice-based double-ended queue instance.

type ArrayStack

type ArrayStack[T any] = arraystack.ArrayStack[T]

ArrayStack is an alias for arraystack.ArrayStack, providing slice-based stack functionality.

func NewArrayStack

func NewArrayStack[T any]() *ArrayStack[T]

NewArrayStack creates a new slice-based stack instance.

type BTree

type BTree[T any] = btree.BTree[T]

BTree is an alias for btree.BTree, providing ordered data storage functionality.

func NewBTree

func NewBTree[T any](comparator func(T, T) int) *BTree[T]

NewBTree creates a new B-tree instance. comparator is used to compare element sizes and cannot be nil.

func NewOrderedBTree

func NewOrderedBTree[T cmp.Ordered]() *BTree[T]

NewOrderedBTree creates a new ordered B-tree instance. The element type must implement the cmp.Ordered interface.

type BTreeMap

type BTreeMap[K any, V any] = btreemap.BTreeMap[K, V]

BTreeMap is a type alias for btreemap.BTreeMap, providing ordered key-value mapping functionality.

func NewBTreeMap

func NewBTreeMap[K any, V any](comparator func(K, K) int) *BTreeMap[K, V]

NewBTreeMap creates a new B-tree map instance. comparator is used to compare key sizes, returning negative, zero, or positive to indicate whether the first key is less than, equal to, or greater than the second key.

func NewOrderedBTreeMap

func NewOrderedBTreeMap[K cmp.Ordered, V any]() *BTreeMap[K, V]

NewOrderedBTreeMap creates a new ordered B-tree map instance. The key type must implement the cmp.Ordered interface.

type BTreeSet

type BTreeSet[T any] = btreeset.BTreeSet[T]

BTreeSet is a type alias for btreeset.BTreeSet, providing ordered set functionality.

func NewBTreeSet

func NewBTreeSet[T any](comparator func(T, T) int) *BTreeSet[T]

NewBTreeSet creates a new B-tree set instance. comparator is used to compare element sizes, returning negative, zero, or positive to indicate whether the first element is less than, equal to, or greater than the second element.

func NewOrderedBTreeSet

func NewOrderedBTreeSet[T cmp.Ordered]() *BTreeSet[T]

NewOrderedBTreeSet creates a new ordered B-tree set instance. The element type must implement the cmp.Ordered interface.

type DefaultHasher

type DefaultHasher[E comparable] = hashutil.Default[E]

DefaultHasher is a default hasher implementation for comparable types. It uses Go's standard library maphash package for hash calculations.

type HashMap

type HashMap[K any, V any, H hashutil.Hasher[K]] = hashmap.HashMap[K, V, H]

HashMap is an alias for hashmap.HashMap, providing key-value mapping functionality.

func NewComparableHashMap

func NewComparableHashMap[K comparable, V any]() *HashMap[K, V, hashutil.Default[K]]

NewComparableHashMap creates a new hash map instance with a default hasher for comparable key types.

func NewHashMap

func NewHashMap[K any, V any, H hashutil.Hasher[K]](h H) *HashMap[K, V, H]

NewHashMap creates a new hash map instance. h is the hasher used to calculate key hash values.

func NewHashMapFromMap

func NewHashMapFromMap[K comparable, V any, M ~map[K]V](m M) *HashMap[K, V, hashutil.Default[K]]

NewHashMapFromMap creates a new hash map instance from an existing map.

type HashSet

type HashSet[T any, H hashutil.Hasher[T]] = hashset.HashSet[T, H]

HashSet is an alias for hashset.HashSet, providing set functionality.

func NewComparableHashSet

func NewComparableHashSet[T comparable]() *HashSet[T, hashutil.Default[T]]

NewComparableHashSet creates a new hash set instance with a default hasher for comparable key types.

func NewHashSet

func NewHashSet[T any, H hashutil.Hasher[T]](h H) *HashSet[T, H]

NewHashSet creates a new hash set instance. h is the hasher used to calculate element hash values.

type Hasher

type Hasher[E any] = hashutil.Hasher[E]

Hasher is an alias for hashutil.Hasher, providing a generic interface for comparing and hashing values of any type.

type LinkedList

type LinkedList[T any] = linkedlist.LinkedList[T]

LinkedList is an alias for linkedlist.LinkedList, providing linked list-based functionality.

func NewLinkedList

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

NewLinkedList creates a new linked list instance.

type Map

type Map[K any, V any] interface {
	// Get retrieves the value associated with the specified key.
	// Parameters:
	//   - key: The key to look up
	//
	// Return values:
	//   - If the key exists, returns the associated value and true
	//   - If the key does not exist, returns the zero value and false
	Get(key K) (V, bool)

	// GetMut retrieves a mutable reference to the value associated with the specified key, allowing in-place modification.
	// Parameters:
	//   - key: The key to look up
	//
	// Return values:
	//   - If the key exists, returns a pointer to the value and true
	//   - If the key does not exist, returns nil and false
	GetMut(key K) (*V, bool)

	// GetKeyValue returns the key, value, and an existence flag.
	// Parameters:
	//   - key: The key to look up
	//
	// Return values:
	//   - If the key exists, returns the key, associated value, and true
	//   - If the key does not exist, returns the zero key, zero value, and false
	GetKeyValue(key K) (K, V, bool)

	// Insert inserts or updates a key-value pair.
	// Parameters:
	//   - key: The key to insert or update
	//   - value: The value to associate
	//
	// Return values:
	//   - If the key already exists, returns the old value and true
	//   - If the key does not exist, returns the zero value and false
	Insert(key K, value V) (V, bool)

	// Remove deletes the key-value pair for the specified key.
	// Parameters:
	//   - key: The key to delete
	//
	// Return values:
	//   - If the key exists, returns the deleted value and true
	//   - If the key does not exist, returns the zero value and false
	Remove(key K) (V, bool)

	// ContainsKey checks if the map contains the specified key.
	// Parameters:
	//   - key: The key to check
	//
	// Return value:
	//   - Returns true if the key exists, otherwise false
	ContainsKey(key K) bool

	// Len returns the number of key-value pairs in the map.
	// Return value:
	//   - The number of elements in the map
	Len() int

	// IsEmpty checks if the map is empty.
	// Return value:
	//   - Returns true if the map is empty, otherwise false
	IsEmpty() bool

	// Clear removes all key-value pairs from the map, making it empty.
	Clear()

	// Extend adds another iterable collection of key-value pairs to the current map.
	// Parameters:
	//   - iter: Iterator providing key-value pairs
	//
	// Behavior:
	//   - For each key-value pair, updates the value if the key already exists, otherwise adds a new key-value pair
	Extend(iter iter.Seq2[K, V])

	// Keys returns an iterator over all keys in the map.
	// Return value:
	//   - Iterator over keys, of type iter.Seq[K]
	//
	// Note: For ordered maps, keys are returned in order; for unordered maps, the order is uncertain.
	Keys() iter.Seq[K]

	// Values returns an iterator over all values in the map.
	// Return value:
	//   - Iterator over values, of type iter.Seq[V]
	//
	// Note: For ordered maps, values are returned in key order; for unordered maps, the order is uncertain.
	Values() iter.Seq[V]

	// ValuesMut returns an iterator over mutable references to all values in the map.
	// Return value:
	//   - Iterator over mutable references to values, of type iter.Seq[*V]
	//
	// Note: For ordered maps, values are returned in key order; for unordered maps, the order is uncertain.
	ValuesMut() iter.Seq[*V]

	// Iter returns an iterator over all key-value pairs in the map.
	// Return value:
	//   - Iterator over all key-value pairs, of type iter.Seq2[K, V]
	//
	// Note: For ordered maps, key-value pairs are returned in key order; for unordered maps, the order is uncertain.
	Iter() iter.Seq2[K, V]

	// IterMut returns a mutable iterator over all key-value pairs in the map.
	// Return value:
	//   - Mutable iterator over all key-value pairs, of type iter.Seq2[K, *V]
	//
	// Note: For ordered maps, key-value pairs are returned in key order; for unordered maps, the order is uncertain.
	IterMut() iter.Seq2[K, *V]
}

Map defines a common interface for key-value mappings. All types implementing this interface provide key-to-value mapping functionality, supporting basic operations like addition, deletion, modification, and lookup, as well as iteration.

Type parameters:

  • K: Key type
  • V: Value type

Example:

// Using a concrete type that implements the Map interface
var m ds.Map[string, int]
m = hashmap.NewHashMap[string, int](hashutil.StrHasher{})

// Using interface methods
m.Insert("apple", 5)
val, found := m.Get("apple")
if found {
    fmt.Println(val) // Output: 5
}

// Iterating over the map
for k, v := range m.Iter() {
    fmt.Printf("%s: %d\n", k, v)
}

type MapHasher

type MapHasher[E ~map[K]V, K comparable, V any, H Hasher[V]] = hashutil.MapHasher[E, K, V, H]

MapHasher is a hasher implementation for map types. It uses the key type's Hasher and value type's Hasher to calculate the hash for the entire map.

type OrderedMap

type OrderedMap[K any, V any] interface {
	Map[K, V]

	// First returns the first (smallest key) key-value pair in the map.
	// Return values:
	//   - If the map is non-empty, returns the key, value, and true
	//   - If the map is empty, returns zero key, zero value, and false
	First() (K, V, bool)

	// Last returns the last (largest key) key-value pair in the map.
	// Return values:
	//   - If the map is non-empty, returns the key, value, and true
	//   - If the map is empty, returns zero key, zero value, and false
	Last() (K, V, bool)

	// PopFirst removes and returns the first (smallest key) key-value pair from the map.
	// Return values:
	//   - If the map is non-empty, returns the removed key, value, and true
	//   - If the map is empty, returns zero key, zero value, and false
	PopFirst() (K, V, bool)

	// PopLast removes and returns the last (largest key) key-value pair from the map.
	// Return values:
	//   - If the map is non-empty, returns the removed key, value, and true
	//   - If the map is empty, returns zero key, zero value, and false
	PopLast() (K, V, bool)

	// Range returns an iterator over key-value pairs where the key is in the [lowerBound, upperBound) range.
	// Parameters:
	//   - lowerBound: Lower bound of the range (inclusive), nil means no lower bound
	//   - upperBound: Upper bound of the range (exclusive), nil means no upper bound
	//
	// Return value:
	//   - Iterator over key-value pairs within the specified range, sorted by key in ascending order
	Range(lowerBound, upperBound *K) iter.Seq2[K, V]

	// RangeMut returns a mutable iterator over key-value pairs where the key is in the [lowerBound, upperBound) range.
	// Parameters:
	//   - lowerBound: Lower bound of the range (inclusive), nil means no lower bound
	//   - upperBound: Upper bound of the range (exclusive), nil means no upper bound
	//
	// Return value:
	//   - Mutable iterator over key-value pairs within the specified range, sorted by key in ascending order
	RangeMut(lowerBound, upperBound *K) iter.Seq2[K, *V]

	// IterBack returns an iterator over all key-value pairs in the map in reverse order.
	// Return value:
	//   - Iterator over all key-value pairs in reverse order, of type iter.Seq2[K, V]
	//
	// Note: For ordered maps, key-value pairs are returned in reverse key order; for unordered maps, the order is uncertain.
	IterBack() iter.Seq2[K, V]

	// IterBackMut returns a mutable iterator over all key-value pairs in the map in reverse order.
	// Return value:
	//   - Mutable iterator over all key-value pairs in reverse order, of type iter.Seq2[K, *V]
	//
	// Note: For ordered maps, key-value pairs are returned in reverse key order; for unordered maps, the order is uncertain.
	IterBackMut() iter.Seq2[K, *V]

	// KeysBack returns an iterator over all keys in the map in reverse order.
	// Return value:
	//   - Iterator over keys in reverse order, of type iter.Seq[K]
	//
	// Note: For ordered maps, keys are returned in reverse order; for unordered maps, the order is uncertain.
	KeysBack() iter.Seq[K]

	// ValuesBack returns an iterator over all values in the map in reverse order.
	// Return value:
	//   - Iterator over values in reverse order, of type iter.Seq[V]
	//
	// Note: For ordered maps, values are returned in reverse key order; for unordered maps, the order is uncertain.
	ValuesBack() iter.Seq[V]

	// ValuesBackMut returns a mutable iterator over all values in the map in reverse order.
	// Return value:
	//   - Mutable iterator over values in reverse order, of type iter.Seq[*V]
	//
	// Note: For ordered maps, values are returned in reverse key order; for unordered maps, the order is uncertain.
	ValuesBackMut() iter.Seq[*V]
}

OrderedMap defines an interface for ordered key-value mappings, extending the basic Map interface. Ordered maps guarantee the iteration order of key-value pairs, typically by key sorting order.

Type parameters:

  • K: Key type
  • V: Value type

Note: Not all Map implementations support ordered operations.

type PriorityQueue

type PriorityQueue[T any] = priorityqueue.PriorityQueue[T]

PriorityQueue is an alias for priorityqueue.PriorityQueue.

func NewMaxOrderedPriorityQueue

func NewMaxOrderedPriorityQueue[T cmp.Ordered]() *PriorityQueue[T]

NewMaxOrderedPriorityQueue creates a new max-heap priority queue, where the element type must implement the cmp.Ordered interface.

func NewMaxPriorityQueue

func NewMaxPriorityQueue[T any](cmp func(T, T) int) *PriorityQueue[T]

NewMaxPriorityQueue creates a new max-heap priority queue. cmp is a comparison function: returns negative when a < b, 0 when a == b, positive when a > b. The largest element has the highest priority in a max-heap.

func NewMinOrderedPriorityQueue

func NewMinOrderedPriorityQueue[T cmp.Ordered]() *PriorityQueue[T]

NewMinOrderedPriorityQueue creates a new min-heap priority queue, where the element type must implement the cmp.Ordered interface.

func NewMinPriorityQueue

func NewMinPriorityQueue[T any](cmp func(T, T) int) *PriorityQueue[T]

NewMinPriorityQueue creates a new min-heap priority queue. cmp is a comparison function: returns negative when a < b, 0 when a == b, positive when a > b. The largest element has the highest priority in a max-heap.

type SkipMap

type SkipMap[K any, V any] = skipmap.SkipMap[K, V]

SkipMap is a type alias for skipmap.SkipMap, providing skip list-based key-value mapping functionality.

func NewOrderedSkipMap

func NewOrderedSkipMap[K cmp.Ordered, V any]() *SkipMap[K, V]

NewOrderedSkipMap creates a new ordered skip list map instance. The key type must implement the cmp.Ordered interface.

func NewSkipMap

func NewSkipMap[K any, V any](comparator func(K, K) int) *SkipMap[K, V]

NewSkipMap creates a new skip list map instance. comparator is used to compare key sizes, returning negative, zero, or positive to indicate whether the first key is less than, equal to, or greater than the second key.

type SkipSet

type SkipSet[E any] = skipset.SkipSet[E]

SkipSet is a type alias for skipset.SkipSet, providing skip list-based ordered set functionality.

func NewOrderedSkipSet

func NewOrderedSkipSet[E cmp.Ordered]() *SkipSet[E]

NewOrderedSkipSet creates a new ordered skip list set instance. The element type must implement the cmp.Ordered interface.

func NewSkipSet

func NewSkipSet[E any](comparator func(E, E) int) *SkipSet[E]

NewSkipSet creates a new skip list set instance. comparator is used to compare element sizes, returning negative, zero, or positive to indicate whether the first element is less than, equal to, or greater than the second element.

type SliceHasher

type SliceHasher[E ~[]T, T any, H Hasher[T]] = hashutil.SliceHasher[E, T, H]

SliceHasher is a hasher implementation for slice types. It uses the element type's Hasher to calculate the hash for the entire slice.

type TrieMap

type TrieMap[K any, V any] = trie.TrieMap[K, V]

TrieMap is an alias for trie.TrieMap, providing trie-based key-value mapping functionality.

func NewOrderedTrieMap

func NewOrderedTrieMap[K cmp.Ordered, V any]() *TrieMap[K, V]

NewOrderedTrieMap creates a new trie map instance for ordered key types. The key type must implement the cmp.Ordered interface.

func NewTrieMap

func NewTrieMap[K any, V any](comparator func(K, K) int) *TrieMap[K, V]

NewTrieMap creates a new trie map instance. comparator is used to compare individual key elements.

Directories

Path Synopsis
Package arraydeque implements a generic double-ended queue data structure based on a linear slice.
Package arraydeque implements a generic double-ended queue data structure based on a linear slice.
Package arraystack implements a generic stack data structure using ArrayDeque as the underlying storage.
Package arraystack implements a generic stack data structure using ArrayDeque as the underlying storage.
Package btree implements a generic B-tree data structure.
Package btree implements a generic B-tree data structure.
Package btreemap implements an ordered key-value map based on B-trees.
Package btreemap implements an ordered key-value map based on B-trees.
Package btreeset implements a B-tree based ordered set data structure.
Package btreeset implements a B-tree based ordered set data structure.
Package hashmap implements a generic hash map data structure.
Package hashmap implements a generic hash map data structure.
Package hashset implements an unordered set data structure based on hash tables.
Package hashset implements an unordered set data structure based on hash tables.
Package hashutil provides generic hashing utilities for hash computation and equality comparison of various types.
Package hashutil provides generic hashing utilities for hash computation and equality comparison of various types.
internal
Package linkedlist implements a generic doubly linked list data structure.
Package linkedlist implements a generic doubly linked list data structure.
Package priorityqueue implements a generic priority queue data structure.
Package priorityqueue implements a generic priority queue data structure.
Package skipmap implements ordered key-value mapping based on skip lists.
Package skipmap implements ordered key-value mapping based on skip lists.
Package skipset implements a sorted set based on skip lists.
Package skipset implements a sorted set based on skip lists.
Package trie implements a generic trie (prefix tree) data structure.
Package trie implements a generic trie (prefix tree) data structure.

Jump to

Keyboard shortcuts

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