Debian Codegraph @

rust/hg-core/src/file_index/on_disk.rs

raw
1 //! This module presents a read-only view of the file index from its on-disk
2 //! representation, which consists of four files:
3 //!
4 //! * `.hg/store/fileindex`: the docket file
5 //! * `.hg/store/fileindex-list.{ID1}`: the list file
6 //! * `.hg/store/fileindex-meta.{ID2}`: the meta file
7 //! * `.hg/store/fileindex-tree.{ID3}`: the tree file
8 //!
9 //! See `mercurial/helptext/internals/file-index.txt` for more details.
10
11 use std::ops::Deref;
12 use std::path::Path;
13 use std::path::PathBuf;
14
15 use bytes_cast::unaligned::U16Be;
16 use bytes_cast::unaligned::U32Be;
17 use bytes_cast::BytesCast;
18 use self_cell::self_cell;
19
20 use super::FileToken;
21 use crate::utils::docket::FileUid;
22 use crate::utils::hg_path::HgPath;
23 use crate::utils::u16_u;
24 use crate::utils::u32_u;
25 use crate::utils::u_u16;
26 use crate::utils::u_u32;
27
28 /// Error type for file index corruption.
29 #[derive(Debug, PartialEq)]
30 pub enum Error {
31 BadFormatMarker,
32 DocketFileEof,
33 DataFileTooSmall,
34 BadMetaFilesize,
35 ListFileOutOfBounds,
36 MetaFileOutOfBounds,
37 TreeFileOutOfBounds,
38 TreeFileEof,
39 BadRootNode,
40 BadSingletonTree,
41 BadLeafLabel,
42 }
43
44 impl std::fmt::Display for Error {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 match self {
47 Error::BadFormatMarker => {
48 write!(f, "unrecognized format marker in docket")
49 }
50 Error::DocketFileEof => {
51 write!(f, "unexpected EOF while reading docket file")
52 }
53 Error::DataFileTooSmall => {
54 write!(f, "file is smaller than its 'used size' docket field")
55 }
56 Error::BadMetaFilesize => {
57 write!(f, "meta file 'used size' is not a multiple of the record size")
58 }
59 Error::ListFileOutOfBounds => {
60 write!(f, "list file access out of bounds")
61 }
62 Error::MetaFileOutOfBounds => {
63 write!(f, "meta file access out of bounds")
64 }
65 Error::TreeFileOutOfBounds => {
66 write!(f, "tree file access out of bounds")
67 }
68 Error::TreeFileEof => {
69 write!(f, "unexpected EOF while parsing tree file")
70 }
71 Error::BadRootNode => {
72 write!(f, "invalid root node in tree")
73 }
74 Error::BadSingletonTree => {
75 write!(f, "invalid singleton tree")
76 }
77 Error::BadLeafLabel => {
78 write!(f, "invalid label for leaf node")
79 }
80 }
81 }
82 }
83
84 impl From<Error> for crate::errors::HgError {
85 fn from(err: Error) -> Self {
86 Self::corrupted(format!("corrupted fileindex: {err}"))
87 }
88 }
89
90 /// The contents of the docket file.
91 pub struct Docket {
92 pub header: DocketHeader,
93 pub garbage_entries: Vec<GarbageEntry>,
94 }
95
96 impl Docket {
97 /// Reads a [`Docket`] from bytes.
98 pub fn read(on_disk: &[u8]) -> Result<Self, Error> {
99 let (header, rest) =
100 DocketHeader::from_bytes(on_disk).or(Err(Error::DocketFileEof))?;
101 if header.marker != *FORMAT_MARKER {
102 return Err(Error::BadFormatMarker);
103 }
104 let (garbage_entries, _rest) = parse_garbage_list(rest)?;
105 Ok(Docket { header: header.clone(), garbage_entries })
106 }
107
108 /// Serializes the docket to bytes.
109 pub fn serialize(&self) -> Vec<u8> {
110 let mut bytes = Vec::new();
111 bytes.extend_from_slice(self.header.as_bytes());
112 serialize_garbage_list(&self.garbage_entries, &mut bytes);
113 bytes
114 }
115
116 /// Returns the path to the docket, relative to the store.
117 pub fn path() -> &'static Path {
118 Path::new("fileindex")
119 }
120
121 /// Returns the path to the pending docket, relative to the store.
122 pub fn pending_path() -> &'static Path {
123 Path::new("fileindex.pending")
124 }
125
126 /// Returns the path to the list file, if there is one.
127 pub fn list_file_path(&self) -> Option<PathBuf> {
128 Self::data_file_path("fileindex-list", self.header.list_file_id)
129 }
130
131 /// Returns the path to the meta file, if there is one.
132 pub fn meta_file_path(&self) -> Option<PathBuf> {
133 Self::data_file_path("fileindex-meta", self.header.meta_file_id)
134 }
135
136 /// Returns the path to the tree file, if there is one.
137 pub fn tree_file_path(&self) -> Option<PathBuf> {
138 Self::data_file_path("fileindex-tree", self.header.tree_file_id)
139 }
140
141 fn data_file_path(name: &str, id: FileUid) -> Option<PathBuf> {
142 id.none_if_unset().map(|id| format!("{}.{}", name, id.as_str()).into())
143 }
144 }
145
146 /// Added at the start of the docket file. This a redundant sanity check more
147 /// than an actual "magic number" since `.hg/store/requires` already governs
148 /// which format should be used.
149 pub const FORMAT_MARKER: &[u8; 12] = b"fileindex-v1";
150
151 /// The contents of the docket file.
152 #[derive(BytesCast, Clone)]
153 #[repr(C)]
154 pub struct DocketHeader {
155 /// Should contain [`FORMAT_MARKER`].
156 pub marker: [u8; FORMAT_MARKER.len()],
157 /// Used size of the list file in bytes.
158 pub list_file_size: U32Be,
159 /// Used size of the meta file in bytes.
160 pub meta_file_size: U32Be,
161 /// Used size of tree file in bytes.
162 pub tree_file_size: U32Be,
163 /// List file path ID.
164 pub list_file_id: FileUid,
165 /// Meta file path ID.
166 pub meta_file_id: FileUid,
167 /// Tree file path ID.
168 pub tree_file_id: FileUid,
169 /// Pseudo-pointer to the root node in the tree file.
170 pub tree_root_pointer: U32Be,
171 /// Number of unused bytes within [`Self::tree_file_size`].
172 pub tree_unused_bytes: U32Be,
173 /// Currently unused. Reset to zero when writing the docket.
174 pub reserved_flags: [u8; 4],
175 }
176
177 impl Default for Docket {
178 fn default() -> Self {
179 Self {
180 header: DocketHeader {
181 marker: *FORMAT_MARKER,
182 list_file_size: 0.into(),
183 meta_file_size: 0.into(),
184 tree_file_size: 0.into(),
185 list_file_id: FileUid::unset(),
186 meta_file_id: FileUid::unset(),
187 tree_file_id: FileUid::unset(),
188 tree_root_pointer: 0.into(),
189 tree_unused_bytes: 0.into(),
190 reserved_flags: [0; 4],
191 },
192 garbage_entries: Vec::new(),
193 }
194 }
195 }
196
197 /// The garbage list parsed from the [`Docket`]. It consists of a
198 /// [`GarbageListHeader`], an array of [`GarbageIndexEntry`], and a buffer of
199 /// paths that the index entries point into.
200 fn parse_garbage_list(
201 bytes: &[u8],
202 ) -> Result<(Vec<GarbageEntry>, &[u8]), Error> {
203 let (header, rest) =
204 GarbageListHeader::from_bytes(bytes).or(Err(Error::DocketFileEof))?;
205 let num_entries = u32_u(header.num_entries.get());
206 let (index_entries, rest) =
207 GarbageIndexEntry::slice_from_bytes(rest, num_entries)
208 .or(Err(Error::DocketFileEof))?;
209 let (path_buf, rest) = rest
210 .split_at_checked(u32_u(header.path_buf_size.get()))
211 .ok_or(Error::DocketFileEof)?;
212 let entries = index_entries
213 .iter()
214 .map(|entry| GarbageEntry::from_index(entry, path_buf))
215 .collect();
216 Ok((entries, rest))
217 }
218
219 /// Serializes garbage entries. Inverse of [`parse_garbage_list`].
220 fn serialize_garbage_list(entries: &[GarbageEntry], out: &mut Vec<u8>) {
221 let mut path_buf = Vec::new();
222 for entry in entries {
223 let path = entry.path.as_os_str().as_encoded_bytes();
224 path_buf.extend_from_slice(path);
225 path_buf.push(b'\x00');
226 }
227 let header = GarbageListHeader {
228 num_entries: u_u32(entries.len()).into(),
229 path_buf_size: u_u32(path_buf.len()).into(),
230 };
231 out.extend_from_slice(header.as_bytes());
232 let mut offset = 0;
233 for entry in entries {
234 out.extend_from_slice(entry.to_index(offset).as_bytes());
235 offset += u_u32(entry.path.as_os_str().len()) + 1;
236 }
237 out.extend_from_slice(&path_buf);
238 }
239
240 /// Header of the garbage list in the [`Docket`].
241 #[derive(BytesCast)]
242 #[repr(C)]
243 struct GarbageListHeader {
244 /// Number of entries in the list.
245 num_entries: U32Be,
246 /// Size of the path buffer that the entries point into.
247 path_buf_size: U32Be,
248 }
249
250 /// An entry in the garbage list index in the [`Docket`].
251 #[derive(BytesCast)]
252 #[repr(C)]
253 struct GarbageIndexEntry {
254 ttl: U16Be,
255 timestamp: U32Be,
256 path_offset: U32Be,
257 path_length: U16Be,
258 }
259
260 /// An entry parsed from the garbage list in the [`Docket`].
261 pub struct GarbageEntry {
262 /// Time-to-live (TTL), decremented by each transaction.
263 /// The file will not be deleted until it reaches zero.
264 pub ttl: u16,
265 /// Time when this entry was added.
266 pub timestamp: u32,
267 /// Path to the file to be deleted.
268 pub path: PathBuf,
269 }
270
271 impl GarbageEntry {
272 /// Creates a [`GarbageEntry`] given its index entry and the path buffer.
273 fn from_index(entry: &GarbageIndexEntry, path_buf: &[u8]) -> Self {
274 let offset = u32_u(entry.path_offset.get());
275 let length = u16_u(entry.path_length.get());
276 Self {
277 ttl: entry.ttl.get(),
278 timestamp: entry.timestamp.get(),
279 path: std::str::from_utf8(&path_buf[offset..offset + length])
280 .expect("garbage entry path should be valid UTF-8")
281 .into(),
282 }
283 }
284
285 /// Converts this [`GarbageEntry`] back to a [`GarbageIndexEntry`].
286 fn to_index(&self, path_offset: u32) -> GarbageIndexEntry {
287 GarbageIndexEntry {
288 ttl: self.ttl.into(),
289 timestamp: self.timestamp.into(),
290 path_offset: path_offset.into(),
291 path_length: u_u16(self.path.as_os_str().len()).into(),
292 }
293 }
294 }
295
296 /// Metadata for a token in the meta file.
297 #[derive(Copy, Clone, BytesCast)]
298 #[repr(C)]
299 pub struct Metadata {
300 /// Pseudo-pointer to the start of the path in the list file.
301 pub offset: U32Be,
302 /// Length of the path.
303 pub length: U16Be,
304 /// Length of the path's dirname prefix, or 0 if there is no slash.
305 pub dirname_length: U16Be,
306 }
307
308 impl Metadata {
309 /// Creates metadata for `path` stored at `offset` in the list file.
310 pub fn new(path: &HgPath, offset: u32) -> Self {
311 let path_len: u16 =
312 path.len().try_into().expect("path len should fit in u16");
313 let dirname_len = path.bytes().rposition(|c| *c == b'/').unwrap_or(0);
314 let dirname_len: u16 =
315 dirname_len.try_into().expect("dirname len should fit in u16");
316 Self {
317 offset: offset.into(),
318 length: path_len.into(),
319 dirname_length: dirname_len.into(),
320 }
321 }
322
323 /// Returns the token's path as a [`Span`].
324 pub fn path(&self) -> Span {
325 Span { offset: self.offset.get(), length: self.length.get() }
326 }
327 }
328
329 /// A serialized empty file index meta file, containing a single entry.
330 // TODO: Construct directly and serialize once bytes_cast provides const fns:
331 // https://foss.heptapod.net/octobus/rust/bytes-cast/-/merge_requests/2
332 pub const EMPTY_META_BYTES: [u8; std::mem::size_of::<Metadata>()] = [0x00; 8];
333
334 /// Information about a token's path.
335 /// Parsed from [`Metadata`] and resolved to a pointer into the list file.
336 pub struct PathInfo<'on_disk> {
337 path: &'on_disk [u8],
338 dirname_length: usize,
339 }
340
341 impl<'a> PathInfo<'a> {
342 /// Returns this token's path.
343 pub fn path(&self) -> &'a HgPath {
344 HgPath::new(self.path)
345 }
346
347 /// Returns the dirname for this token (the prefix up to but not including
348 /// the final slash), or None if there is no slash.
349 pub fn dirname(&self) -> Option<&'a [u8]> {
350 match self.dirname_length {
351 0 => None,
352 _ => Some(&self.path[..self.dirname_length]),
353 }
354 }
355
356 /// Returns the basename for this token (the suffix after the final slash,
357 /// or the whole path is there is no slash).
358 pub fn basename(&self) -> &'a [u8] {
359 match self.dirname_length {
360 0 => self.path,
361 _ => &self.path[self.dirname_length + 1..],
362 }
363 }
364 }
365
366 /// A reference to a string in the list file.
367 pub struct Span {
368 offset: u32,
369 length: u16,
370 }
371
372 /// A node parsed from the tree file.
373 /// It stores a token and, indirectly, a label.
374 /// The label is a substring of the file path corresponding to the token.
375 /// The substring start position is implicit by summing parent label lengths.
376 /// The node also stores the first characters of child labels, for performance.
377 #[derive(Debug, Copy, Clone)]
378 pub struct TreeNode<'on_disk> {
379 /// A token that contains this node's label.
380 pub token: FileToken,
381 /// The length of this node's label.
382 pub label_length: u8,
383 /// First character of each child label. These are all distinct.
384 pub child_chars: &'on_disk [u8],
385 /// Pointers to this node's children.
386 pub child_ptrs: &'on_disk [TaggedNodePointer],
387 }
388
389 impl TreeNode<'_> {
390 /// Returns the index of the child whose label starts with `char`,
391 /// or `None` is there is no such child.
392 fn find_child(&self, char: u8) -> Option<usize> {
393 // Not using memchr because `child_chars` is usually very short, and
394 // memchr is slightly slower in that case (I measured ~10% slower).
395 self.child_chars.iter().position(|&c| c == char)
396 }
397 }
398
399 /// A node header in the tree file.
400 #[derive(Debug, BytesCast, Copy, Clone)]
401 #[repr(C)]
402 pub struct TreeNodeHeader {
403 /// A token that contains this node's label.
404 token: U32Be,
405 /// The length of this node's label.
406 label_length: u8,
407 /// Number of children.
408 pub num_children: u8,
409 }
410
411 /// A serialized empty file index tree file, containing a single root node.
412 // TODO: Construct directly and serialize once bytes_cast provides const fns:
413 // https://foss.heptapod.net/octobus/rust/bytes-cast/-/merge_requests/2
414 pub const EMPTY_TREE_BYTES: [u8; std::mem::size_of::<TreeNodeHeader>()] =
415 [0x00; 6];
416
417 impl TreeNodeHeader {
418 pub fn new(token: FileToken, label_length: u8, num_children: u8) -> Self {
419 Self { token: token.0.into(), label_length, num_children }
420 }
421 }
422
423 /// Pseudo-pointer to a node in the tree file.
424 pub type NodePointer = u32;
425
426 /// A node pointer where the high bit acts as a tag.
427 /// When the bit is 0, it is just a pointer.
428 /// When the bit is 1, it directly stores a [`FileToken`] instead.
429 #[derive(Debug, BytesCast, Copy, Clone)]
430 #[repr(transparent)]
431 pub struct TaggedNodePointer(U32Be);
432
433 /// Expanded version of [`TaggedNodePointer`].
434 #[derive(Debug, Copy, Clone)]
435 pub enum PointerOrToken {
436 Pointer(NodePointer),
437 Token(FileToken),
438 }
439
440 impl TaggedNodePointer {
441 pub fn unpack(self) -> PointerOrToken {
442 let value = self.0.get();
443 let mask = 1 << 31;
444 if value & mask == 0 {
445 PointerOrToken::Pointer(value)
446 } else {
447 PointerOrToken::Token(FileToken(value & !mask))
448 }
449 }
450 }
451
452 impl PointerOrToken {
453 pub fn pack(self) -> TaggedNodePointer {
454 let mask = 1 << 31;
455 let value = match self {
456 PointerOrToken::Pointer(ptr) => ptr,
457 PointerOrToken::Token(token) => mask | token.0,
458 };
459 TaggedNodePointer(value.into())
460 }
461 }
462
463 /// The position of a node's label within the file path. This is never stored
464 /// explicitly, but calculated by adding up the [`TreeNode::label_length`]
465 /// values while descending the tree.
466 pub type LabelPosition = usize;
467
468 /// Data files for creating a [`FileIndexView`].
469 #[derive(Default)]
470 struct DataFiles<'on_disk> {
471 list_file: &'on_disk [u8],
472 meta_file: &'on_disk [u8],
473 tree_file: &'on_disk [u8],
474 }
475
476 /// Owned version of [`DataFiles`].
477 pub struct OwnedDataFiles {
478 pub list_file: Box<dyn Deref<Target = [u8]> + Send + Sync>,
479 pub meta_file: Box<dyn Deref<Target = [u8]> + Send + Sync>,
480 pub tree_file: Box<dyn Deref<Target = [u8]> + Send + Sync>,
481 }
482
483 /// Read-only view of the file index.
484 #[derive(Copy, Clone)]
485 pub struct FileIndexView<'on_disk> {
486 /// Contents of the list file.
487 pub list_file: &'on_disk [u8],
488 /// Contents of the meta file, cast to a slice of [`Metadata`].
489 pub meta_array: &'on_disk [Metadata],
490 /// Contents of the tree file.
491 pub tree_file: &'on_disk [u8],
492 /// Value of [`DocketHeader::tree_file_size`].
493 /// Usually the same as `self.tree_file.len()`, but for an empty file index
494 /// this will be 0 while `self.tree_file` will contain a default.
495 pub tree_file_size: u32,
496 /// Value of [`DocketHeader::tree_root_pointer`].
497 pub tree_root_pointer: NodePointer,
498 /// Value of [`DocketHeader::tree_unused_bytes`].
499 pub tree_unused_bytes: u32,
500 /// Root node of the prefix tree.
501 pub root: TreeNode<'on_disk>,
502 }
503
504 self_cell!(
505 /// A wrapper around [`FileIndexView`] that owns the data.
506 pub struct OwnedFileIndexView {
507 owner: OwnedDataFiles,
508 #[covariant]
509 dependent: FileIndexView,
510 }
511 );
512
513 impl OwnedFileIndexView {
514 pub fn open(docket: &Docket, files: OwnedDataFiles) -> Result<Self, Error> {
515 Self::try_new(files, |files| {
516 FileIndexView::open(
517 docket,
518 DataFiles {
519 list_file: &files.list_file,
520 meta_file: &files.meta_file,
521 tree_file: &files.tree_file,
522 },
523 )
524 })
525 }
526 }
527
528 impl<'on_disk> FileIndexView<'on_disk> {
529 /// Returns a view of an empty file index.
530 pub fn empty() -> Self {
531 Self::open(&Docket::default(), DataFiles::default())
532 .expect("empty file index should be valid")
533 }
534
535 /// Creates a file index given a docket and file contents. It will only
536 /// read file contents up to the "used sizes" stored in the docket.
537 fn open(
538 docket: &Docket,
539 files: DataFiles<'on_disk>,
540 ) -> Result<Self, Error> {
541 let limit = |bytes: &'on_disk [u8], size: U32Be| {
542 bytes.get(..u32_u(size.get())).ok_or(Error::DataFileTooSmall)
543 };
544 let list_file = limit(files.list_file, docket.header.list_file_size)?;
545 let meta_file = limit(files.meta_file, docket.header.meta_file_size)?;
546 let tree_file = limit(files.tree_file, docket.header.tree_file_size)?;
547 let meta_file = if meta_file.is_empty() {
548 &EMPTY_META_BYTES
549 } else {
550 meta_file
551 };
552 let tree_file = if tree_file.is_empty() {
553 &EMPTY_TREE_BYTES
554 } else {
555 tree_file
556 };
557 const META_SIZE: usize = std::mem::size_of::<Metadata>();
558 if meta_file.len() % META_SIZE != 0 {
559 return Err(Error::BadMetaFilesize);
560 }
561 let (meta_array, rest) =
562 Metadata::slice_from_bytes(meta_file, meta_file.len() / META_SIZE)
563 .expect("cannot fail since len comes from actual size");
564 // There cannot be extra bytes because we checked the remainder above.
565 assert!(rest.is_empty());
566 let tree_file_size = docket.header.tree_file_size.get();
567 let tree_root_pointer = docket.header.tree_root_pointer.get();
568 let tree_unused_bytes = docket.header.tree_unused_bytes.get();
569 let root = Self::read_node_from(tree_file, tree_root_pointer)?;
570 if root.token != FileToken::root() || root.label_length != 0 {
571 return Err(Error::BadRootNode);
572 }
573 if tree_file_size > 0 && root.child_ptrs.is_empty() {
574 return Err(Error::BadSingletonTree);
575 }
576 Ok(Self {
577 list_file,
578 meta_array,
579 tree_file,
580 tree_file_size,
581 tree_root_pointer,
582 tree_unused_bytes,
583 root,
584 })
585 }
586
587 /// Returns the number of tokens in the file index.
588 pub fn token_count(&self) -> usize {
589 self.meta_array.len()
590 }
591
592 /// Looks up [`PathInfo`] by token.
593 pub fn get_path_info(
594 &self,
595 token: FileToken,
596 ) -> Result<Option<PathInfo<'on_disk>>, Error> {
597 match self.meta_array.get(u32_u(token.0)) {
598 Some(metadata) => Ok(Some(PathInfo {
599 path: self.read_span(metadata.path())?,
600 dirname_length: u16_u(metadata.dirname_length.get()),
601 })),
602 None => Ok(None),
603 }
604 }
605
606 /// Looks up a path by token.
607 pub fn get_path(
608 &self,
609 token: FileToken,
610 ) -> Result<Option<&'on_disk HgPath>, Error> {
611 Ok(self.get_path_info(token)?.map(|info| info.path()))
612 }
613
614 /// Looks up a token by path.
615 /// Returns `None` if the path isn't in the file index.
616 pub fn get_token(&self, path: &HgPath) -> Result<Option<FileToken>, Error> {
617 if path.is_empty() {
618 return Ok(None);
619 }
620 let path = path.as_bytes();
621 let mut node = self.root;
622 let mut position: LabelPosition = 0;
623 while let Some(index) = node.find_child(path[position]) {
624 let ptr = node.child_ptrs.get(index).ok_or(Error::TreeFileEof)?;
625 let (child_node, metadata) =
626 self.read_node_metadata(*ptr, position)?;
627 let span = Self::label_span(child_node, metadata, position);
628 let label = self.read_span(span)?;
629 if !path[position..].starts_with(label) {
630 break;
631 }
632 position += label.len();
633 if position == path.len() {
634 if path.len() == u16_u(metadata.length.get()) {
635 return Ok(Some(child_node.token));
636 }
637 break;
638 }
639 node = child_node;
640 }
641 Ok(None)
642 }
643
644 /// Returns an iterator over `(path, token)` pairs in the file index.
645 /// Excludes the root token.
646 pub fn iter(
647 &self,
648 ) -> impl Iterator<Item = Result<(PathInfo<'on_disk>, FileToken), Error>>
649 {
650 self.meta_array.iter().enumerate().skip(1).map(|(i, metadata)| {
651 Ok((
652 PathInfo {
653 path: self.read_span(metadata.path())?,
654 dirname_length: u16_u(metadata.dirname_length.get()),
655 },
656 FileToken(u_u32(i)),
657 ))
658 })
659 }
660
661 /// Reads a [`Span`] from the list file.
662 pub fn read_span(&self, span: Span) -> Result<&'on_disk [u8], Error> {
663 let offset = u32_u(span.offset);
664 let length = u16_u(span.length);
665 self.list_file
666 .get(offset..offset + length)
667 .ok_or(Error::ListFileOutOfBounds)
668 }
669
670 /// Reads a [`Metadata`] entry from the meta file by token.
671 pub fn read_metadata(
672 &self,
673 token: FileToken,
674 ) -> Result<&'on_disk Metadata, Error> {
675 debug_assert!(token.is_valid());
676 self.meta_array.get(u32_u(token.0)).ok_or(Error::MetaFileOutOfBounds)
677 }
678
679 /// Constructs a label [`Span`] for a node given its metadata and position.
680 pub fn label_span(
681 node: TreeNode<'_>,
682 metadata: &Metadata,
683 position: LabelPosition,
684 ) -> Span {
685 Span {
686 offset: metadata.offset.get() + u_u32(position),
687 length: node.label_length as u16,
688 }
689 }
690
691 /// Reads a [`TreeNode`] from the tree file.
692 pub fn read_node(&self, ptr: u32) -> Result<TreeNode<'on_disk>, Error> {
693 Self::read_node_from(self.tree_file, ptr)
694 }
695
696 /// Reads [`TreeNode`] and [`Metadata`] for a tagged pointer.
697 fn read_node_metadata(
698 &self,
699 ptr: TaggedNodePointer,
700 position: LabelPosition,
701 ) -> Result<(TreeNode<'on_disk>, &'on_disk Metadata), Error> {
702 match ptr.unpack() {
703 PointerOrToken::Pointer(ptr) => {
704 let node = self.read_node(ptr)?;
705 let metadata = self.read_metadata(node.token)?;
706 Ok((node, metadata))
707 }
708 PointerOrToken::Token(token) => {
709 self.read_leaf_node(token, position)
710 }
711 }
712 }
713
714 /// Reads a leaf node by token.
715 pub fn read_leaf_node(
716 &self,
717 token: FileToken,
718 position: LabelPosition,
719 ) -> Result<(TreeNode<'on_disk>, &'on_disk Metadata), Error> {
720 let metadata = self.read_metadata(token)?;
721 let label_length = metadata.length.get() - u_u16(position);
722 let label_length: u8 =
723 label_length.try_into().or(Err(Error::BadLeafLabel))?;
724 let node =
725 TreeNode { token, label_length, child_chars: &[], child_ptrs: &[] };
726 Ok((node, metadata))
727 }
728
729 /// Helper for reading a [`TreeNode`] before constructing an instance.
730 fn read_node_from(
731 tree_file: &'on_disk [u8],
732 ptr: u32,
733 ) -> Result<TreeNode<'on_disk>, Error> {
734 let slice =
735 tree_file.get(u32_u(ptr)..).ok_or(Error::TreeFileOutOfBounds)?;
736 let (header, rest) =
737 TreeNodeHeader::from_bytes(slice).or(Err(Error::TreeFileEof))?;
738 let (child_chars, rest) = rest
739 .split_at_checked(header.num_children as usize)
740 .ok_or(Error::TreeFileEof)?;
741 let (child_ptrs, _rest) = TaggedNodePointer::slice_from_bytes(
742 rest,
743 header.num_children as usize,
744 )
745 .or(Err(Error::TreeFileEof))?;
746 Ok(TreeNode {
747 token: FileToken(header.token.get()),
748 label_length: header.label_length,
749 child_chars,
750 child_ptrs,
751 })
752 }
753
754 /// Iterates over tree nodes, for debug output.
755 pub fn debug_iter_tree_nodes(&self) -> DebugTreeNodeIter<'on_disk> {
756 let stack = vec![(self.tree_root_pointer, 0)];
757 DebugTreeNodeIter { inner: *self, stack }
758 }
759 }
760
761 /// An iterator over the nodes of a [`FileIndexView`].
762 pub struct DebugTreeNodeIter<'on_disk> {
763 inner: FileIndexView<'on_disk>,
764 stack: Vec<(NodePointer, LabelPosition)>,
765 }
766
767 /// A debug representation of a file index tree node.
768 pub struct DebugTreeNode<'on_disk> {
769 pub pointer: NodePointer,
770 pub token: FileToken,
771 pub label: &'on_disk [u8],
772 // Use `&[u8; 1]` instead of `u8` to simplify PyO3 conversion.
773 pub children: Vec<(&'on_disk [u8; 1], DebugTreeChild<'on_disk>)>,
774 }
775
776 /// A debug representation of a file index tree node child.
777 #[derive(Copy, Clone)]
778 pub enum DebugTreeChild<'on_disk> {
779 Pointer(NodePointer),
780 Leaf(&'on_disk [u8], FileToken),
781 }
782
783 impl<'on_disk> Iterator for DebugTreeNodeIter<'on_disk> {
784 type Item = Result<DebugTreeNode<'on_disk>, Error>;
785
786 fn next(&mut self) -> Option<Self::Item> {
787 let (pointer, position) = self.stack.pop()?;
788 Some(self.next_result(pointer, position))
789 }
790 }
791
792 impl<'on_disk> DebugTreeNodeIter<'on_disk> {
793 fn next_result(
794 &mut self,
795 pointer: NodePointer,
796 position: LabelPosition,
797 ) -> Result<DebugTreeNode<'on_disk>, Error> {
798 let node = self.inner.read_node(pointer)?;
799 let token = node.token;
800 let metadata = self.inner.read_metadata(token)?;
801 let span = FileIndexView::label_span(node, metadata, position);
802 let label = self.inner.read_span(span)?;
803 let position = position + node.label_length as usize;
804 let mut children = Vec::with_capacity(node.child_chars.len());
805 for (char, &ptr) in node.child_chars.iter().zip(node.child_ptrs) {
806 let child = match ptr.unpack() {
807 PointerOrToken::Pointer(ptr) => DebugTreeChild::Pointer(ptr),
808 PointerOrToken::Token(token) => {
809 let (node, metadata) =
810 self.inner.read_leaf_node(token, position)?;
811 let span =
812 FileIndexView::label_span(node, metadata, position);
813 let label = self.inner.read_span(span)?;
814 DebugTreeChild::Leaf(label, token)
815 }
816 };
817 children.push((std::array::from_ref(char), child));
818 }
819 // Push to stack in reverse order to match Python which uses recursion.
820 for &ptr in node.child_ptrs.iter().rev() {
821 match ptr.unpack() {
822 PointerOrToken::Pointer(ptr) => {
823 self.stack.push((ptr, position));
824 }
825 PointerOrToken::Token(_) => {}
826 }
827 }
828 Ok(DebugTreeNode { pointer, token, label, children })
829 }
830 }