aboutsummaryrefslogtreecommitdiff
path: root/storage/index.go
blob: 1d01b93975642bfa3bdec611d088ad14bf2c1034 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package storage

import (
	"bufio"
	"code.laria.me/petrific/objects"
	"fmt"
	"io"
	"strings"
)

type Index map[objects.ObjectType]map[string]struct{}

func NewIndex() Index {
	idx := make(Index)
	idx.Init()
	return idx
}

func (idx Index) Init() {
	for _, t := range objects.AllObjectTypes {
		idx[t] = make(map[string]struct{})
	}
}

func (idx Index) Set(id objects.ObjectId, typ objects.ObjectType) {
	idx[typ][id.String()] = struct{}{}
}

func (idx Index) List(typ objects.ObjectType) []objects.ObjectId {
	ids := make([]objects.ObjectId, 0, len(idx[typ]))
	for id := range idx[typ] {
		ids = append(ids, objects.MustParseObjectId(id))
	}

	return ids
}

func (idx Index) Save(w io.Writer) error {
	for t, objs := range idx {
		for id := range objs {
			if _, err := fmt.Fprintf(w, "%s %s\n", t, id); err != nil {
				return err
			}
		}
	}
	return nil
}

func (idx Index) Load(r io.Reader) error {
	scan := bufio.NewScanner(r)
	for scan.Scan() {
		line := scan.Text()

		parts := strings.SplitN(strings.TrimSpace(line), " ", 2)
		if len(parts) == 2 {
			id, err := objects.ParseObjectId(parts[1])
			if err != nil {
				return err
			}

			typ := objects.ObjectType(parts[0])

			if _, ok := idx[typ]; !ok {
				return fmt.Errorf("Failed loading index: Unknown ObjectType %s", typ)
			}

			idx[typ][id.String()] = struct{}{}
		}
	}
	return scan.Err()
}

func (a Index) Combine(b Index) {
	for t, objs := range b {
		for id := range objs {
			a[t][id] = struct{}{}
		}
	}
}