readyset

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 10 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

CI Coverage Go Reference

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

It also handles sets of records identified by a key, such as users by email or rows by ID, even when the records themselves cannot be compared with ==.

Installation

go get github.com/kastolars/readyset

Requires Go 1.23 or later.

Sets of records

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

type User struct {
    Email string
    Name  string
    Tags  []string // a slice, so User cannot be compared with ==
}

byEmail := func(u User) string { return u.Email }

team := keyed.New(byEmail,
    User{Email: "ann@example.com", Name: "Ann"},
    User{Email: "bob@example.com", Name: "Bob"},
)
oncall := keyed.New(byEmail, User{Email: "bob@example.com"})
newHires := keyed.New(byEmail, User{Email: "cy@example.com", Name: "Cy"})

team.Contains(User{Email: "ann@example.com"}) // true: only the key is compared
team.Difference(oncall)                       // Ann
team.Union(newHires)                          // Ann, Bob and Cy: one User per email

Without this you would keep a map[string]User, write union, intersection and difference yourself, and decide by hand what happens when two sources disagree about the same user. In keyed, two elements are the same element exactly when their keys are equal, and adding an element whose key is already present replaces the stored one.

Sets of values

When your elements are comparable (int, string, structs of comparable fields, ...), a plain readyset.Set is all you need. Two elements are the same when their values are equal.

import "github.com/kastolars/readyset"

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

a.Union(b)        // {1, 2, 3, 4}
a.Intersection(b) // {3}
a.Difference(b)   // {1, 2}
Package Use it when Elements are the same when
readyset your elements are comparable 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

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
readyset.Collect(slices.Values(xs)) // a set from any iter.Seq

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. This continues the example from "Sets of records" above.

team.Add(User{Email: "bob@example.com", Name: "Robert"}) // replaces the stored Bob

u, ok := team.Get("ann@example.com")  // the stored record, found by key
team.ContainsKey("ann@example.com")   // true
team.RemoveKey("ann@example.com")     // remove by key alone, no User needed
team.Keys()                           // []string{"bob@example.com"}, in no particular order

AddSet follows the same replace rule as Add. 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(team) returns the elements in ascending key order. keyed has the same RetainSet, RemoveFunc, Filter, Pop, ContainsAll, ContainsAny and proper-subset methods, plus keyed.Collect(key, seq).

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.

Sharing a set between goroutines

A plain Set is not safe for concurrent use. When goroutines share a set, use SyncSet, which does the locking for you. Both packages have one: readyset.NewSync(...) and keyed.NewSync(key, ...).

seen := readyset.NewSync[string]() // a *SyncSet; the zero value works too

go func() { seen.Add("a") }()
seen.Contains("a")
  • Each method is atomic, a sequence of methods is not. if !seen.Contains(x) { seen.Add(x) } is a race, because another goroutine can add x in between. Do runs several steps under one lock:

    var added bool
    seen.Do(func(set *readyset.Set[string]) {
        if !set.Contains("a") {
            set.Add("a")
            added = true
        }
    })
    
  • Operations between two sets lock both in a fixed order. a.Union(b) and b.Union(a) running at once cannot deadlock, and a.Union(a) is fine.

  • Functions you pass in run under the lock. The callbacks of Filter, RemoveFunc and Do must not call methods on any SyncSet, not only the same one: two callbacks that each lock the other's set can deadlock. To combine two sets use RemoveSet, RetainSet, Intersection and the like, which lock both safely, or take a Snapshot() of the other set first.

  • All() iterates over a copy taken when the loop starts, so the loop body can change the set.

  • Snapshot() returns an independent plain Set, for Sorted or for code that needs no locking. Its elements are copied by value, so anything they point to (a pointer, or in keyed a slice or map inside a record) is still shared, and the lock does not protect it.

  • Use a pointer and never copy one. A SyncSet contains a lock, and go vet reports copies. Hold a *SyncSet in a struct field: a value field cannot be copied safely, and json.Marshal of the struct passed by value writes {} for it.

The lock has a cost, so a plain Set stays the default: use it when one goroutine owns the set or you already hold a mutex. Uncontended, the lock adds about 2 ns to a lookup (4.6 to 6.6 ns) and about 6 ns to an Add (4.4 to 10 ns). When many cores read the same set at once they contend on the lock, and a lookup averaged about 50 ns with 18 cores. For a set that is read by many goroutines and rarely changes, share an immutable Snapshot() instead. The numbers come from go test -bench SyncCost on an Apple M5 Pro.

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 set that holds, or has held, elements to another variable shares the underlying map. Only a zero-value Set that has never held an element copies independently. Use Clone() for an independent copy.
  • Elements must be equal to themselves. A NaN, or a value containing one, is ignored by New, Add and Collect, because a set could never find or remove it again. In keyed, an element whose key is a NaN is ignored.
  • Sets of interface values can panic. In a Set[any], adding or looking up a slice, map or function panics, as a Go map key does. Decoding JSON into one returns an error instead.
  • 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.
  • Set is not safe for concurrent use. Use a SyncSet (see above), or guard the set with your own mutex.
  • 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. One difference in keyed: for a key in both sets, AddSet takes the argument's element, like Add, while Union keeps the receiver's.

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.

There are two kinds of set. 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}

For sets of records identified by a key, such as users by email or rows by ID, including records that cannot be compared with ==, use github.com/kastolars/readyset/keyed. Two elements there are the same element when their keys are equal.

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 ordered slices and from iterators.

A Set is not safe for concurrent use. SyncSet, created with NewSync, is the same set behind a lock, for goroutines that share it.

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.

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.

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 Set that holds or has held elements copies a reference to the same underlying storage; use Set.Clone for an independent copy.

An element must be equal to itself to be in a set, so Set.Add ignores a NaN, or any value containing one: a set could never find or remove it again. If T is an interface type, adding or looking up an element whose dynamic type cannot be compared, such as a slice or a map, panics, as it does for a Go map key.

A Set is not safe for concurrent use; use a SyncSet to share one between goroutines.

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. As with New, an element that is not equal to itself, such as a NaN, is ignored.

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, and so is any element that is not equal to itself, such as a NaN.

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, and so is any element that is not equal to itself, such as a NaN.

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.

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 a set encodes the same way whatever its map iteration order. 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, including when T is an interface type and the array holds an element that cannot be in a set, such as a nested array.

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

type SyncSet added in v0.4.0

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

SyncSet is a Set that is safe for concurrent use by multiple goroutines.

Use it when goroutines share a set and you want the locking done for you. A plain Set is faster and has no restrictions, so prefer it when only one goroutine touches the set at a time, or when you already hold a lock of your own around it.

The zero value is an empty set that is ready to use. A SyncSet contains a lock, so it must be used through a pointer and must not be copied after first use; go vet reports copies. Use NewSync to create one with elements.

Every method is atomic by itself, but a sequence of calls is not. This is a race, because another goroutine can add the element between the two calls:

if !s.Contains(x) { // wrong
	s.Add(x)
}

Use SyncSet.Do to run several steps under one lock.

Operations that take another SyncSet lock both sets, always in the same order, so two goroutines running a.Union(b) and b.Union(a) cannot deadlock, and a.Union(a) is fine. Functions you pass in (to SyncSet.Filter, SyncSet.RemoveFunc and SyncSet.Do) run while the lock is held, so they must not call methods on any SyncSet, not only the same one. A callback that locks a different set does so outside that fixed order, so two callbacks that each use the other's set can deadlock. To combine two sets use a two-set method such as SyncSet.RemoveSet or SyncSet.Intersection, or take a SyncSet.Snapshot of the other set before the call.

The lock protects the set, not what its elements point to. Elements are copied by value into snapshots, clones and slices, and anything an element holds a reference to, such as a pointer, is shared and not locked.

func NewSync added in v0.4.0

func NewSync[T comparable](elements ...T) *SyncSet[T]

NewSync returns a SyncSet containing elements. Duplicates are ignored.

Example

A SyncSet can be shared between goroutines without any locking of your own.

package main

import (
	"fmt"
	"sync"

	"github.com/kastolars/readyset"
)

func main() {
	seen := readyset.NewSync[string]()

	var wg sync.WaitGroup
	for _, word := range []string{"b", "a", "b", "c", "a"} {
		wg.Add(1)
		go func() {
			defer wg.Done()
			seen.Add(word)
		}()
	}
	wg.Wait()

	fmt.Println(seen.Len(), seen)
}
Output:
3 {a, b, c}

func (*SyncSet[T]) Add added in v0.4.0

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

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

func (*SyncSet[T]) AddSet added in v0.4.0

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

AddSet inserts every element of other into the set. It is the in-place counterpart of SyncSet.Union, and other is not modified. See Set.AddSet.

func (*SyncSet[T]) All added in v0.4.0

func (s *SyncSet[T]) All() iter.Seq[T]

All returns an iterator over the elements of the set, in no particular order. The elements are copied when iteration starts, so the loop body may freely change this set (or any other goroutine may) without affecting or deadlocking the loop, and the loop does not see those changes.

func (*SyncSet[T]) Clear added in v0.4.0

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

Clear removes every element from the set.

func (*SyncSet[T]) Clone added in v0.4.0

func (s *SyncSet[T]) Clone() *SyncSet[T]

Clone returns an independent copy of the set.

func (*SyncSet[T]) Contains added in v0.4.0

func (s *SyncSet[T]) Contains(element T) bool

Contains reports whether element is in the set.

func (*SyncSet[T]) ContainsAll added in v0.4.0

func (s *SyncSet[T]) ContainsAll(elements ...T) bool

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

func (*SyncSet[T]) ContainsAny added in v0.4.0

func (s *SyncSet[T]) ContainsAny(elements ...T) bool

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

func (*SyncSet[T]) Difference added in v0.4.0

func (s *SyncSet[T]) Difference(other *SyncSet[T]) *SyncSet[T]

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

func (*SyncSet[T]) Do added in v0.4.0

func (s *SyncSet[T]) Do(fn func(*Set[T]))

Do calls fn with the underlying Set while holding the set's write lock, and returns when fn returns. Use it for a sequence of steps that must not be interleaved with other goroutines, such as adding an element only if it is absent:

var added bool
s.Do(func(set *readyset.Set[string]) {
	if !set.Contains(name) {
		set.Add(name)
		added = true
	}
})

fn must not call methods on s, which would deadlock, or on any other SyncSet, which can deadlock too (see SyncSet), and must not keep the *Set after it returns.

Example

Contains followed by Add is a race, because another goroutine can add the name in between. Do runs both steps under one lock.

package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	names := readyset.NewSync("ann")

	claim := func(name string) bool {
		claimed := false
		names.Do(func(set *readyset.Set[string]) {
			if !set.Contains(name) {
				set.Add(name)
				claimed = true
			}
		})
		return claimed
	}

	fmt.Println(claim("ann"), claim("bob"))
}
Output:
false true

func (*SyncSet[T]) Equal added in v0.4.0

func (s *SyncSet[T]) Equal(other *SyncSet[T]) bool

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

func (*SyncSet[T]) Filter added in v0.4.0

func (s *SyncSet[T]) Filter(keep func(T) bool) *SyncSet[T]

Filter returns a new set of the elements for which keep returns true. keep runs while the set is locked, so it must not call methods on any SyncSet.

func (*SyncSet[T]) Intersection added in v0.4.0

func (s *SyncSet[T]) Intersection(other *SyncSet[T]) *SyncSet[T]

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

func (*SyncSet[T]) IsDisjoint added in v0.4.0

func (s *SyncSet[T]) IsDisjoint(other *SyncSet[T]) bool

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

func (*SyncSet[T]) IsEmpty added in v0.4.0

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

IsEmpty reports whether the set has no elements.

func (*SyncSet[T]) IsProperSubset added in v0.4.0

func (s *SyncSet[T]) IsProperSubset(other *SyncSet[T]) bool

IsProperSubset reports whether s is a subset of other and the two are not equal.

func (*SyncSet[T]) IsProperSuperset added in v0.4.0

func (s *SyncSet[T]) IsProperSuperset(other *SyncSet[T]) bool

IsProperSuperset reports whether s is a superset of other and the two are not equal.

func (*SyncSet[T]) IsSubset added in v0.4.0

func (s *SyncSet[T]) IsSubset(other *SyncSet[T]) bool

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

func (*SyncSet[T]) IsSuperset added in v0.4.0

func (s *SyncSet[T]) IsSuperset(other *SyncSet[T]) bool

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

func (*SyncSet[T]) Len added in v0.4.0

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

Len returns the number of elements in the set.

func (*SyncSet[T]) MarshalJSON added in v0.4.0

func (s *SyncSet[T]) MarshalJSON() ([]byte, error)

MarshalJSON encodes the set as a JSON array in a stable order. See Set.MarshalJSON.

func (*SyncSet[T]) Pop added in v0.4.0

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

Pop removes and returns an arbitrary element of the set. The boolean is false if the set was empty. See Set.Pop.

func (*SyncSet[T]) Remove added in v0.4.0

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

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

func (*SyncSet[T]) RemoveFunc added in v0.4.0

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

RemoveFunc deletes every element for which remove returns true and reports how many it deleted. remove runs while the set is locked, so it must not call methods on any SyncSet.

func (*SyncSet[T]) RemoveSet added in v0.4.0

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

RemoveSet deletes every element of other from the set. It is the in-place counterpart of SyncSet.Difference, and other is not modified.

func (*SyncSet[T]) RetainSet added in v0.4.0

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

RetainSet deletes every element that is not also in other. It is the in-place counterpart of SyncSet.Intersection, and other is not modified.

func (*SyncSet[T]) Slice added in v0.4.0

func (s *SyncSet[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 (*SyncSet[T]) Snapshot added in v0.4.0

func (s *SyncSet[T]) Snapshot() Set[T]

Snapshot returns the elements as a plain, independent Set, for use with Sorted or in code that does not need locking. Later changes to either set do not affect the other. The elements themselves are copied by value, so anything they refer to is still shared.

Example

Snapshot copies a SyncSet into a plain Set, for functions like Sorted.

package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	s := readyset.NewSync(30, 10, 20)
	fmt.Println(readyset.Sorted(s.Snapshot()))
}
Output:
[10 20 30]

func (*SyncSet[T]) String added in v0.4.0

func (s *SyncSet[T]) String() string

String returns the elements in braces, in a stable order. See Set.String.

func (*SyncSet[T]) SymmetricDifference added in v0.4.0

func (s *SyncSet[T]) SymmetricDifference(other *SyncSet[T]) *SyncSet[T]

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

func (*SyncSet[T]) Union added in v0.4.0

func (s *SyncSet[T]) Union(other *SyncSet[T]) *SyncSet[T]

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

func (*SyncSet[T]) UnmarshalJSON added in v0.4.0

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

UnmarshalJSON decodes a JSON array into the set, replacing its previous contents. See Set.UnmarshalJSON.

Directories

Path Synopsis
internal
jsonenc
Package jsonenc encodes the JSON arrays that sets marshal to.
Package jsonenc encodes the JSON arrays that sets marshal to.
lockorder
Package lockorder locks two read-write mutexes together without risking a deadlock.
Package lockorder locks two read-write mutexes together without risking a deadlock.
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