/
codec.go
57 lines (49 loc) · 1.24 KB
/
codec.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
package codec
import (
"io"
"runtime"
"sync/atomic"
"time"
)
const (
headerKeySize int64 = 4 // uint32
headerValueSize int64 = 8 // uint64
headerChecksumSize int64 = 4 // uint32
headerTTLSize int64 = 8 // uint64
HeaderSize int64 = headerKeySize + headerValueSize + headerChecksumSize + headerTTLSize // 24 byte
)
var (
_ io.ReadCloser = (*Payload)(nil)
)
type Header struct {
KeySize int32
ValueSize int64
Checksum uint32
Expiry time.Time
N int64
}
type Payload struct {
Key []byte
Value io.Reader
Checksum uint32
Expiry time.Time
N int64
ValueSize int64
closed int32
release func()
}
func (p *Payload) Read(buf []byte) (int, error) {
return p.Value.Read(buf)
}
func (p *Payload) Close() error {
if atomic.CompareAndSwapInt32(&p.closed, 0, 1) {
runtime.SetFinalizer(p, nil) // clear finalizer
if p.release != nil {
p.release()
}
}
return nil
}
func finalizePayload(p *Payload) {
p.Close()
}