~tsileo/blobstash

ref: b178995e346d blobstash/pkg/backend/s3/index/index.go -rw-r--r-- 1.7 KiB
b178995eThomas Sileo vendor: update deps 2 years ago
                                                                                
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package index // import "a4.io/blobstash/pkg/backend/s3/index"

import (
	"encoding/hex"
	"sync"

	"a4.io/blobstash/pkg/rangedb"
)

// Queue is a FIFO queue,
type Index struct {
	db   *rangedb.RangeDB
	path string
	sync.Mutex
}

// New creates a new database.
func New(path string) (*Index, error) {
	kvdb, err := rangedb.New(path)
	if err != nil {
		return nil, err
	}

	return &Index{
		db:   kvdb,
		path: path,
	}, nil
}

// Remove the underlying db file.
func (i *Index) Remove() error {
	return i.db.Destroy()
}

// Close the underlying db file.
func (i *Index) Close() error {
	return i.db.Close()
}

func (i *Index) Index(plainHash, encryptedHash string) error {
	i.Lock()
	defer i.Unlock()
	phash, err := hex.DecodeString(plainHash)
	if err != nil {
		return err
	}
	ehash, err := hex.DecodeString(encryptedHash)
	if err != nil {
		return err
	}
	return i.db.Set(phash, ehash)
}

func (i *Index) Delete(hash string) error {
	i.Lock()
	defer i.Unlock()
	bhash, err := hex.DecodeString(hash)
	if err != nil {
		return err
	}
	if err := i.db.Delete(bhash); err != nil {
		return err
	}
	return nil
}

func (i *Index) Exists(hash string) (bool, error) {
	i.Lock()
	defer i.Unlock()
	bhash, err := hex.DecodeString(hash)
	if err != nil {
		return false, err
	}
	exists, err := i.db.Get(bhash)
	if err != nil {
		return false, err
	}
	if exists != nil {
		return true, nil
	}
	return false, nil
}

func (i *Index) Get(hash string) (string, error) {
	i.Lock()
	defer i.Unlock()
	bhash, err := hex.DecodeString(hash)
	if err != nil {
		return "", err
	}
	v, err := i.db.Get(bhash)
	if err != nil {
		return "", err
	}
	if v != nil {
		return hex.EncodeToString(v), nil
	}
	return "", nil
}