meshio.go raw
1 // Package meshio reads and writes the MESH format, the go-ref binary form of a
2 // lattice Tree with meta, lexicon and adjacency layers.
3 //
4 // No moxie code writes MESH. The format, and every function in this package, is
5 // a port of go-ref/meshio/meshio.go, and the fixed fields are little-endian.
6 // The body slices are copied through unsafe, so the Go layout of
7 // lattice.Node/MetaEntry/LexEntry/AdjLink/KeyMapEntry is the wire layout, and
8 // those layouts are not the .iskr layouts. Renaming a .iskr to .iskr.mesh does
9 // not produce a MESH file: MESH requires a per-key index map that .iskr does
10 // not store, which is why ReadISKR exists below.
11 package meshio
12
13 import (
14 "encoding/binary"
15 "fmt"
16 "io"
17 "os"
18 "sort"
19 "unsafe"
20
21 "git.smesh.lol/go-iskra/lattice"
22 )
23
24 const headerSize = 32
25
26 // KeyMapEntry maps a key to its meta and lex indices.
27 type KeyMapEntry struct {
28 Key uint64
29 MetaIdx uint32
30 LexIdx uint32
31 } // 16 bytes
32
33 // Format limits as the writer lays them out.
34 const (
35 // MaxMetaIndexable is the largest MetaPtr whose block start still falls
36 // inside a Meta slice indexed from 0: MetaPtr+keyPos must be 0..N-1, so the
37 // last usable block start is N-C. Below 9 meta entries nothing is usable.
38 MaxMetaIndexable = uint64(1)<<32 - lattice.C
39 MaxLexIndexable = uint64(1)<<32 - lattice.C
40 )
41
42 func writeHeader(w io.Writer, h MeshHeader, srcLang, tgtLang uint8) error {
43 var buf [headerSize]byte
44 copy(buf[0:4], "MESH")
45 binary.LittleEndian.PutUint16(buf[4:6], 2) // version 2 = POS bitfield
46 buf[6] = srcLang
47 buf[7] = tgtLang
48 binary.LittleEndian.PutUint32(buf[8:12], h.Nodes)
49 binary.LittleEndian.PutUint32(buf[12:16], h.Meta)
50 binary.LittleEndian.PutUint32(buf[16:20], h.Lex)
51 binary.LittleEndian.PutUint32(buf[20:24], h.Adj)
52 binary.LittleEndian.PutUint32(buf[24:28], h.Pool)
53 binary.LittleEndian.PutUint32(buf[28:32], h.KeyMap)
54 _, err := w.Write(buf[:])
55 return err
56 }
57
58 // ParsedHeader is a decoded MESH header.
59 type ParsedHeader struct {
60 Version uint16
61 SrcLang uint8
62 TgtLang uint8
63 NodeCount uint32
64 MetaCount uint32
65 LexCount uint32
66 AdjCount uint32
67 PoolSize uint32
68 KeyMapSize uint32
69 }
70
71 func readHeader(r io.Reader) (ParsedHeader, error) {
72 var buf [headerSize]byte
73 if _, err := io.ReadFull(r, buf[:]); err != nil {
74 return ParsedHeader{}, fmt.Errorf("meshio: read header: %w", err)
75 }
76 if string(buf[0:4]) != "MESH" {
77 return ParsedHeader{}, fmt.Errorf("meshio: bad magic %q (want MESH)", buf[0:4])
78 }
79 version := binary.LittleEndian.Uint16(buf[4:6])
80 if version != 1 && version != 2 {
81 return ParsedHeader{}, fmt.Errorf("meshio: unsupported MESH version %d", version)
82 }
83 return ParsedHeader{
84 Version: version,
85 SrcLang: buf[6],
86 TgtLang: buf[7],
87 NodeCount: binary.LittleEndian.Uint32(buf[8:12]),
88 MetaCount: binary.LittleEndian.Uint32(buf[12:16]),
89 LexCount: binary.LittleEndian.Uint32(buf[16:20]),
90 AdjCount: binary.LittleEndian.Uint32(buf[20:24]),
91 PoolSize: binary.LittleEndian.Uint32(buf[24:28]),
92 KeyMapSize: binary.LittleEndian.Uint32(buf[28:32]),
93 }, nil
94 }
95
96 func writeSliceRaw[T any](w io.Writer, data []T) error {
97 if len(data) == 0 {
98 return nil
99 }
100 size := int(unsafe.Sizeof(data[0]))
101 raw := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(data))), size*len(data))
102 _, err := w.Write(raw)
103 return err
104 }
105
106 func readSliceRaw[T any](r io.Reader, n uint32) ([]T, error) {
107 if n == 0 {
108 return nil, nil
109 }
110 data := make([]T, n)
111 size := int(unsafe.Sizeof(data[0]))
112 raw := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(data))), size*int(n))
113 if _, err := io.ReadFull(r, raw); err != nil {
114 return nil, err
115 }
116 return data, nil
117 }
118
119 // ReadMeshHeader extracts the MESH header fields from a tree.
120 func ReadMeshHeader(t *lattice.Tree) MeshHeader {
121 return MeshHeader{
122 Nodes: uint32(len(t.Nodes)),
123 Meta: uint32(len(t.Meta)),
124 Lex: uint32(len(t.Lex)),
125 Adj: uint32(len(t.Adj)),
126 Pool: uint32(len(t.StringPool)),
127 KeyMap: uint32(len(t.KeyMeta)),
128 }
129 }
130
131 // Validate checks a tree against what MESH can express. It refuses rather than
132 // writing a file whose key map fails to read back.
133 //
134 // The traps it encodes:
135 //
136 // - Record index 0 is the null pointer in MESH. An .iskr holds record 0 (see
137 // lattice.Record), so a tree copied from one must renumber first.
138 // - Block 0 must be the root, and no other block may be a root: Walk starts
139 // at block 0, and RegisterKey only sees the key map MESH carries.
140 // - A populated Meta or Lex pool must start above index 0, because MESH
141 // stores one block start and indexes from 0, and LookupMeta/LookupLex treat
142 // index 0 as null.
143 // - The pool size is a 32-bit field.
144 func Validate(t *lattice.Tree) error {
145 if t.IsMemory() == false {
146 return fmt.Errorf("meshio: Save needs an in-memory tree; load it with lattice.LoadFile first")
147 }
148 if len(t.Nodes) == 0 {
149 return fmt.Errorf("meshio: tree has no blocks")
150 }
151 if len(t.Nodes) > lattice.MaxKeyBlocks {
152 return fmt.Errorf("meshio: %d blocks exceeds the %d a single key per block allows", len(t.Nodes), lattice.MaxKeyBlocks)
153 }
154 if t.Roots[0] != 0 {
155 return fmt.Errorf("meshio: branch root is block %d, MESH walks from block 0", t.Roots[0])
156 }
157 for b := 1; b < lattice.C; b++ {
158 if t.Roots[b] != 0 {
159 return fmt.Errorf("meshio: branch %d has a separate root block %d; MESH has one key space", b, t.Roots[b])
160 }
161 }
162 if t.RecordCount() > 0 {
163 r := t.MustRecord(0)
164 if r.DataLen != 0 || r.DataFile != 0 || r.Link[0] != lattice.NullRec || r.Link[1] != lattice.NullRec || r.Inline != [24]byte{} {
165 return fmt.Errorf("meshio: record 0 holds data, and 0 is MESH's null record pointer; renumber records from 1")
166 }
167 }
168 if len(t.Meta) > 1 && uint64(len(t.Meta)) > 1<<32-1 {
169 return fmt.Errorf("meshio: meta pool of %d entries exceeds the format's 32-bit count", len(t.Meta))
170 }
171 if len(t.Lex) > 1 {
172 if uint64(len(t.Lex)) > 1<<32-1 {
173 return fmt.Errorf("meshio: lex pool of %d entries exceeds the format's 32-bit count", len(t.Lex))
174 }
175 }
176 if uint64(len(t.StringPool)) > 1<<32-1 {
177 return fmt.Errorf("meshio: string pool of %d bytes exceeds the format's 32-bit size", len(t.StringPool))
178 }
179 if uint64(len(t.Adj)) > 1<<32-1 {
180 return fmt.Errorf("meshio: %d adjacency links exceeds the format's 32-bit count", len(t.Adj))
181 }
182 if len(t.KeyMeta) == 0 {
183 return fmt.Errorf("meshio: tree has no key map; MESH cannot carry a tree without one")
184 }
185 for key, v := range t.KeyMeta {
186 if len(t.Meta) > 1 && (v[0] == 0 || int(v[0]) >= len(t.Meta)) {
187 return fmt.Errorf("meshio: key %#x maps to meta %d, outside 1..%d", key, v[0], len(t.Meta)-1)
188 }
189 if len(t.Lex) > 1 && (v[1] == 0 || int(v[1]) >= len(t.Lex)) {
190 return fmt.Errorf("meshio: key %#x maps to lex %d, outside 1..%d", key, v[1], len(t.Lex)-1)
191 }
192 }
193 return nil
194 }
195
196 // Save writes a tree as MESH version 2.
197 func Save(w io.Writer, t *lattice.Tree, srcLang, tgtLang uint8) error {
198 if err := Validate(t); err != nil {
199 return err
200 }
201 h := ReadMeshHeader(t)
202 if err := writeHeader(w, h, srcLang, tgtLang); err != nil {
203 return fmt.Errorf("meshio: write header: %w", err)
204 }
205 if err := writeSliceRaw(w, t.Nodes); err != nil {
206 return fmt.Errorf("meshio: write nodes: %w", err)
207 }
208 if err := writeSliceRaw(w, t.Meta); err != nil {
209 return fmt.Errorf("meshio: write meta: %w", err)
210 }
211 if err := writeSliceRaw(w, t.Lex); err != nil {
212 return fmt.Errorf("meshio: write lex: %w", err)
213 }
214 if err := writeSliceRaw(w, t.Adj); err != nil {
215 return fmt.Errorf("meshio: write adj: %w", err)
216 }
217 if _, err := w.Write(t.StringPool); err != nil {
218 return fmt.Errorf("meshio: write string pool: %w", err)
219 }
220 keyEntries := make([]KeyMapEntry, 0, len(t.KeyMeta))
221 for key, v := range t.KeyMeta {
222 keyEntries = append(keyEntries, KeyMapEntry{Key: uint64(key), MetaIdx: v[0], LexIdx: v[1]})
223 }
224 // The key map is a Go map; sort by (key, meta, lex) so the file is the same
225 // on every save. go-ref wrote map order, which changes between runs.
226 sort.Slice(keyEntries, func(i, j int) bool {
227 if keyEntries[i].Key != keyEntries[j].Key {
228 return keyEntries[i].Key < keyEntries[j].Key
229 }
230 if keyEntries[i].MetaIdx != keyEntries[j].MetaIdx {
231 return keyEntries[i].MetaIdx < keyEntries[j].MetaIdx
232 }
233 return keyEntries[i].LexIdx < keyEntries[j].LexIdx
234 })
235 if err := writeSliceRaw(w, keyEntries); err != nil {
236 return fmt.Errorf("meshio: write keymap: %w", err)
237 }
238 return nil
239 }
240
241 // Load reads a MESH version 1 or 2 file into an in-memory tree, migrating the
242 // v1 POS enum to the v2 bitfield.
243 func Load(r io.Reader) (*lattice.Tree, uint8, uint8, error) {
244 hdr, err := readHeader(r)
245 if err != nil {
246 return nil, 0, 0, err
247 }
248 nodes, err := readSliceRaw[lattice.Node](r, hdr.NodeCount)
249 if err != nil {
250 return nil, 0, 0, fmt.Errorf("meshio: read nodes: %w", err)
251 }
252 meta, err := readSliceRaw[lattice.MetaEntry](r, hdr.MetaCount)
253 if err != nil {
254 return nil, 0, 0, fmt.Errorf("meshio: read meta: %w", err)
255 }
256 if hdr.Version == 1 {
257 for i := range meta {
258 old := uint8(meta[i].PosTag)
259 if old > 0 && old <= 15 {
260 meta[i].PosTag = lattice.POS(1 << (old - 1))
261 }
262 }
263 }
264 lex, err := readSliceRaw[lattice.LexEntry](r, hdr.LexCount)
265 if err != nil {
266 return nil, 0, 0, fmt.Errorf("meshio: read lex: %w", err)
267 }
268 adj, err := readSliceRaw[lattice.AdjLink](r, hdr.AdjCount)
269 if err != nil {
270 return nil, 0, 0, fmt.Errorf("meshio: read adj: %w", err)
271 }
272 pool := make([]byte, hdr.PoolSize)
273 if hdr.PoolSize > 0 {
274 if _, err := io.ReadFull(r, pool); err != nil {
275 return nil, 0, 0, fmt.Errorf("meshio: read string pool: %w", err)
276 }
277 }
278 keyEntries, err := readSliceRaw[KeyMapEntry](r, hdr.KeyMapSize)
279 if err != nil {
280 return nil, 0, 0, fmt.Errorf("meshio: read keymap: %w", err)
281 }
282 tree := lattice.NewMeshTree(nodes, meta, lex, adj, pool)
283 for _, e := range keyEntries {
284 tree.RegisterKey(lattice.Key(e.Key), e.MetaIdx, e.LexIdx)
285 }
286 return tree, hdr.SrcLang, hdr.TgtLang, nil
287 }
288
289 // SaveFile writes a tree to a .mesh file.
290 func SaveFile(path string, t *lattice.Tree, srcLang, tgtLang uint8) error {
291 f, err := os.Create(path)
292 if err != nil {
293 return err
294 }
295 if err := Save(f, t, srcLang, tgtLang); err != nil {
296 f.Close()
297 return err
298 }
299 return f.Close()
300 }
301
302 // LoadFile reads a tree from a .mesh file.
303 func LoadFile(path string) (*lattice.Tree, uint8, uint8, error) {
304 f, err := os.Open(path)
305 if err != nil {
306 return nil, 0, 0, err
307 }
308 defer f.Close()
309 return Load(f)
310 }
311