readyset

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ReadySet

Generic sets for Go, with the usual set logic: union, intersection, difference, symmetric difference, subset and superset checks.

Two packages, for two situations:

Package Use it when Elements are the same when
readyset your elements are comparable (int, string, structs of comparable fields, ...) their values are equal
readyset/keyed elements are not comparable (they hold slices or maps), or only part of them, like an ID, defines identity their keys are equal

Requires Go 1.18 or later. Sorted needs Go 1.21 or later, and the iterator functions All() and Collect need Go 1.23 or later.

Installation

go get github.com/kastolars/readyset

readyset

import "github.com/kastolars/readyset"

a := readyset.New(1, 2, 3)
b := readyset.New(3, 4)

a.Add(5, 6)          // variadic
a.Remove(1)
a.Contains(2)        // true
a.ContainsAll(2, 3)  // true: every one is present
a.ContainsAny(8, 9)  // false: none is present

a.Union(b)               // {2, 3, 4, 5, 6}
a.Intersection(b)        // {3}
a.Difference(b)          // {2, 5, 6}
a.SymmetricDifference(b) // {2, 4, 5, 6}
a.IsSubset(b)            // false
a.IsProperSubset(b)      // false: a proper subset is a subset that is not equal
a.IsDisjoint(b)          // false
a.Equal(b)               // false

a.AddSet(b)              // in place: a is now the union, {2, 3, 4, 5, 6}
a.RemoveSet(b)           // in place: a is now the difference, {2, 5, 6}

c := a.Clone()
c.RetainSet(b)           // in place: c is now the intersection, {}

evens := a.Filter(func(n int) bool { return n%2 == 0 }) // a new set, {2, 6}
c.AddSet(a)
c.RemoveFunc(func(n int) bool { return n > 4 })         // in place; returns how many it removed (2)
e, ok := c.Pop()                                        // remove and return an arbitrary element

readyset.Sorted(a)                  // []int{2, 5, 6}, ascending (Go 1.21+)
readyset.Collect(slices.Values(xs)) // a set from any iter.Seq (Go 1.23+)

var zero readyset.Set[string] // the zero value is an empty, usable set
zero.Add("x")

readyset/keyed

A key function maps each element to a comparable key. Two elements are the same element exactly when their keys are equal.

import "github.com/kastolars/readyset/keyed"

type User struct {
    Email string
    Name  string
    Tags  []string // not comparable, so User cannot go in a readyset.Set
}

users := keyed.New(func(u User) string { return u.Email })
users.Add(User{Email: "ann@example.com", Name: "Ann"})

users.Contains(User{Email: "ann@example.com"}) // true: only the key is compared
u, ok := users.Get("ann@example.com")

users.ContainsKey("ann@example.com") // true
users.RemoveKey("ann@example.com")   // remove by key alone, no User needed
users.Keys()                         // []string{}, in no particular order

Because key equality is element equality, adding an element whose key is already present replaces the stored element, and AddSet follows the same rule. Operations between two sets compare keys only and expect the same key function on both. Union and Intersection return the receiver's elements. keyed.Sorted(users) returns the elements in ascending key order (Go 1.21+). keyed has the same RetainSet, RemoveFunc, Filter, Pop, ContainsAll, ContainsAny and proper-subset methods, plus keyed.Collect(key, seq) (Go 1.23+).

Printing and JSON

Both packages print readably and encode to JSON as arrays, in a stable order (numbers numerically, strings lexically, keyed sets by key), so output never depends on map iteration order.

fmt.Println(readyset.New(10, 2, 1)) // {1, 2, 10}

b, _ := json.Marshal(readyset.New("b", "a")) // ["a","b"]

var tags readyset.Set[string]
_ = json.Unmarshal([]byte(`["go","sets"]`), &tags) // works as a struct field too

A keyed set needs its key function to decode, so create it with keyed.New before calling json.Unmarshal.

Recipes

// Unique values from a slice. Slice() is in random order; Sorted is not.
unique := readyset.Sorted(readyset.New(ids...))

// What changed between two snapshots.
added := current.Difference(previous)
removed := previous.Difference(current)

// Does the caller hold every permission the action needs?
if granted.IsSuperset(required) {
    // ...
}

// Merge several sources into one set, then drop the blocked values.
var all readyset.Set[string] // the zero value is ready to use
for _, src := range sources {
    all.AddSet(src)
}
all.RemoveSet(blocked)

// Drain a worklist: process each item once, in no particular order.
for {
    item, ok := todo.Pop()
    if !ok {
        break
    }
    // ... may call todo.Add(...) for newly discovered work
}

// One record per ID, in ID order. Later records replace earlier ones.
byID := keyed.New(func(r Record) int { return r.ID }, records...)
latest := keyed.Sorted(byID)

Behaviour to know about

  • Iteration order is random. Go randomises map iteration, so Slice() and All() return elements in no particular order. Printing and JSON are sorted for you; sort the result yourself if you need a stable order from Slice().
  • Copies share storage. Assigning a non-empty set to another variable shares the underlying map. Use Clone() for an independent copy.
  • Result sets are sized for speed. Union, Intersection and Difference allocate their result for the largest it could be, which avoids regrowing the map. If you keep a small result computed from a very large input, Clone() it to release the extra memory.
  • Not safe for concurrent use. Guard a set with your own mutex if goroutines share it.
  • Set operations return new sets. Union, Intersection and the rest never modify their operands. AddSet, RemoveSet and RetainSet are the in-place forms of Union, Difference and Intersection.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate. go test -race ./... and gofmt must pass; CI also runs staticcheck.

License

MIT

Documentation

Overview

Package readyset provides generic sets for Go, with the usual set logic: union, intersection, difference, symmetric difference, and subset, superset and disjointness checks.

Set holds any comparable type, and two elements are the same element when they are equal:

a := readyset.New(1, 2, 3)
b := readyset.New(3, 4)
fmt.Println(a.Union(b))        // {1, 2, 3, 4}
fmt.Println(a.Intersection(b)) // {3}

Union, difference and intersection also have in-place forms: Set.AddSet, Set.RemoveSet and Set.RetainSet update a set instead of returning a new one. Set.Filter, Set.RemoveFunc and Set.Pop select, delete and drain elements, and Sorted and Collect convert to and from ordered slices and iterators on the Go versions that support them.

For elements that are not comparable, or that are identified by only part of their value such as an ID, use github.com/kastolars/readyset/keyed.

Sets print with their elements in a stable order, and encode to and decode from JSON as arrays. Iteration order (Set.Slice) is random, as with Go maps.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Sorted added in v0.2.0

func Sorted[T cmp.Ordered](s Set[T]) []T

Sorted returns the elements of s as a new slice in ascending order. It works for any ordered element type: integers, floats and strings. NaN, if present, sorts before every other float.

Sorted is a function rather than a method because only an ordered element type can be sorted, and a method cannot add that constraint to Set. It is available when building with Go 1.21 or later.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	// Slice returns elements in random order; Sorted gives a stable one.
	ids := readyset.New(30, 10, 20, 10)
	fmt.Println(readyset.Sorted(ids))
}
Output:
[10 20 30]

Types

type Set

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

Set is an unordered collection of unique elements.

The zero value is an empty set that is ready to use. Methods that modify a set have pointer receivers, so call them on an addressable variable. Copying a non-empty Set copies a reference to the same underlying storage; use Set.Clone for an independent copy.

A Set is not safe for concurrent use.

func Collect added in v0.3.0

func Collect[T comparable](seq iter.Seq[T]) Set[T]

Collect returns a new set of the elements yielded by seq. It is available when building with Go 1.23 or later.

Example
package main

import (
	"fmt"
	"slices"

	"github.com/kastolars/readyset"
)

func main() {
	words := []string{"b", "a", "b", "c"}
	unique := readyset.Collect(slices.Values(words))
	fmt.Println(unique)
}
Output:
{a, b, c}

func New

func New[T comparable](elements ...T) Set[T]

New returns a Set containing elements. Duplicates are ignored.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	s := readyset.New(3, 1, 2, 3)
	fmt.Println(s.Len(), s.Contains(2), s.Contains(9))
}
Output:
3 true false

func (*Set[T]) Add

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

Add inserts elements into the set. Elements already present are ignored.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	var s readyset.Set[string] // the zero value is ready to use
	s.Add("a", "b")
	s.Add("b", "c")
	fmt.Println(s.Len())
}
Output:
3

func (*Set[T]) AddSet added in v0.2.0

func (s *Set[T]) AddSet(other Set[T])

AddSet inserts every element of other into the set. It is the in-place counterpart of Set.Union: afterwards s holds what s.Union(other) would have returned, and other is not modified.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	all := readyset.New(1, 2)
	all.AddSet(readyset.New(2, 3))
	fmt.Println(all)
}
Output:
{1, 2, 3}

func (Set[T]) All

func (s Set[T]) All() iter.Seq[T]

All returns an iterator over the elements of the set, in no particular order. It is available when building with Go 1.23 or later.

The set must not be modified while iterating over it.

func (*Set[T]) Clear

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

Clear removes every element from the set.

func (Set[T]) Clone

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

Clone returns an independent copy of the set.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2)
	b := a.Clone()
	b.Add(3)
	fmt.Println(a.Len(), b.Len())
}
Output:
2 3

func (Set[T]) Contains

func (s Set[T]) Contains(element T) bool

Contains reports whether element is in the set.

func (Set[T]) ContainsAll added in v0.3.0

func (s Set[T]) ContainsAll(elements ...T) bool

ContainsAll reports whether every one of elements is in the set. It is true when elements is empty.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	s := readyset.New(1, 2, 3)
	fmt.Println(s.ContainsAll(1, 2), s.ContainsAll(1, 9))
}
Output:
true false

func (Set[T]) ContainsAny added in v0.3.0

func (s Set[T]) ContainsAny(elements ...T) bool

ContainsAny reports whether at least one of elements is in the set. It is false when elements is empty.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	s := readyset.New(1, 2, 3)
	fmt.Println(s.ContainsAny(9, 3), s.ContainsAny(8, 9))
}
Output:
true false

func (Set[T]) Difference

func (s Set[T]) Difference(other Set[T]) Set[T]

Difference returns a new set of the elements that are in s but not in other.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2, 3)
	b := readyset.New(2, 3, 4)
	fmt.Println(a.Difference(b))
}
Output:
{1}

func (Set[T]) Equal

func (s Set[T]) Equal(other Set[T]) bool

Equal reports whether s and other contain exactly the same elements.

func (Set[T]) Filter added in v0.3.0

func (s Set[T]) Filter(keep func(T) bool) Set[T]

Filter returns a new set of the elements for which keep returns true.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	s := readyset.New(1, 2, 3, 4, 5, 6)
	fmt.Println(s.Filter(func(n int) bool { return n > 4 }))
}
Output:
{5, 6}

func (Set[T]) Intersection

func (s Set[T]) Intersection(other Set[T]) Set[T]

Intersection returns a new set of the elements that are in both s and other.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2, 3)
	b := readyset.New(2, 3, 4)
	fmt.Println(a.Intersection(b))
}
Output:
{2, 3}

func (Set[T]) IsDisjoint

func (s Set[T]) IsDisjoint(other Set[T]) bool

IsDisjoint reports whether s and other have no elements in common.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	odds := readyset.New(1, 3, 5)
	evens := readyset.New(2, 4, 6)
	fmt.Println(odds.IsDisjoint(evens))
}
Output:
true

func (Set[T]) IsEmpty

func (s Set[T]) IsEmpty() bool

IsEmpty reports whether the set has no elements.

func (Set[T]) IsProperSubset added in v0.3.0

func (s Set[T]) IsProperSubset(other Set[T]) bool

IsProperSubset reports whether s is a subset of other and the two are not equal, that is, other has at least one element that s lacks.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a, b := readyset.New(1, 2), readyset.New(1, 2, 3)
	fmt.Println(a.IsSubset(a), a.IsProperSubset(a), a.IsProperSubset(b))
}
Output:
true false true

func (Set[T]) IsProperSuperset added in v0.3.0

func (s Set[T]) IsProperSuperset(other Set[T]) bool

IsProperSuperset reports whether s is a superset of other and the two are not equal, that is, s has at least one element that other lacks.

func (Set[T]) IsSubset

func (s Set[T]) IsSubset(other Set[T]) bool

IsSubset reports whether every element of s is also in other. The empty set is a subset of every set, and every set is a subset of itself.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(2, 3)
	b := readyset.New(1, 2, 3, 4)
	fmt.Println(a.IsSubset(b), b.IsSubset(a))
}
Output:
true false

func (Set[T]) IsSuperset

func (s Set[T]) IsSuperset(other Set[T]) bool

IsSuperset reports whether every element of other is also in s.

func (Set[T]) Len

func (s Set[T]) Len() int

Len returns the number of elements in the set.

func (Set[T]) MarshalJSON

func (s Set[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. It encodes the set as a JSON array of its elements, in the same stable order as Set.String, so equal sets always encode to the same bytes. An empty set encodes as [].

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	b, _ := json.Marshal(readyset.New("b", "a"))
	fmt.Println(string(b))
}
Output:
["a","b"]

func (*Set[T]) Pop added in v0.3.0

func (s *Set[T]) Pop() (T, bool)

Pop removes and returns an arbitrary element of the set. The boolean is false if the set was empty. Which element is returned is unspecified and can differ between calls, so use it to drain a worklist, not to pick a particular element.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	// Pop drains a worklist: process each item once, in no particular order.
	todo := readyset.New("a", "b", "c")
	n := 0
	for {
		_, ok := todo.Pop()
		if !ok {
			break
		}
		n++
	}
	fmt.Println(n, todo.IsEmpty())
}
Output:
3 true

func (*Set[T]) Remove

func (s *Set[T]) Remove(elements ...T)

Remove deletes elements from the set. Elements not present are ignored.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	s := readyset.New(1, 2, 3)
	s.Remove(1, 9) // 9 is not present; that is not an error
	fmt.Println(s)
}
Output:
{2, 3}

func (*Set[T]) RemoveFunc added in v0.3.0

func (s *Set[T]) RemoveFunc(remove func(T) bool) int

RemoveFunc deletes every element for which remove returns true and reports how many it deleted. remove must not modify the set.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	s := readyset.New(1, 2, 3, 4, 5, 6)
	removed := s.RemoveFunc(func(n int) bool { return n%2 == 0 })
	fmt.Println(removed, s)
}
Output:
3 {1, 3, 5}

func (*Set[T]) RemoveSet added in v0.2.0

func (s *Set[T]) RemoveSet(other Set[T])

RemoveSet deletes every element of other from the set. It is the in-place counterpart of Set.Difference: afterwards s holds what s.Difference(other) would have returned, and other is not modified.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	all := readyset.New(1, 2, 3)
	all.RemoveSet(readyset.New(2, 9))
	fmt.Println(all)
}
Output:
{1, 3}

func (*Set[T]) RetainSet added in v0.3.0

func (s *Set[T]) RetainSet(other Set[T])

RetainSet deletes every element that is not also in other. It is the in-place counterpart of Set.Intersection: afterwards s holds what s.Intersection(other) would have returned, and other is not modified.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	granted := readyset.New("read", "write", "admin")
	granted.RetainSet(readyset.New("read", "write", "delete"))
	fmt.Println(granted)
}
Output:
{read, write}

func (Set[T]) Slice

func (s Set[T]) Slice() []T

Slice returns the elements of the set as a new slice, in no particular order. The order can differ between calls.

func (Set[T]) String

func (s Set[T]) String() string

String returns the elements in braces, separated by commas, in a stable order: numbers numerically, strings lexically, and any other value by its printed form. It implements fmt.Stringer, so a set prints readably with fmt.Println and the %v and %s verbs.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	// Numbers print in numeric order, whatever order they were added in.
	s := readyset.New(10, 2, 1)
	fmt.Println(s)
}
Output:
{1, 2, 10}

func (Set[T]) SymmetricDifference

func (s Set[T]) SymmetricDifference(other Set[T]) Set[T]

SymmetricDifference returns a new set of the elements that are in exactly one of s and other.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2, 3)
	b := readyset.New(2, 3, 4)
	fmt.Println(a.SymmetricDifference(b))
}
Output:
{1, 4}

func (Set[T]) Union

func (s Set[T]) Union(other Set[T]) Set[T]

Union returns a new set of the elements that are in s, in other, or in both.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2, 3)
	b := readyset.New(3, 4)
	fmt.Println(a.Union(b))
}
Output:
{1, 2, 3, 4}

func (*Set[T]) UnmarshalJSON

func (s *Set[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler. It decodes a JSON array into the set, replacing its previous contents; duplicate elements in the array are collapsed. A JSON null leaves the set unchanged. If decoding fails the set is also left unchanged.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	type Config struct {
		Tags readyset.Set[string] `json:"tags"`
	}
	var c Config
	err := json.Unmarshal([]byte(`{"tags":["go","sets","go"]}`), &c)
	fmt.Println(err, c.Tags.Len(), c.Tags.Contains("sets"))
}
Output:
<nil> 2 true

Directories

Path Synopsis
internal
order
Package order sorts values of any type into a stable, human-friendly order, so that printed and encoded sets do not depend on map iteration order.
Package order sorts values of any type into a stable, human-friendly order, so that printed and encoded sets do not depend on map iteration order.
setlaws
Package setlaws checks the algebraic laws that every set type in this module must satisfy.
Package setlaws checks the algebraic laws that every set type in this module must satisfy.
Package keyed provides a generic Set for elements that are identified by a key rather than by their own value.
Package keyed provides a generic Set for elements that are identified by a key rather than by their own value.

Jump to

Keyboard shortcuts

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