File size: 9,316 Bytes
761f4fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#![allow(dead_code)]
use serde::{Serialize, Deserialize};
use crate::mft::types::{FileKind, FileRecord, JournalCheckpoint};
use crate::mft::reader::ScanResult;

// ── Cache format (disk) ──────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedEntry {
    pub file_ref: u64,
    pub parent_ref: u64,
    pub name: String,
    pub kind: FileKind,
}

#[derive(Serialize, Deserialize)]
pub struct CacheData {
    pub entries: Vec<CachedEntry>,
    pub drive_root: String,
    pub checkpoints: Vec<JournalCheckpoint>,
}

// ── Compact in-memory entry (32 bytes) ───────────────────────────────
#[derive(Clone)]
pub struct IndexEntry {
    pub file_ref: u64,
    pub parent_ref: u64,
    pub name_off: u32,
    pub name_lower_off: u32,
    pub name_len: u16,
    pub name_lower_len: u16,
    pub flags: u8, // bit 0 = is_dir
}

impl IndexEntry {
    #[inline]
    pub fn is_dir(&self) -> bool {
        self.flags & 1 != 0
    }

    #[inline]
    pub fn kind(&self) -> FileKind {
        if self.is_dir() { FileKind::Directory } else { FileKind::File }
    }
}

// ── Main index store ─────────────────────────────────────────────────
pub struct IndexStore {
    pub entries: Vec<IndexEntry>,
    pub name_arena: Vec<u8>,
    pub name_lower_arena: Vec<u8>,
    pub ref_lookup: Vec<(u64, u32)>, // sorted by file_ref for binary search
    pub drive_root: String,
    pub checkpoints: Vec<JournalCheckpoint>,
}

impl IndexStore {
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            name_arena: Vec::new(),
            name_lower_arena: Vec::new(),
            ref_lookup: Vec::new(),
            drive_root: String::new(),
            checkpoints: Vec::new(),
        }
    }

    // ── Arena accessors ──────────────────────────────────────────────

    #[inline]
    pub fn name(&self, e: &IndexEntry) -> &str {
        unsafe {
            std::str::from_utf8_unchecked(
                &self.name_arena[e.name_off as usize..(e.name_off as usize + e.name_len as usize)]
            )
        }
    }

    #[inline]
    pub fn name_lower(&self, e: &IndexEntry) -> &str {
        unsafe {
            std::str::from_utf8_unchecked(
                &self.name_lower_arena[e.name_lower_off as usize..(e.name_lower_off as usize + e.name_lower_len as usize)]
            )
        }
    }

    // ── Ref lookup (binary search) ───────────────────────────────────

    pub fn lookup_idx(&self, file_ref: u64) -> Option<u32> {
        self.ref_lookup
            .binary_search_by_key(&file_ref, |&(r, _)| r)
            .ok()
            .map(|pos| self.ref_lookup[pos].1)
    }

    fn rebuild_ref_lookup(&mut self) {
        self.ref_lookup.clear();
        self.ref_lookup.reserve(self.entries.len());
        for (i, e) in self.entries.iter().enumerate() {
            self.ref_lookup.push((e.file_ref, i as u32));
        }
        self.ref_lookup.sort_unstable_by_key(|&(r, _)| r);
    }

    // ── Populate from MFT scan ───────────────────────────────────────

    pub fn populate_from_scan(&mut self, scan: ScanResult, drive_root: &str) {
        self.drive_root = drive_root.to_string();
        let count = scan.records.len();
        self.entries.reserve(count);
        // Estimate ~30 bytes avg per name
        self.name_arena.reserve(count * 30);
        self.name_lower_arena.reserve(count * 30);

        for r in &scan.records {
            let name_slice = &scan.name_data[r.name_off as usize..(r.name_off as usize + r.name_len as usize)];
            let name = String::from_utf16_lossy(name_slice);
            let name_lower = name.to_lowercase();

            let n_off = self.name_arena.len() as u32;
            let n_len = name.len() as u16;
            self.name_arena.extend_from_slice(name.as_bytes());

            let nl_off = self.name_lower_arena.len() as u32;
            let nl_len = name_lower.len() as u16;
            self.name_lower_arena.extend_from_slice(name_lower.as_bytes());

            self.entries.push(IndexEntry {
                file_ref: r.file_ref,
                parent_ref: r.parent_ref,
                name_off: n_off,
                name_lower_off: nl_off,
                name_len: n_len,
                name_lower_len: nl_len,
                flags: if r.is_dir { 1 } else { 0 },
            });
        }
    }

    pub fn finalize(&mut self) {
        let store_ptr = self as *const IndexStore;
        self.entries.sort_unstable_by(|a, b| {
            let s = unsafe { &*store_ptr };
            s.name_lower(a).cmp(s.name_lower(b))
        });
        self.rebuild_ref_lookup();
        // Shrink arenas to fit
        self.name_arena.shrink_to_fit();
        self.name_lower_arena.shrink_to_fit();
    }

    // ── Cache serialization ──────────────────────────────────────────

    pub fn to_cache(&self) -> CacheData {
        CacheData {
            entries: self.entries.iter().map(|e| CachedEntry {
                file_ref: e.file_ref,
                parent_ref: e.parent_ref,
                name: self.name(e).to_string(),
                kind: e.kind(),
            }).collect(),
            drive_root: self.drive_root.clone(),
            checkpoints: self.checkpoints.clone(),
        }
    }

    pub fn from_cache(cache: CacheData) -> Self {
        let count = cache.entries.len();
        let mut store = Self {
            entries: Vec::with_capacity(count),
            name_arena: Vec::with_capacity(count * 30),
            name_lower_arena: Vec::with_capacity(count * 30),
            ref_lookup: Vec::with_capacity(count),
            drive_root: cache.drive_root,
            checkpoints: cache.checkpoints,
        };

        for c in cache.entries {
            let name_lower = c.name.to_lowercase();

            let n_off = store.name_arena.len() as u32;
            let n_len = c.name.len() as u16;
            store.name_arena.extend_from_slice(c.name.as_bytes());

            let nl_off = store.name_lower_arena.len() as u32;
            let nl_len = name_lower.len() as u16;
            store.name_lower_arena.extend_from_slice(name_lower.as_bytes());

            let flags = match c.kind {
                FileKind::Directory => 1u8,
                FileKind::File => 0u8,
            };

            store.entries.push(IndexEntry {
                file_ref: c.file_ref,
                parent_ref: c.parent_ref,
                name_off: n_off,
                name_lower_off: nl_off,
                name_len: n_len,
                name_lower_len: nl_len,
                flags,
            });
        }

        store.rebuild_ref_lookup();
        store.name_arena.shrink_to_fit();
        store.name_lower_arena.shrink_to_fit();
        store
    }

    // ── Live mutations ───────────────────────────────────────────────

    pub fn insert(&mut self, record: FileRecord) {
        let name_lower = record.name.to_lowercase();

        let n_off = self.name_arena.len() as u32;
        let n_len = record.name.len() as u16;
        self.name_arena.extend_from_slice(record.name.as_bytes());

        let nl_off = self.name_lower_arena.len() as u32;
        let nl_len = name_lower.len() as u16;
        self.name_lower_arena.extend_from_slice(name_lower.as_bytes());

        let flags = match record.kind {
            FileKind::Directory => 1u8,
            FileKind::File => 0u8,
        };

        let entry = IndexEntry {
            file_ref: record.file_ref,
            parent_ref: record.parent_ref,
            name_off: n_off,
            name_lower_off: nl_off,
            name_len: n_len,
            name_lower_len: nl_len,
            flags,
        };

        let store_ptr = self as *const IndexStore;
        let pos = self.entries.partition_point(|e| {
            let s = unsafe { &*store_ptr };
            s.name_lower(e) < name_lower.as_str()
        });
        self.entries.insert(pos, entry);
        self.rebuild_ref_lookup();
    }

    pub fn remove(&mut self, file_ref: u64) {
        // Name bytes left as dead space in arena (negligible for rare deletes)
        self.entries.retain(|e| e.file_ref != file_ref);
        self.rebuild_ref_lookup();
    }

    pub fn rename(&mut self, old_ref: u64, new_record: FileRecord) {
        self.remove(old_ref);
        self.insert(new_record);
    }

    pub fn apply_move(&mut self, file_ref: u64, new_parent_ref: u64, name: String, kind: FileKind) {
        self.remove(file_ref);
        self.insert(FileRecord { file_ref, parent_ref: new_parent_ref, name, kind });
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }
}