summaryrefslogtreecommitdiff
path: root/lib/containers/set.go
blob: e20b5becd3242f25498fd5519e0e3c36902442a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package containers

import (
	"io"

	"git.lukeshu.com/go/lowmemjson"
	"golang.org/x/exp/constraints"

	"git.lukeshu.com/btrfs-progs-ng/lib/maps"
)

type Set[T constraints.Ordered] map[T]struct{}

var (
	_ lowmemjson.Encodable = Set[int]{}
	_ lowmemjson.Decodable = (*Set[int])(nil)
)

func (o Set[T]) EncodeJSON(w io.Writer) error {
	return lowmemjson.Encode(w, maps.SortedKeys(o))
}

func (o *Set[T]) DecodeJSON(r io.RuneScanner) error {
	c, _, _ := r.ReadRune()
	if c == 'n' {
		_, _, _ = r.ReadRune() // u
		_, _, _ = r.ReadRune() // l
		_, _, _ = r.ReadRune() // l
		*o = nil
		return nil
	}
	_ = r.UnreadRune()
	*o = Set[T]{}
	return lowmemjson.DecodeArray(r, func(r io.RuneScanner) error {
		var val T
		if err := lowmemjson.Decode(r, &val); err != nil {
			return err
		}
		(*o)[val] = struct{}{}
		return nil
	})
}

func (o *Set[T]) Insert(v T) {
	if o == nil {
		*o = Set[T]{}
	}
	(*o)[v] = struct{}{}
}

func (o *Set[T]) Delete(v T) {
	if o == nil {
		return
	}
	delete(*o, v)
}