-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposting.go
More file actions
82 lines (67 loc) · 1.86 KB
/
Copy pathposting.go
File metadata and controls
82 lines (67 loc) · 1.86 KB
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
package tinygram
import (
"bytes"
"encoding/binary"
"fmt"
"io"
)
// Posting represents a single document’s entry in a trigram’s posting list.
// - DocID: the unique identifier of the document
// - DocLength: the total number of trigrams extracted from the document field
// - Frequency: how many times this trigram appears in that document
type Posting struct {
DocID string
DocLength uint16
Frequency uint8
}
// serializes a posting in binary
func serializePosting(p Posting) ([]byte, error) {
buf := new(bytes.Buffer)
// write docID
if len(p.DocID) > 65535 {
return nil, fmt.Errorf("docID too long")
}
if err := binary.Write(buf, binary.LittleEndian, uint16(len(p.DocID))); err != nil {
return nil, err
}
if _, err := buf.WriteString(p.DocID); err != nil {
return nil, err
}
// write docLength
if err := binary.Write(buf, binary.LittleEndian, p.DocLength); err != nil {
return nil, err
}
// write frequency
if err := buf.WriteByte(p.Frequency); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// de-serializes a posting from binary
func deserializePosting(r io.Reader) (Posting, error) {
var p Posting
var idLen uint16
if err := binary.Read(r, binary.LittleEndian, &idLen); err != nil {
return p, err
}
idBytes := make([]byte, idLen)
if _, err := r.Read(idBytes); err != nil {
return p, err
}
p.DocID = string(idBytes)
if err := binary.Read(r, binary.LittleEndian, &p.DocLength); err != nil {
return p, err
}
if err := binary.Read(r, binary.LittleEndian, &p.Frequency); err != nil {
return p, err
}
return p, nil
}
func serializeDocFreq(freq uint32) []byte {
buf := make([]byte, 4)
binary.LittleEndian.PutUint32(buf, freq)
return buf
}
func deserializeDocFreq(data []byte) uint32 {
return binary.LittleEndian.Uint32(data)
}