// Package meshio reads and writes the MESH format, the go-ref binary form of a // lattice Tree with meta, lexicon and adjacency layers. // // No moxie code writes MESH. The format, and every function in this package, is // a port of go-ref/meshio/meshio.go, and the fixed fields are little-endian. // The body slices are copied through unsafe, so the Go layout of // lattice.Node/MetaEntry/LexEntry/AdjLink/KeyMapEntry is the wire layout, and // those layouts are not the .iskr layouts. Renaming a .iskr to .iskr.mesh does // not produce a MESH file: MESH requires a per-key index map that .iskr does // not store, which is why ReadISKR exists below. package meshio import ( "encoding/binary" "fmt" "io" "os" "sort" "unsafe" "git.smesh.lol/go-iskra/lattice" ) const headerSize = 32 // KeyMapEntry maps a key to its meta and lex indices. type KeyMapEntry struct { Key uint64 MetaIdx uint32 LexIdx uint32 } // 16 bytes // Format limits as the writer lays them out. const ( // MaxMetaIndexable is the largest MetaPtr whose block start still falls // inside a Meta slice indexed from 0: MetaPtr+keyPos must be 0..N-1, so the // last usable block start is N-C. Below 9 meta entries nothing is usable. MaxMetaIndexable = uint64(1)<<32 - lattice.C MaxLexIndexable = uint64(1)<<32 - lattice.C ) func writeHeader(w io.Writer, h MeshHeader, srcLang, tgtLang uint8) error { var buf [headerSize]byte copy(buf[0:4], "MESH") binary.LittleEndian.PutUint16(buf[4:6], 2) // version 2 = POS bitfield buf[6] = srcLang buf[7] = tgtLang binary.LittleEndian.PutUint32(buf[8:12], h.Nodes) binary.LittleEndian.PutUint32(buf[12:16], h.Meta) binary.LittleEndian.PutUint32(buf[16:20], h.Lex) binary.LittleEndian.PutUint32(buf[20:24], h.Adj) binary.LittleEndian.PutUint32(buf[24:28], h.Pool) binary.LittleEndian.PutUint32(buf[28:32], h.KeyMap) _, err := w.Write(buf[:]) return err } // ParsedHeader is a decoded MESH header. type ParsedHeader struct { Version uint16 SrcLang uint8 TgtLang uint8 NodeCount uint32 MetaCount uint32 LexCount uint32 AdjCount uint32 PoolSize uint32 KeyMapSize uint32 } func readHeader(r io.Reader) (ParsedHeader, error) { var buf [headerSize]byte if _, err := io.ReadFull(r, buf[:]); err != nil { return ParsedHeader{}, fmt.Errorf("meshio: read header: %w", err) } if string(buf[0:4]) != "MESH" { return ParsedHeader{}, fmt.Errorf("meshio: bad magic %q (want MESH)", buf[0:4]) } version := binary.LittleEndian.Uint16(buf[4:6]) if version != 1 && version != 2 { return ParsedHeader{}, fmt.Errorf("meshio: unsupported MESH version %d", version) } return ParsedHeader{ Version: version, SrcLang: buf[6], TgtLang: buf[7], NodeCount: binary.LittleEndian.Uint32(buf[8:12]), MetaCount: binary.LittleEndian.Uint32(buf[12:16]), LexCount: binary.LittleEndian.Uint32(buf[16:20]), AdjCount: binary.LittleEndian.Uint32(buf[20:24]), PoolSize: binary.LittleEndian.Uint32(buf[24:28]), KeyMapSize: binary.LittleEndian.Uint32(buf[28:32]), }, nil } func writeSliceRaw[T any](w io.Writer, data []T) error { if len(data) == 0 { return nil } size := int(unsafe.Sizeof(data[0])) raw := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(data))), size*len(data)) _, err := w.Write(raw) return err } func readSliceRaw[T any](r io.Reader, n uint32) ([]T, error) { if n == 0 { return nil, nil } data := make([]T, n) size := int(unsafe.Sizeof(data[0])) raw := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(data))), size*int(n)) if _, err := io.ReadFull(r, raw); err != nil { return nil, err } return data, nil } // ReadMeshHeader extracts the MESH header fields from a tree. func ReadMeshHeader(t *lattice.Tree) MeshHeader { return MeshHeader{ Nodes: uint32(len(t.Nodes)), Meta: uint32(len(t.Meta)), Lex: uint32(len(t.Lex)), Adj: uint32(len(t.Adj)), Pool: uint32(len(t.StringPool)), KeyMap: uint32(len(t.KeyMeta)), } } // Validate checks a tree against what MESH can express. It refuses rather than // writing a file whose key map fails to read back. // // The traps it encodes: // // - Record index 0 is the null pointer in MESH. An .iskr holds record 0 (see // lattice.Record), so a tree copied from one must renumber first. // - Block 0 must be the root, and no other block may be a root: Walk starts // at block 0, and RegisterKey only sees the key map MESH carries. // - A populated Meta or Lex pool must start above index 0, because MESH // stores one block start and indexes from 0, and LookupMeta/LookupLex treat // index 0 as null. // - The pool size is a 32-bit field. func Validate(t *lattice.Tree) error { if t.IsMemory() == false { return fmt.Errorf("meshio: Save needs an in-memory tree; load it with lattice.LoadFile first") } if len(t.Nodes) == 0 { return fmt.Errorf("meshio: tree has no blocks") } if len(t.Nodes) > lattice.MaxKeyBlocks { return fmt.Errorf("meshio: %d blocks exceeds the %d a single key per block allows", len(t.Nodes), lattice.MaxKeyBlocks) } if t.Roots[0] != 0 { return fmt.Errorf("meshio: branch root is block %d, MESH walks from block 0", t.Roots[0]) } for b := 1; b < lattice.C; b++ { if t.Roots[b] != 0 { return fmt.Errorf("meshio: branch %d has a separate root block %d; MESH has one key space", b, t.Roots[b]) } } if t.RecordCount() > 0 { r := t.MustRecord(0) if r.DataLen != 0 || r.DataFile != 0 || r.Link[0] != lattice.NullRec || r.Link[1] != lattice.NullRec || r.Inline != [24]byte{} { return fmt.Errorf("meshio: record 0 holds data, and 0 is MESH's null record pointer; renumber records from 1") } } if len(t.Meta) > 1 && uint64(len(t.Meta)) > 1<<32-1 { return fmt.Errorf("meshio: meta pool of %d entries exceeds the format's 32-bit count", len(t.Meta)) } if len(t.Lex) > 1 { if uint64(len(t.Lex)) > 1<<32-1 { return fmt.Errorf("meshio: lex pool of %d entries exceeds the format's 32-bit count", len(t.Lex)) } } if uint64(len(t.StringPool)) > 1<<32-1 { return fmt.Errorf("meshio: string pool of %d bytes exceeds the format's 32-bit size", len(t.StringPool)) } if uint64(len(t.Adj)) > 1<<32-1 { return fmt.Errorf("meshio: %d adjacency links exceeds the format's 32-bit count", len(t.Adj)) } if len(t.KeyMeta) == 0 { return fmt.Errorf("meshio: tree has no key map; MESH cannot carry a tree without one") } for key, v := range t.KeyMeta { if len(t.Meta) > 1 && (v[0] == 0 || int(v[0]) >= len(t.Meta)) { return fmt.Errorf("meshio: key %#x maps to meta %d, outside 1..%d", key, v[0], len(t.Meta)-1) } if len(t.Lex) > 1 && (v[1] == 0 || int(v[1]) >= len(t.Lex)) { return fmt.Errorf("meshio: key %#x maps to lex %d, outside 1..%d", key, v[1], len(t.Lex)-1) } } return nil } // Save writes a tree as MESH version 2. func Save(w io.Writer, t *lattice.Tree, srcLang, tgtLang uint8) error { if err := Validate(t); err != nil { return err } h := ReadMeshHeader(t) if err := writeHeader(w, h, srcLang, tgtLang); err != nil { return fmt.Errorf("meshio: write header: %w", err) } if err := writeSliceRaw(w, t.Nodes); err != nil { return fmt.Errorf("meshio: write nodes: %w", err) } if err := writeSliceRaw(w, t.Meta); err != nil { return fmt.Errorf("meshio: write meta: %w", err) } if err := writeSliceRaw(w, t.Lex); err != nil { return fmt.Errorf("meshio: write lex: %w", err) } if err := writeSliceRaw(w, t.Adj); err != nil { return fmt.Errorf("meshio: write adj: %w", err) } if _, err := w.Write(t.StringPool); err != nil { return fmt.Errorf("meshio: write string pool: %w", err) } keyEntries := make([]KeyMapEntry, 0, len(t.KeyMeta)) for key, v := range t.KeyMeta { keyEntries = append(keyEntries, KeyMapEntry{Key: uint64(key), MetaIdx: v[0], LexIdx: v[1]}) } // The key map is a Go map; sort by (key, meta, lex) so the file is the same // on every save. go-ref wrote map order, which changes between runs. sort.Slice(keyEntries, func(i, j int) bool { if keyEntries[i].Key != keyEntries[j].Key { return keyEntries[i].Key < keyEntries[j].Key } if keyEntries[i].MetaIdx != keyEntries[j].MetaIdx { return keyEntries[i].MetaIdx < keyEntries[j].MetaIdx } return keyEntries[i].LexIdx < keyEntries[j].LexIdx }) if err := writeSliceRaw(w, keyEntries); err != nil { return fmt.Errorf("meshio: write keymap: %w", err) } return nil } // Load reads a MESH version 1 or 2 file into an in-memory tree, migrating the // v1 POS enum to the v2 bitfield. func Load(r io.Reader) (*lattice.Tree, uint8, uint8, error) { hdr, err := readHeader(r) if err != nil { return nil, 0, 0, err } nodes, err := readSliceRaw[lattice.Node](r, hdr.NodeCount) if err != nil { return nil, 0, 0, fmt.Errorf("meshio: read nodes: %w", err) } meta, err := readSliceRaw[lattice.MetaEntry](r, hdr.MetaCount) if err != nil { return nil, 0, 0, fmt.Errorf("meshio: read meta: %w", err) } if hdr.Version == 1 { for i := range meta { old := uint8(meta[i].PosTag) if old > 0 && old <= 15 { meta[i].PosTag = lattice.POS(1 << (old - 1)) } } } lex, err := readSliceRaw[lattice.LexEntry](r, hdr.LexCount) if err != nil { return nil, 0, 0, fmt.Errorf("meshio: read lex: %w", err) } adj, err := readSliceRaw[lattice.AdjLink](r, hdr.AdjCount) if err != nil { return nil, 0, 0, fmt.Errorf("meshio: read adj: %w", err) } pool := make([]byte, hdr.PoolSize) if hdr.PoolSize > 0 { if _, err := io.ReadFull(r, pool); err != nil { return nil, 0, 0, fmt.Errorf("meshio: read string pool: %w", err) } } keyEntries, err := readSliceRaw[KeyMapEntry](r, hdr.KeyMapSize) if err != nil { return nil, 0, 0, fmt.Errorf("meshio: read keymap: %w", err) } tree := lattice.NewMeshTree(nodes, meta, lex, adj, pool) for _, e := range keyEntries { tree.RegisterKey(lattice.Key(e.Key), e.MetaIdx, e.LexIdx) } return tree, hdr.SrcLang, hdr.TgtLang, nil } // SaveFile writes a tree to a .mesh file. func SaveFile(path string, t *lattice.Tree, srcLang, tgtLang uint8) error { f, err := os.Create(path) if err != nil { return err } if err := Save(f, t, srcLang, tgtLang); err != nil { f.Close() return err } return f.Close() } // LoadFile reads a tree from a .mesh file. func LoadFile(path string) (*lattice.Tree, uint8, uint8, error) { f, err := os.Open(path) if err != nil { return nil, 0, 0, err } defer f.Close() return Load(f) }