forked from miku/microblob
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend_safe.go
76 lines (64 loc) · 1.63 KB
/
backend_safe.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
67
68
69
70
71
72
73
74
75
76
// +build !darwin,!dragonfly,!freebsd,!linux,!nacl,!netbsd,!openbsd,!solaris
package microblob
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"sync"
)
var mu sync.Mutex // Protects seek and read on systems without pread.
// Get retrieves the data for a given key.
// Raw timings of the operations:
// Cold:
// time.Now(): 89ns
// b.openDatabase(): 2.692719ms
// b.db.Get: 5.441917ms
// binary.ReadVarint: 5.456746ms
// make([]byte, length): 5.473913ms
// b.blob.Seek: 5.479361ms
// b.blob.Read: 5.487422ms
// Warm:
// time.Now(): 57ns
// b.openDatabase(): 86.018µs
// b.db.Get: 139.769µs
// binary.ReadVarint: 155.258µs
// make([]byte, length): 210.089µs
// b.blob.Seek: 218.031µs
// b.blob.Read: 252.66µs
//
func (b *LevelDBBackend) Get(key string) (data []byte, err error) {
if err = b.openDatabase(); err != nil {
return nil, err
}
var value []byte
var offset, length int64
if value, err = b.db.Get([]byte(key), nil); err != nil {
return nil, err
}
if len(value) < 16 {
return nil, ErrInvalidValue
}
if offset, err = binary.ReadVarint(bytes.NewBuffer(value[:8])); err != nil {
return nil, err
}
if length, err = binary.ReadVarint(bytes.NewBuffer(value[8:])); err != nil {
return nil, err
}
if err = b.openBlob(); err != nil {
return nil, err
}
data = make([]byte, length)
mu.Lock()
defer mu.Unlock()
if _, err = b.blob.Seek(offset, io.SeekStart); err != nil {
return nil, err
}
if _, err = b.blob.Read(data); err != nil {
return nil, err
}
if !b.AllowEmptyValues && IsAllZero(data) {
return nil, fmt.Errorf("empty value")
}
return data, nil
}