aboutsummaryrefslogtreecommitdiff
path: root/util/kv.go
blob: df616540a8305e69b944f5a00d55bb62095d0504 (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
80
81
82
83
84
85
86
87
88
89
90
91
package util

import (
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"sync"
)

var (
	errInvalidKey = errors.New("invalid key")
	errNoSuchKey  = errors.New("no such key")
)

type Database struct {
	cache   map[string][]byte
	basedir string
	m       sync.RWMutex
}

func NewDatabse(basedir string) (db *Database, err error) {
	err = os.Mkdir(basedir, 0755)
	if err != nil && !os.IsExist(err) {
		return
	}

	return &Database{
		cache:   make(map[string][]byte),
		basedir: basedir,
	}, nil
}

func (db *Database) Set(key string, val []byte) (err error) {
	if len(key) < 1 || strings.ContainsRune(key, os.PathSeparator) {
		return errInvalidKey
	}

	err = ioutil.WriteFile(filepath.Join(db.basedir, key), val, 0644)
	if err != nil {
		return
	}

	db.m.Lock()
	db.cache[key] = val
	db.m.Unlock()

	return
}

func (db *Database) Get(key string) (val []byte, err error) {
	if len(key) < 1 || strings.ContainsRune(key, os.PathSeparator) {
		return nil, errInvalidKey
	}

	db.m.RLock()
	data, ok := db.cache[key]
	db.m.RUnlock()

	if !ok {
		data, err = ioutil.ReadFile(filepath.Join(db.basedir, key))
		if err != nil {
			err = errNoSuchKey
			return nil, err
		}

		db.m.Lock()
		db.cache[key] = data
		db.m.Unlock()
	}

	val = make([]byte, len(data))
	copy(val, data)

	return
}

func (db *Database) Remove(key string) {
	if len(key) < 1 || strings.ContainsRune(key, os.PathSeparator) {
		return
	}

	os.Remove(filepath.Join(db.basedir, key))

	db.m.Lock()
	delete(db.cache, key)
	db.m.Unlock()

	return
}