-
Notifications
You must be signed in to change notification settings - Fork 2
/
item.go
101 lines (83 loc) · 2.11 KB
/
item.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package forget
import (
"sync"
"time"
)
type item struct {
hash uint64
keyspace string
keySize, size int
firstChunk, lastChunk node
chunkOffset int
expires time.Time
readers int
writeComplete, discarded bool
writeCond *sync.Cond
prevItem, nextItem node
}
func newItem(hash uint64, keyspace string, keySize int, ttl time.Duration) *item {
return &item{
hash: hash,
keyspace: keyspace,
keySize: keySize,
expires: time.Now().Add(ttl),
writeCond: sync.NewCond(&sync.Mutex{}),
}
}
func (i *item) prev() node { return i.prevItem }
func (i *item) next() node { return i.nextItem }
func (i *item) setPrev(p node) { i.prevItem = p }
func (i *item) setNext(n node) { i.nextItem = n }
func (i *item) expired() bool {
return i.expires.Before(time.Now())
}
func (i *item) data() (*chunk, *chunk) {
if i.firstChunk == nil {
return nil, nil
}
return i.firstChunk.(*chunk), i.lastChunk.(*chunk)
}
func (i *item) appendChunk(s *chunk) {
if i.firstChunk == nil {
i.firstChunk = s
}
i.lastChunk = s
i.chunkOffset = 0
}
// checks if a key equals with the item's key. Keys are stored in the underlying chunks, if a key spans
// multiple chunks, keyEquals proceeds through the required number of chunks.
func (i *item) keyEquals(key string) bool {
if len(key) != i.keySize {
return false
}
p, s := []byte(key), i.firstChunk
for len(p) > 0 && s != nil {
ok, n := s.(*chunk).bytesEqual(0, p)
if !ok {
return false
}
p, s = p[n:], s.next()
}
return len(p) == 0
}
// writes from the last used chunk position of the last chunk, maximum to the end of the chunk
func (i *item) write(p []byte) (int, error) {
if i.discarded {
return 0, ErrItemDiscarded
}
if i.lastChunk == nil {
return 0, nil
}
n := i.lastChunk.(*chunk).write(i.chunkOffset, p)
i.size += n
i.chunkOffset += n
return n, nil
}
// closes the item and releases the underlying chunks
func (i *item) close() {
i.discarded = true
i.firstChunk = nil
i.lastChunk = nil
i.prevItem = nil
i.nextItem = nil
}