forked from beeker1121/goque
-
Notifications
You must be signed in to change notification settings - Fork 0
/
item.go
68 lines (59 loc) · 1.65 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
package goque
import (
"bytes"
"encoding/binary"
"encoding/gob"
)
// Item represents an entry in either a stack or queue.
type Item struct {
ID uint64
Key []byte
Value []byte
}
// ToString returns the item value as a string.
func (i *Item) ToString() string {
return string(i.Value)
}
// ToObject decodes the item value into the given value type using
// encoding/gob.
//
// The value passed to this method should be a pointer to a variable
// of the type you wish to decode into. The variable pointed to will
// hold the decoded object.
func (i *Item) ToObject(value interface{}) error {
buffer := bytes.NewBuffer(i.Value)
dec := gob.NewDecoder(buffer)
return dec.Decode(value)
}
// PriorityItem represents an entry in a priority queue.
type PriorityItem struct {
ID uint64
Priority uint8
Key []byte
Value []byte
}
// ToString returns the priority item value as a string.
func (pi *PriorityItem) ToString() string {
return string(pi.Value)
}
// ToObject decodes the item value into the given value type using
// encoding/gob.
//
// The value passed to this method should be a pointer to a variable
// of the type you wish to decode into. The variable pointed to will
// hold the decoded object.
func (pi *PriorityItem) ToObject(value interface{}) error {
buffer := bytes.NewBuffer(pi.Value)
dec := gob.NewDecoder(buffer)
return dec.Decode(value)
}
// idToKey converts and returns the given ID to a key.
func idToKey(id uint64) []byte {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, id)
return key
}
// keyToID converts and returns the given key to an ID.
func keyToID(key []byte) uint64 {
return binary.BigEndian.Uint64(key)
}