-
Notifications
You must be signed in to change notification settings - Fork 8
/
keydir.go
66 lines (55 loc) · 1.54 KB
/
keydir.go
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
package barrel
import (
"encoding/gob"
"os"
)
// KeyDir represents an in-memory hash for faster lookups of the key.
// Once the key is found in the map, the additional metadata like the offset record
// and the file ID is used to extract the underlying record from the disk.
// Advantage is that this approach only requires a single disk seek of the db file
// since the position offset (in bytes) is already stored.
type KeyDir map[string]Meta
// Meta represents some additional properties for the given key.
// The actual value of the key is not stored in the in-memory hashtable.
type Meta struct {
Timestamp int
RecordSize int
RecordPos int
FileID int
}
// Encode encodes the map to a gob file.
// This is typically used to generate a hints file.
// Caller of this program should ensure to lock/unlock the map before calling.
func (k *KeyDir) Encode(fPath string) error {
// Create a file for storing gob data.
file, err := os.Create(fPath)
if err != nil {
return err
}
defer file.Close()
// Create a new gob encoder.
encoder := gob.NewEncoder(file)
// Encode the map and save it to the file.
err = encoder.Encode(k)
if err != nil {
return err
}
return nil
}
// Decode decodes the gob data in the map.
func (k *KeyDir) Decode(fPath string) error {
// Open the file for decoding gob data.
file, err := os.Open(fPath)
if err != nil {
return err
}
defer file.Close()
// Create a new gob decoder.
decoder := gob.NewDecoder(file)
// Decode the file to the map.
err = decoder.Decode(k)
if err != nil {
return err
}
return nil
}