File size: 9,730 Bytes
2cfa635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36690d3
2cfa635
 
 
36690d3
2cfa635
 
 
 
 
 
 
 
c0617a8
2cfa635
 
 
 
 
36690d3
2cfa635
 
 
36690d3
 
 
 
2cfa635
 
 
 
36690d3
 
 
 
 
 
 
 
 
 
2cfa635
36690d3
2cfa635
 
 
 
 
 
8899a5e
 
2cfa635
 
 
 
 
 
 
 
 
 
8899a5e
 
2cfa635
 
 
36690d3
2cfa635
 
36690d3
2cfa635
36690d3
 
 
2cfa635
 
 
124234c
 
 
 
 
2cfa635
 
 
8899a5e
36690d3
 
2cfa635
8899a5e
36690d3
 
2cfa635
 
 
 
 
 
 
 
 
36690d3
2cfa635
8899a5e
2cfa635
 
36690d3
 
2cfa635
36690d3
 
8899a5e
36690d3
 
 
 
 
 
 
 
8899a5e
36690d3
8899a5e
36690d3
 
8899a5e
2cfa635
c0617a8
 
2cfa635
 
36690d3
2cfa635
 
 
 
36690d3
2cfa635
 
 
36690d3
 
2cfa635
36690d3
2cfa635
 
 
 
36690d3
2cfa635
 
 
 
 
36690d3
2cfa635
 
 
c0617a8
 
2cfa635
 
 
 
 
8899a5e
36690d3
 
2cfa635
8899a5e
36690d3
 
2cfa635
 
 
 
 
 
 
 
 
36690d3
2cfa635
 
 
 
c0617a8
 
2cfa635
 
 
36690d3
 
2cfa635
 
 
 
8899a5e
36690d3
 
2cfa635
8899a5e
36690d3
 
7bb5463
2cfa635
 
 
 
 
 
 
 
36690d3
2cfa635
 
36690d3
2cfa635
36690d3
2cfa635
 
36690d3
 
 
2cfa635
 
 
 
 
 
 
 
36690d3
 
2cfa635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36690d3
2cfa635
 
36690d3
2cfa635
 
 
 
 
 
 
36690d3
 
2cfa635
 
 
 
36690d3
 
 
2cfa635
8899a5e
 
36690d3
2cfa635
8899a5e
2cfa635
 
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FastSeekWpf.Core;

[Serializable]
public class CachedEntry
{
    public ulong FileRef { get; set; }
    public ulong ParentRef { get; set; }
    public string Name { get; set; } = string.Empty;
    public FileKind Kind { get; set; }
}

[Serializable]
public class CacheData
{
    public List<CachedEntry> Entries { get; set; } = new();
    public string DriveRoot { get; set; } = string.Empty;
    public List<JournalCheckpoint> Checkpoints { get; set; } = new();
}

// Compact in-memory entry β€” matches Rust IndexEntry exactly
public struct IndexEntry
{
    public ulong FileRef;
    public ulong ParentRef;
    public uint NameOff;
    public uint NameLowerOff;
    public ushort NameLen;
    public ushort NameLowerLen;
    public byte Flags; // bit 0 = is_dir

    public readonly bool IsDir => (Flags & 1) != 0;
    public readonly FileKind Kind => IsDir ? FileKind.Directory : FileKind.File;
}

// Main index store β€” matches Rust IndexStore exactly (single drive_root)
public class IndexStore
{
    public List<IndexEntry> Entries = new();
    public List<byte> NameArena = new();        // UTF-8 name bytes
    public List<byte> NameLowerArena = new();   // UTF-8 lowercase name bytes
    public List<(ulong fileRef, int idx)> RefLookup = new(); // sorted by file_ref
    public string DriveRoot = string.Empty;
    public List<JournalCheckpoint> Checkpoints = new();

    public int Count => Entries.Count;

    // Arena accessors β€” matches Rust name() and name_lower()
    public string Name(IndexEntry e)
    {
        return Encoding.UTF8.GetString(NameArena.ToArray(), (int)e.NameOff, e.NameLen);
    }

    public string NameLower(IndexEntry e)
    {
        return Encoding.UTF8.GetString(NameLowerArena.ToArray(), (int)e.NameLowerOff, e.NameLowerLen);
    }

    // Ref lookup (binary search) β€” matches Rust lookup_idx()
    public uint? LookupIdx(ulong fileRef)
    {
        int lo = 0, hi = RefLookup.Count - 1;
        while (lo <= hi)
        {
            int mid = (lo + hi) >>> 1;
            var r = RefLookup[mid].fileRef;
            if (r == fileRef) return (uint)RefLookup[mid].idx;
            if (r < fileRef) lo = mid + 1;
            else hi = mid - 1;
        }
        return null;
    }

    private void RebuildRefLookup()
    {
        RefLookup.Clear();
        RefLookup.Capacity = Entries.Count;
        for (int i = 0; i < Entries.Count; i++)
            RefLookup.Add((Entries[i].FileRef, i));
        RefLookup.Sort((a, b) => a.fileRef.CompareTo(b.fileRef));
    }

    // Populate from MFT scan β€” matches Rust populate_from_scan()
    public void PopulateFromScan(ScanResult scan, string driveRoot)
    {
        this.DriveRoot = driveRoot;
        int count = scan.Records.Count;
        Entries.Capacity = count;
        NameArena.Capacity = count * 30;
        NameLowerArena.Capacity = count * 30;

        foreach (var r in scan.Records)
        {
            int start = (int)r.NameOff;
            int len = r.NameLen;
            var nameChars = new char[len];
            for (int i = 0; i < len; i++)
                nameChars[i] = scan.NameData[start + i];
            string name = new string(nameChars);
            string nameLower = name.ToLowerInvariant();

            uint nOff = (uint)NameArena.Count;
            ushort nLen = (ushort)name.Length;
            NameArena.AddRange(Encoding.UTF8.GetBytes(name));

            uint nlOff = (uint)NameLowerArena.Count;
            ushort nlLen = (ushort)nameLower.Length;
            NameLowerArena.AddRange(Encoding.UTF8.GetBytes(nameLower));

            Entries.Add(new IndexEntry
            {
                FileRef = r.FileRef,
                ParentRef = r.ParentRef,
                NameOff = nOff,
                NameLowerOff = nlOff,
                NameLen = nLen,
                NameLowerLen = nlLen,
                Flags = r.IsDir ? (byte)1 : (byte)0
            });
        }
    }

    // Sort entries by lowercase name and rebuild lookup β€” matches Rust finalize()
    public void Finalize()
    {
        // Rust uses sort_unstable_by with store_ptr for name_lower comparison.
        // We use a stable sort with proper key extraction.
        var indices = Enumerable.Range(0, Entries.Count).ToArray();
        Array.Sort(indices, (a, b) =>
        {
            var ea = Entries[a];
            var eb = Entries[b];
            return string.CompareOrdinal(
                Encoding.UTF8.GetString(NameLowerArena.ToArray(), (int)ea.NameLowerOff, ea.NameLowerLen),
                Encoding.UTF8.GetString(NameLowerArena.ToArray(), (int)eb.NameLowerOff, eb.NameLowerLen));
        });

        var sorted = new List<IndexEntry>(Entries.Count);
        foreach (var i in indices)
            sorted.Add(Entries[i]);
        Entries = sorted;

        RebuildRefLookup();
        NameArena.TrimExcess();
        NameLowerArena.TrimExcess();
    }

    // Cache serialization β€” matches Rust to_cache()
    public CacheData ToCache()
    {
        return new CacheData
        {
            Entries = Entries.Select(e => new CachedEntry
            {
                FileRef = e.FileRef,
                ParentRef = e.ParentRef,
                Name = Name(e),
                Kind = e.Kind
            }).ToList(),
            DriveRoot = DriveRoot,
            Checkpoints = new List<JournalCheckpoint>(Checkpoints)
        };
    }

    // Cache deserialization β€” matches Rust from_cache()
    public static IndexStore FromCache(CacheData cache)
    {
        int count = cache.Entries.Count;
        var store = new IndexStore
        {
            DriveRoot = cache.DriveRoot,
            Checkpoints = new List<JournalCheckpoint>(cache.Checkpoints)
        };
        store.Entries.Capacity = count;
        store.NameArena.Capacity = count * 30;
        store.NameLowerArena.Capacity = count * 30;

        foreach (var c in cache.Entries)
        {
            string nameLower = c.Name.ToLowerInvariant();

            uint nOff = (uint)store.NameArena.Count;
            ushort nLen = (ushort)c.Name.Length;
            store.NameArena.AddRange(Encoding.UTF8.GetBytes(c.Name));

            uint nlOff = (uint)store.NameLowerArena.Count;
            ushort nlLen = (ushort)nameLower.Length;
            store.NameLowerArena.AddRange(Encoding.UTF8.GetBytes(nameLower));

            store.Entries.Add(new IndexEntry
            {
                FileRef = c.FileRef,
                ParentRef = c.ParentRef,
                NameOff = nOff,
                NameLowerOff = nlOff,
                NameLen = nLen,
                NameLowerLen = nlLen,
                Flags = c.Kind == FileKind.Directory ? (byte)1 : (byte)0
            });
        }

        store.RebuildRefLookup();
        store.NameArena.TrimExcess();
        store.NameLowerArena.TrimExcess();
        return store;
    }

    // Live mutations β€” match Rust insert(), remove(), rename(), apply_move()

    public void Insert(FileRecord record)
    {
        string nameLower = record.Name.ToLowerInvariant();

        uint nOff = (uint)NameArena.Count;
        ushort nLen = (ushort)record.Name.Length;
        NameArena.AddRange(Encoding.UTF8.GetBytes(record.Name));

        uint nlOff = (uint)NameLowerArena.Count;
        ushort nlLen = (ushort)nameLower.Length;
        NameLowerArena.AddRange(Encoding.UTF8.GetBytes(nameLower));

        var entry = new IndexEntry
        {
            FileRef = record.FileRef,
            ParentRef = record.ParentRef,
            NameOff = nOff,
            NameLowerOff = nlOff,
            NameLen = nLen,
            NameLowerLen = nlLen,
            Flags = record.Kind == FileKind.Directory ? (byte)1 : (byte)0
        };

        // Rust: partition_point by name_lower comparison
        int pos = 0;
        string key = nameLower;
        for (; pos < Entries.Count; pos++)
        {
            var e = Entries[pos];
            string cmp = Encoding.UTF8.GetString(NameLowerArena.ToArray(), (int)e.NameLowerOff, e.NameLowerLen);
            if (string.CompareOrdinal(key, cmp) < 0)
                break;
        }
        Entries.Insert(pos, entry);
        RebuildRefLookup();
    }

    public void Remove(ulong fileRef)
    {
        // Name bytes left as dead space in arena (negligible for rare deletes)
        Entries.RemoveAll(e => e.FileRef == fileRef);
        RebuildRefLookup();
    }

    public void Rename(ulong oldRef, FileRecord newRecord)
    {
        Remove(oldRef);
        Insert(newRecord);
    }

    public void ApplyMove(ulong fileRef, ulong newParentRef, string name, FileKind kind)
    {
        Remove(fileRef);
        Insert(new FileRecord
        {
            FileRef = fileRef,
            ParentRef = newParentRef,
            Name = name,
            Kind = kind
        });
    }

    // Build path by walking parent chain β€” matches Rust build_path()
    public string BuildPath(ulong fileRef)
    {
        var components = new List<string>(16);
        ulong current = fileRef;

        for (int i = 0; i < 64; i++)
        {
            var idx = LookupIdx(current);
            if (idx == null) break;

            var entry = Entries[(int)idx];
            components.Add(Name(entry));
            if (entry.ParentRef == current) break;
            current = entry.ParentRef;
        }

        components.Reverse();
        var sb = new StringBuilder(DriveRoot);
        foreach (var comp in components)
        {
            if (sb.Length > 0 && sb[sb.Length - 1] != '\\' && sb[sb.Length - 1] != '/')
                sb.Append('\\');
            sb.Append(comp);
        }
        return sb.ToString();
    }
}