1 package lattice
2
3 import (
4 "encoding/binary"
5 "fmt"
6 "io"
7 "os"
8 )
9
10 var le = binary.LittleEndian
11
12 // encodeHeader writes the 72-byte header. NodeCap and RecCap are the region
13 // capacities actually laid out on disk.
14 func encodeHeader(t *Tree, nodeCap, recCap uint32) [HeaderSize]byte {
15 var buf [HeaderSize]byte
16 copy(buf[0:4], Magic)
17 le.PutUint16(buf[4:6], Version)
18 le.PutUint32(buf[6:10], t.nCount)
19 le.PutUint32(buf[10:14], t.rCount)
20 le.PutUint32(buf[14:18], uint32(len(t.Pending)))
21 for i := 0; i < C; i++ {
22 le.PutUint32(buf[18+i*4:], t.Roots[i])
23 }
24 le.PutUint32(buf[50:54], t.FreeHead)
25 le.PutUint32(buf[54:58], t.FreeCount)
26 le.PutUint32(buf[58:62], nodeCap)
27 le.PutUint32(buf[62:66], recCap)
28 return buf
29 }
30
31 // DecodeHeader parses the 72-byte header and rejects anything that is not
32 // version 5.
33 func DecodeHeader(buf [HeaderSize]byte) (FileHeader, error) {
34 if string(buf[0:4]) != Magic {
35 return FileHeader{}, fmt.Errorf("lattice: bad magic %q (want %q)", buf[0:4], Magic)
36 }
37 v := le.Uint16(buf[4:6])
38 if v != Version {
39 // Version 4 is not a header-only difference. A version-5 reader applies
40 // version-5 offsets to a version-4 header and lands on the free pointer
41 // as NodeCap and the last root word as FreeHead, so it resolves records
42 // through block 0 while claiming the file is fine (see EmptyLattice).
43 // A version-4 file is opened by translating its header first, which
44 // Migrate4to5 does, or refused here.
45 return FileHeader{}, fmt.Errorf("lattice: file is version %d; this reader is version %d, and a version-4 file must be translated with Migrate4to5 first", v, Version)
46 }
47 h := FileHeader{
48 Version: v,
49 NCount: le.Uint32(buf[6:10]),
50 RCount: le.Uint32(buf[10:14]),
51 PendCount: le.Uint32(buf[14:18]),
52 FreeHead: le.Uint32(buf[50:54]),
53 FreeCount: le.Uint32(buf[54:58]),
54 NodeCap: le.Uint32(buf[58:62]),
55 RecCap: le.Uint32(buf[62:66]),
56 }
57 for i := 0; i < C; i++ {
58 h.Roots[i] = le.Uint32(buf[18+i*4:])
59 }
60 return h, nil
61 }
62
63 // decodeNode4 parses one 200-byte version-4 block: 8 keys of 128 bits, of which
64 // only the low 64 are kept, then the version-5 offsets shifted by 64.
65 func decodeNode4(buf []byte) Node {
66 var n Node
67 for i := 0; i < C; i++ {
68 n.Keys[i] = Key(le.Uint64(buf[i*16:]))
69 }
70 for i := 0; i < C; i++ {
71 n.RecPtrs[i] = le.Uint32(buf[128+i*4:])
72 }
73 for i := 0; i < C+1; i++ {
74 n.Children[i] = le.Uint32(buf[160+i*4:])
75 }
76 n.Mult = buf[196]
77 n.Flags = buf[197]
78 return n
79 }
80
81 // encodeNode4 writes one 200-byte version-4 block: the 64-bit key in the low
82 // half of a 128-bit slot and zeros in the high half, which is the form
83 // Migrate4to5 accepts.
84 func encodeNode4(n *Node, buf []byte) {
85 for i := 0; i < C; i++ {
86 le.PutUint64(buf[i*16:], uint64(n.Keys[i]))
87 le.PutUint64(buf[i*16+8:], 0)
88 }
89 for i := 0; i < C; i++ {
90 le.PutUint32(buf[128+i*4:], n.RecPtrs[i])
91 }
92 for i := 0; i < C+1; i++ {
93 le.PutUint32(buf[160+i*4:], n.Children[i])
94 }
95 buf[196] = n.Mult
96 buf[197] = n.Flags
97 buf[198], buf[199] = 0, 0
98 }
99
100 // encodeNode writes one 136-byte node: 8 keys, 8 record pointers, 9 children,
101 // Mult at 132, Flags at 133.
102 func encodeNode(n *Node, buf []byte) {
103 for i := 0; i < C; i++ {
104 le.PutUint64(buf[i*8:], uint64(n.Keys[i]))
105 }
106 for i := 0; i < C; i++ {
107 le.PutUint32(buf[64+i*4:], n.RecPtrs[i])
108 }
109 for i := 0; i < C+1; i++ {
110 le.PutUint32(buf[96+i*4:], n.Children[i])
111 }
112 buf[132] = n.Mult
113 buf[133] = n.Flags
114 }
115
116 // DecodeNode parses one 136-byte node.
117 func DecodeNode(buf []byte) Node {
118 var n Node
119 for i := 0; i < C; i++ {
120 n.Keys[i] = Key(le.Uint64(buf[i*8:]))
121 }
122 for i := 0; i < C; i++ {
123 n.RecPtrs[i] = le.Uint32(buf[64+i*4:])
124 }
125 for i := 0; i < C+1; i++ {
126 n.Children[i] = le.Uint32(buf[96+i*4:])
127 }
128 n.Mult = buf[132]
129 n.Flags = buf[133]
130 return n
131 }
132
133 // encodeRecord writes one 48-byte record.
134 func encodeRecord(r *Record, buf []byte) {
135 le.PutUint32(buf[0:], r.DataFile)
136 le.PutUint32(buf[4:], r.DataOff)
137 le.PutUint32(buf[8:], r.DataLen)
138 le.PutUint32(buf[12:], r.Link[0])
139 le.PutUint32(buf[16:], r.Link[1])
140 buf[20] = r.Branch
141 buf[21], buf[22], buf[23] = 0, 0, 0
142 copy(buf[24:48], r.Inline[:])
143 }
144
145 // DecodeRecord parses one 48-byte record.
146 func DecodeRecord(buf []byte) Record {
147 var r Record
148 r.DataFile = le.Uint32(buf[0:])
149 r.DataOff = le.Uint32(buf[4:])
150 r.DataLen = le.Uint32(buf[8:])
151 r.Link[0] = le.Uint32(buf[12:])
152 r.Link[1] = le.Uint32(buf[16:])
153 r.Branch = buf[20]
154 copy(r.Inline[:], buf[24:48])
155 return r
156 }
157
158 func encodePending(p *PendingExp, buf []byte) {
159 buf[0] = uint8(p.Branch)
160 le.PutUint16(buf[1:3], p.Depth)
161 buf[3] = p.Factor
162 }
163
164 // Save writes a complete .iskr image: header, all in-use nodes, all records,
165 // then the expansion journal. NodeCap and RecCap equal the in-use counts.
166 func Save(w io.Writer, t *Tree) error {
167 if !t.IsMemory() {
168 return fmt.Errorf("lattice: Save needs an in-memory tree; a disk-backed tree writes through Flush")
169 }
170 hdr := encodeHeader(t, t.nCount, t.rCount)
171 if _, err := w.Write(hdr[:]); err != nil {
172 return fmt.Errorf("lattice: header: %w", err)
173 }
174 nb := make([]byte, NodeSize)
175 for i := uint32(0); i < t.nCount; i++ {
176 encodeNode(&t.Nodes[i], nb)
177 if _, err := w.Write(nb); err != nil {
178 return fmt.Errorf("lattice: node %d: %w", i, err)
179 }
180 }
181 rb := make([]byte, RecordSize)
182 for i := uint32(0); i < t.rCount; i++ {
183 encodeRecord(&t.Records[i], rb)
184 if _, err := w.Write(rb); err != nil {
185 return fmt.Errorf("lattice: record %d: %w", i, err)
186 }
187 }
188 pb := make([]byte, PendingSize)
189 for i := range t.Pending {
190 encodePending(&t.Pending[i], pb)
191 if _, err := w.Write(pb); err != nil {
192 return fmt.Errorf("lattice: pending %d: %w", i, err)
193 }
194 }
195 return nil
196 }
197
198 // Load reads a complete .iskr image into an in-memory tree.
199 func Load(r io.Reader) (*Tree, error) {
200 var hb [HeaderSize]byte
201 if _, err := io.ReadFull(r, hb[:]); err != nil {
202 return nil, fmt.Errorf("lattice: read header: %w", err)
203 }
204 hdr, err := DecodeHeader(hb)
205 if err != nil {
206 return nil, err
207 }
208 t := AllocTree(hdr.NCount, hdr.RCount, hdr.Roots)
209 t.FreeHead = hdr.FreeHead
210 t.FreeCount = hdr.FreeCount
211 nb := make([]byte, NodeSize)
212 for i := uint32(0); i < hdr.NCount; i++ {
213 if _, err := io.ReadFull(r, nb); err != nil {
214 return nil, fmt.Errorf("lattice: node %d: %w", i, err)
215 }
216 t.Nodes[i] = DecodeNode(nb)
217 }
218 t.SourceVersion = Version
219 rb := make([]byte, RecordSize)
220 for i := uint32(0); i < hdr.RCount; i++ {
221 if _, err := io.ReadFull(r, rb); err != nil {
222 return nil, fmt.Errorf("lattice: record %d: %w", i, err)
223 }
224 t.Records[i] = DecodeRecord(rb)
225 }
226 if hdr.PendCount > 0 {
227 pb := make([]byte, PendingSize)
228 t.Pending = make([]PendingExp, hdr.PendCount)
229 for i := uint32(0); i < hdr.PendCount; i++ {
230 if _, err := io.ReadFull(r, pb); err != nil {
231 return nil, fmt.Errorf("lattice: pending %d: %w", i, err)
232 }
233 t.Pending[i] = PendingExp{
234 Branch: Branch(pb[0]),
235 Depth: le.Uint16(pb[1:3]),
236 Factor: pb[3],
237 }
238 }
239 }
240 t.rebuildRecKey()
241 return t, nil
242 }
243
244 // SaveFile writes an in-memory tree to path.
245 func SaveFile(path string, t *Tree) error {
246 f, err := os.Create(path)
247 if err != nil {
248 return err
249 }
250 if err := Save(f, t); err != nil {
251 f.Close()
252 return err
253 }
254 return f.Close()
255 }
256
257 // LoadFile reads a tree from path into memory.
258 func LoadFile(path string) (*Tree, error) {
259 f, err := os.Open(path)
260 if err != nil {
261 return nil, err
262 }
263 defer f.Close()
264 return Load(f)
265 }
266
267 // Migrate4to5 converts a version-4 .iskr (128-bit keys, 200-byte blocks) into
268 // a version-5 file by keeping the low 64 bits of every key. Records and the
269 // pending journal pass through unchanged. The version-4 header's region
270 // capacities do not describe migratable content, so the source nodes and
271 // records are read by their in-use counts and not by their capacities.
272 func Migrate4to5(src, dst string) error {
273 f, err := os.Open(src)
274 if err != nil {
275 return err
276 }
277 defer f.Close()
278 var hbuf [HeaderSize]byte
279 if _, err := io.ReadFull(f, hbuf[:]); err != nil {
280 return fmt.Errorf("lattice: migrate: read header: %w", err)
281 }
282 if string(hbuf[0:4]) != Magic {
283 return fmt.Errorf("lattice: migrate: bad magic %q", hbuf[0:4])
284 }
285 if v := le.Uint16(hbuf[4:6]); v != Version4 {
286 return fmt.Errorf("lattice: migrate: source is version %d, want %d", v, Version4)
287 }
288 nCount := le.Uint32(hbuf[6:10])
289 rCount := le.Uint32(hbuf[10:14])
290 pendCount := le.Uint32(hbuf[14:18])
291 var roots [C]uint32
292 for i := 0; i < C; i++ {
293 roots[i] = le.Uint32(hbuf[18+i*4:])
294 }
295 t := AllocTree(nCount, rCount, roots)
296 t.FreeHead = le.Uint32(hbuf[50:54])
297 t.FreeCount = le.Uint32(hbuf[54:58])
298 nb := make([]byte, NodeSize4)
299 for i := uint32(0); i < nCount; i++ {
300 if _, err := io.ReadFull(f, nb); err != nil {
301 return fmt.Errorf("lattice: migrate: node %d: %w", i, err)
302 }
303 t.Nodes[i] = decodeNode4(nb)
304 }
305 rb := make([]byte, RecordSize)
306 for i := uint32(0); i < rCount; i++ {
307 if _, err := io.ReadFull(f, rb); err != nil {
308 return fmt.Errorf("lattice: migrate: record %d: %w", i, err)
309 }
310 t.Records[i] = DecodeRecord(rb)
311 }
312 if pendCount > 0 {
313 pb := make([]byte, PendingSize)
314 t.Pending = make([]PendingExp, pendCount)
315 for i := uint32(0); i < pendCount; i++ {
316 if _, err := io.ReadFull(f, pb); err != nil {
317 return fmt.Errorf("lattice: migrate: pending %d: %w", i, err)
318 }
319 t.Pending[i] = PendingExp{Branch: Branch(pb[0]), Depth: le.Uint16(pb[1:3]), Factor: pb[3]}
320 }
321 }
322 t.SourceVersion = 0
323 return SaveFile(dst, t)
324 }
325
326 // encodeRecordBytes returns the 48-byte encoding of one record.
327 func encodeRecordBytes(r *Record) []byte {
328 b := make([]byte, RecordSize)
329 encodeRecord(r, b)
330 return b
331 }
332