Debian Codegraph @

rust/hg-core/src/dirstate/dirstate_map.rs

raw
1 use std::borrow::Cow;
2 use std::fs::Metadata;
3 use std::os::unix::fs::MetadataExt;
4 use std::path::PathBuf;
5
6 use bytes_cast::BytesCast;
7
8 use super::on_disk;
9 use super::on_disk::DirstateV2ParseError;
10 use super::owning::OwningDirstateMap;
11 use super::path_with_basename::WithBasename;
12 use super::status::DirstateStatus;
13 use super::status::StatusError;
14 use super::status::StatusOptions;
15 use super::DirstateError;
16 use super::DirstateMapError;
17 use crate::dirstate::entry::DirstateEntry;
18 use crate::dirstate::entry::DirstateV2Data;
19 use crate::dirstate::entry::ParentFileData;
20 use crate::dirstate::entry::TruncatedTimestamp;
21 use crate::dirstate::parsers::pack_entry;
22 use crate::dirstate::parsers::packed_entry_size;
23 use crate::dirstate::parsers::parse_dirstate_entries;
24 use crate::dirstate::CopyMapIter;
25 use crate::dirstate::StateMapIter;
26 use crate::matchers::Matcher;
27 use crate::utils::filter_map_results;
28 use crate::utils::hg_path::HgPath;
29 use crate::utils::hg_path::HgPathBuf;
30 use crate::warnings::HgWarningContext;
31 use crate::DirstateParents;
32 use crate::FastHashbrownMap as FastHashMap;
33
34 /// Append to an existing data file if the amount of unreachable data (not used
35 /// anymore) is less than this fraction of the total amount of existing data.
36 const ACCEPTABLE_UNREACHABLE_BYTES_RATIO: f32 = 0.5;
37
38 #[derive(Debug, PartialEq, Eq)]
39 /// Version of the on-disk format
40 pub enum DirstateVersion {
41 V1,
42 V2,
43 }
44
45 #[derive(Debug, PartialEq, Eq)]
46 pub enum DirstateMapWriteMode {
47 Auto,
48 ForceNewDataFile,
49 ForceAppend,
50 }
51
52 /// Used to detect out-of-process changes in the dirstate
53 #[derive(Debug, Copy, Clone)]
54 pub struct DirstateIdentity {
55 pub mode: u32,
56 pub dev: u64,
57 pub ino: u64,
58 pub nlink: u64,
59 pub uid: u32,
60 pub gid: u32,
61 pub size: u64,
62 pub mtime: i64,
63 pub mtime_nsec: i64,
64 pub ctime: i64,
65 pub ctime_nsec: i64,
66 }
67
68 impl From<Metadata> for DirstateIdentity {
69 fn from(value: Metadata) -> Self {
70 Self {
71 mode: value.mode(),
72 dev: value.dev(),
73 ino: value.ino(),
74 nlink: value.nlink(),
75 uid: value.uid(),
76 gid: value.gid(),
77 size: value.size(),
78 mtime: value.mtime(),
79 mtime_nsec: value.mtime_nsec(),
80 ctime: value.ctime(),
81 ctime_nsec: value.ctime_nsec(),
82 }
83 }
84 }
85
86 impl PartialEq for DirstateIdentity {
87 fn eq(&self, other: &Self) -> bool {
88 // Some platforms return 0 when they have no support for nanos.
89 // This shouldn't be a problem in practice because of how highly
90 // unlikely it is that we actually get exactly 0 nanos, and worst
91 // case scenario, we don't write out the dirstate in a non-wlocked
92 // situation like status.
93 let mtime_nanos_equal = (self.mtime_nsec == 0 || other.mtime_nsec == 0)
94 || self.mtime_nsec == other.mtime_nsec;
95 let ctime_nanos_equal = (self.ctime_nsec == 0 || other.ctime_nsec == 0)
96 || self.ctime_nsec == other.ctime_nsec;
97
98 self.mode == other.mode
99 && self.dev == other.dev
100 && self.ino == other.ino
101 && self.nlink == other.nlink
102 && self.uid == other.uid
103 && self.gid == other.gid
104 && self.size == other.size
105 && self.mtime == other.mtime
106 && mtime_nanos_equal
107 && self.ctime == other.ctime
108 && ctime_nanos_equal
109 }
110 }
111
112 #[derive(Debug)]
113 pub struct DirstateMap<'on_disk> {
114 /// Contents of the `.hg/dirstate` file
115 pub(super) on_disk: &'on_disk [u8],
116
117 pub(super) root: ChildNodes<'on_disk>,
118
119 /// Number of nodes anywhere in the tree that have `.entry.is_some()`.
120 pub(super) nodes_with_entry_count: u32,
121
122 /// Number of nodes anywhere in the tree that have
123 /// `.copy_source.is_some()`.
124 pub(super) nodes_with_copy_source_count: u32,
125
126 /// See on_disk::Header
127 pub(super) ignore_patterns_hash: on_disk::IgnorePatternsHash,
128
129 /// How many bytes of `on_disk` are not used anymore
130 pub(super) unreachable_bytes: u32,
131
132 /// Size of the data used to first load this `DirstateMap`. Used in case
133 /// we need to write some new metadata, but no new data on disk,
134 /// as well as to detect writes that have happened in another process
135 /// since first read.
136 pub(super) old_data_size: usize,
137
138 /// UUID used when first loading this `DirstateMap`. Used to check if
139 /// the UUID has been changed by another process since first read.
140 /// Can be `None` if using dirstate v1 or if it's a brand new dirstate.
141 pub(super) old_uuid: Option<Vec<u8>>,
142
143 /// Identity of the dirstate file (for dirstate-v1) or the docket file
144 /// (v2). Used to detect if the file has changed from another process.
145 /// Since it's always written atomically, we can compare the inode to
146 /// check the file identity.
147 ///
148 /// TODO On non-Unix systems, something like hashing is a possibility?
149 pub(super) identity: Option<DirstateIdentity>,
150
151 pub(super) dirstate_version: DirstateVersion,
152
153 /// Controlled by config option `devel.dirstate.v2.data_update_mode`
154 pub(super) write_mode: DirstateMapWriteMode,
155
156 /// Controlled by config option `format.use-dirstate-tracked-hint`
157 pub(super) use_tracked_hint: bool,
158 }
159
160 /// Using a plain `HgPathBuf` of the full path from the repository root as a
161 /// map key would also work: all paths in a given map have the same parent
162 /// path, so comparing full paths gives the same result as comparing base
163 /// names. However `HashMap` would waste time always re-hashing the same
164 /// string prefix.
165 pub(super) type NodeKey<'on_disk> = WithBasename<Cow<'on_disk, HgPath>>;
166
167 /// Similar to `&'tree Cow<'on_disk, HgPath>`, but can also be returned
168 /// for on-disk nodes that don’t actually have a `Cow` to borrow.
169 #[derive(Debug)]
170 pub(super) enum BorrowedPath<'tree, 'on_disk> {
171 InMemory(&'tree HgPathBuf),
172 OnDisk(&'on_disk HgPath),
173 }
174
175 #[derive(Debug)]
176 pub(super) enum ChildNodes<'on_disk> {
177 InMemory(FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
178 OnDisk(&'on_disk [on_disk::Node]),
179 }
180
181 #[derive(Debug)]
182 pub(super) enum ChildNodesRef<'tree, 'on_disk> {
183 InMemory(&'tree FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
184 OnDisk(&'on_disk [on_disk::Node]),
185 }
186
187 #[derive(Debug)]
188 pub(super) enum NodeRef<'tree, 'on_disk> {
189 InMemory(&'tree NodeKey<'on_disk>, &'tree Node<'on_disk>),
190 OnDisk(&'on_disk on_disk::Node),
191 }
192
193 impl<'on_disk> BorrowedPath<'_, 'on_disk> {
194 pub fn detach_from_tree(&self) -> Cow<'on_disk, HgPath> {
195 match *self {
196 BorrowedPath::InMemory(in_memory) => Cow::Owned(in_memory.clone()),
197 BorrowedPath::OnDisk(on_disk) => Cow::Borrowed(on_disk),
198 }
199 }
200 }
201
202 impl std::ops::Deref for BorrowedPath<'_, '_> {
203 type Target = HgPath;
204
205 fn deref(&self) -> &HgPath {
206 match *self {
207 BorrowedPath::InMemory(in_memory) => in_memory,
208 BorrowedPath::OnDisk(on_disk) => on_disk,
209 }
210 }
211 }
212
213 impl Default for ChildNodes<'_> {
214 fn default() -> Self {
215 ChildNodes::InMemory(Default::default())
216 }
217 }
218
219 impl<'on_disk> ChildNodes<'on_disk> {
220 pub(super) fn as_ref<'tree>(&'tree self) -> ChildNodesRef<'tree, 'on_disk> {
221 match self {
222 ChildNodes::InMemory(nodes) => ChildNodesRef::InMemory(nodes),
223 ChildNodes::OnDisk(nodes) => ChildNodesRef::OnDisk(nodes),
224 }
225 }
226
227 pub(super) fn is_empty(&self) -> bool {
228 match self {
229 ChildNodes::InMemory(nodes) => nodes.is_empty(),
230 ChildNodes::OnDisk(nodes) => nodes.is_empty(),
231 }
232 }
233
234 fn make_mut(
235 &mut self,
236 on_disk: &'on_disk [u8],
237 unreachable_bytes: &mut u32,
238 ) -> Result<
239 &mut FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>,
240 DirstateV2ParseError,
241 > {
242 match self {
243 ChildNodes::InMemory(nodes) => Ok(nodes),
244 ChildNodes::OnDisk(nodes) => {
245 *unreachable_bytes +=
246 std::mem::size_of_val::<[on_disk::Node]>(*nodes) as u32;
247 let nodes = nodes
248 .iter()
249 .map(|node| {
250 Ok((
251 node.path(on_disk)?,
252 node.to_in_memory_node(on_disk)?,
253 ))
254 })
255 .collect::<Result<_, _>>()?;
256 *self = ChildNodes::InMemory(nodes);
257 match self {
258 ChildNodes::InMemory(nodes) => Ok(nodes),
259 ChildNodes::OnDisk(_) => unreachable!(),
260 }
261 }
262 }
263 }
264 }
265
266 impl<'tree, 'on_disk> ChildNodesRef<'tree, 'on_disk> {
267 pub(super) fn get(
268 &self,
269 base_name: &HgPath,
270 on_disk: &'on_disk [u8],
271 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
272 match self {
273 ChildNodesRef::InMemory(nodes) => Ok(nodes
274 .get_key_value(base_name)
275 .map(|(k, v)| NodeRef::InMemory(k, v))),
276 ChildNodesRef::OnDisk(nodes) => {
277 let mut parse_result = Ok(());
278 let search_result = nodes.binary_search_by(|node| {
279 match node.base_name(on_disk) {
280 Ok(node_base_name) => node_base_name.cmp(base_name),
281 Err(e) => {
282 parse_result = Err(e);
283 // Dummy comparison result, `search_result` won’t
284 // be used since `parse_result` is an error
285 std::cmp::Ordering::Equal
286 }
287 }
288 });
289 parse_result.map(|()| {
290 search_result.ok().map(|i| NodeRef::OnDisk(&nodes[i]))
291 })
292 }
293 }
294 }
295
296 /// Iterate in undefined order
297 pub(super) fn iter(
298 &self,
299 ) -> impl Iterator<Item = NodeRef<'tree, 'on_disk>> + use<'tree, 'on_disk>
300 {
301 match self {
302 ChildNodesRef::InMemory(nodes) => itertools::Either::Left(
303 nodes.iter().map(|(k, v)| NodeRef::InMemory(k, v)),
304 ),
305 ChildNodesRef::OnDisk(nodes) => {
306 itertools::Either::Right(nodes.iter().map(NodeRef::OnDisk))
307 }
308 }
309 }
310
311 /// Iterate in parallel in undefined order
312 pub(super) fn par_iter(
313 &self,
314 ) -> impl rayon::iter::ParallelIterator<Item = NodeRef<'tree, 'on_disk>>
315 + use<'tree, 'on_disk> {
316 use rayon::prelude::*;
317 match self {
318 ChildNodesRef::InMemory(nodes) => rayon::iter::Either::Left(
319 nodes.par_iter().map(|(k, v)| NodeRef::InMemory(k, v)),
320 ),
321 ChildNodesRef::OnDisk(nodes) => rayon::iter::Either::Right(
322 nodes.par_iter().map(NodeRef::OnDisk),
323 ),
324 }
325 }
326
327 pub(super) fn sorted(&self) -> Vec<NodeRef<'tree, 'on_disk>> {
328 match self {
329 ChildNodesRef::InMemory(nodes) => {
330 let mut vec: Vec<_> = nodes
331 .iter()
332 .map(|(k, v)| NodeRef::InMemory(k, v))
333 .collect();
334 fn sort_key<'a>(node: &'a NodeRef) -> &'a HgPath {
335 match node {
336 NodeRef::InMemory(path, _node) => path.base_name(),
337 NodeRef::OnDisk(_) => unreachable!(),
338 }
339 }
340 // `sort_unstable_by_key` doesn’t allow keys borrowing from the
341 // value: https://github.com/rust-lang/rust/issues/34162
342 vec.sort_unstable_by(|a, b| sort_key(a).cmp(sort_key(b)));
343 vec
344 }
345 ChildNodesRef::OnDisk(nodes) => {
346 // Nodes on disk are already sorted
347 nodes.iter().map(NodeRef::OnDisk).collect()
348 }
349 }
350 }
351 }
352
353 impl<'tree, 'on_disk> NodeRef<'tree, 'on_disk> {
354 pub(super) fn full_path(
355 &self,
356 on_disk: &'on_disk [u8],
357 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
358 match self {
359 NodeRef::InMemory(path, _node) => Ok(path.full_path()),
360 NodeRef::OnDisk(node) => node.full_path(on_disk),
361 }
362 }
363
364 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
365 /// HgPath>` detached from `'tree`
366 pub(super) fn full_path_borrowed(
367 &self,
368 on_disk: &'on_disk [u8],
369 ) -> Result<BorrowedPath<'tree, 'on_disk>, DirstateV2ParseError> {
370 match self {
371 NodeRef::InMemory(path, _node) => match path.full_path() {
372 Cow::Borrowed(on_disk) => Ok(BorrowedPath::OnDisk(on_disk)),
373 Cow::Owned(in_memory) => Ok(BorrowedPath::InMemory(in_memory)),
374 },
375 NodeRef::OnDisk(node) => {
376 Ok(BorrowedPath::OnDisk(node.full_path(on_disk)?))
377 }
378 }
379 }
380
381 pub(super) fn base_name(
382 &self,
383 on_disk: &'on_disk [u8],
384 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
385 match self {
386 NodeRef::InMemory(path, _node) => Ok(path.base_name()),
387 NodeRef::OnDisk(node) => node.base_name(on_disk),
388 }
389 }
390
391 pub(super) fn children(
392 &self,
393 on_disk: &'on_disk [u8],
394 ) -> Result<ChildNodesRef<'tree, 'on_disk>, DirstateV2ParseError> {
395 match self {
396 NodeRef::InMemory(_path, node) => Ok(node.children.as_ref()),
397 NodeRef::OnDisk(node) => {
398 Ok(ChildNodesRef::OnDisk(node.children(on_disk)?))
399 }
400 }
401 }
402
403 pub(super) fn has_copy_source(&self) -> bool {
404 match self {
405 NodeRef::InMemory(_path, node) => node.copy_source.is_some(),
406 NodeRef::OnDisk(node) => node.has_copy_source(),
407 }
408 }
409
410 pub(super) fn copy_source(
411 &self,
412 on_disk: &'on_disk [u8],
413 ) -> Result<Option<&'tree HgPath>, DirstateV2ParseError> {
414 match self {
415 NodeRef::InMemory(_path, node) => Ok(node.copy_source.as_deref()),
416 NodeRef::OnDisk(node) => node.copy_source(on_disk),
417 }
418 }
419 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
420 /// HgPath>` detached from `'tree`
421 pub(super) fn copy_source_borrowed(
422 &self,
423 on_disk: &'on_disk [u8],
424 ) -> Result<Option<BorrowedPath<'tree, 'on_disk>>, DirstateV2ParseError>
425 {
426 Ok(match self {
427 NodeRef::InMemory(_path, node) => {
428 node.copy_source.as_ref().map(|source| match source {
429 Cow::Borrowed(on_disk) => BorrowedPath::OnDisk(on_disk),
430 Cow::Owned(in_memory) => BorrowedPath::InMemory(in_memory),
431 })
432 }
433 NodeRef::OnDisk(node) => {
434 node.copy_source(on_disk)?.map(BorrowedPath::OnDisk)
435 }
436 })
437 }
438
439 pub(super) fn entry(
440 &self,
441 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
442 match self {
443 NodeRef::InMemory(_path, node) => Ok(node.data.as_entry().copied()),
444 NodeRef::OnDisk(node) => node.entry(),
445 }
446 }
447
448 pub(super) fn cached_directory_mtime(
449 &self,
450 ) -> Result<Option<TruncatedTimestamp>, DirstateV2ParseError> {
451 match self {
452 NodeRef::InMemory(_path, node) => Ok(match node.data {
453 NodeData::CachedDirectory { mtime } => Some(mtime),
454 _ => None,
455 }),
456 NodeRef::OnDisk(node) => node.cached_directory_mtime(),
457 }
458 }
459
460 pub(super) fn descendants_with_entry_count(&self) -> u32 {
461 match self {
462 NodeRef::InMemory(_path, node) => node.descendants_with_entry_count,
463 NodeRef::OnDisk(node) => node.descendants_with_entry_count.get(),
464 }
465 }
466
467 pub(super) fn tracked_descendants_count(&self) -> u32 {
468 match self {
469 NodeRef::InMemory(_path, node) => node.tracked_descendants_count,
470 NodeRef::OnDisk(node) => node.tracked_descendants_count.get(),
471 }
472 }
473 }
474
475 /// Represents a file or a directory
476 #[derive(Default, Debug)]
477 pub(super) struct Node<'on_disk> {
478 pub(super) data: NodeData,
479
480 pub(super) copy_source: Option<Cow<'on_disk, HgPath>>,
481
482 pub(super) children: ChildNodes<'on_disk>,
483
484 /// How many (non-inclusive) descendants of this node have an entry.
485 pub(super) descendants_with_entry_count: u32,
486
487 /// How many (non-inclusive) descendants of this node have an entry whose
488 /// state is "tracked".
489 pub(super) tracked_descendants_count: u32,
490 }
491
492 #[derive(Debug, Default)]
493 pub(super) enum NodeData {
494 Entry(DirstateEntry),
495 CachedDirectory {
496 mtime: TruncatedTimestamp,
497 },
498 #[default]
499 None,
500 }
501
502 impl NodeData {
503 fn has_entry(&self) -> bool {
504 matches!(self, NodeData::Entry(_))
505 }
506
507 fn as_entry(&self) -> Option<&DirstateEntry> {
508 match self {
509 NodeData::Entry(entry) => Some(entry),
510 _ => None,
511 }
512 }
513
514 fn as_entry_mut(&mut self) -> Option<&mut DirstateEntry> {
515 match self {
516 NodeData::Entry(entry) => Some(entry),
517 _ => None,
518 }
519 }
520 }
521
522 impl<'on_disk> DirstateMap<'on_disk> {
523 pub(super) fn empty(on_disk: &'on_disk [u8]) -> Self {
524 Self {
525 on_disk,
526 root: ChildNodes::default(),
527 nodes_with_entry_count: 0,
528 nodes_with_copy_source_count: 0,
529 ignore_patterns_hash: [0; on_disk::IGNORE_PATTERNS_HASH_LEN],
530 unreachable_bytes: 0,
531 old_data_size: 0,
532 old_uuid: None,
533 identity: None,
534 dirstate_version: DirstateVersion::V1,
535 write_mode: DirstateMapWriteMode::Auto,
536 use_tracked_hint: false,
537 }
538 }
539
540 #[tracing::instrument(level = "debug", skip_all)]
541 pub fn new_v2(
542 on_disk: &'on_disk [u8],
543 data_size: usize,
544 metadata: &[u8],
545 uuid: Vec<u8>,
546 identity: Option<DirstateIdentity>,
547 ) -> Result<Self, DirstateError> {
548 if let Some(data) = on_disk.get(..data_size) {
549 Ok(on_disk::read(data, metadata, uuid, identity)?)
550 } else {
551 Err(DirstateV2ParseError::new("not enough bytes on disk").into())
552 }
553 }
554
555 #[tracing::instrument(level = "debug", skip_all)]
556 pub fn new_v1(
557 on_disk: &'on_disk [u8],
558 identity: Option<DirstateIdentity>,
559 ) -> Result<(Self, Option<DirstateParents>), DirstateError> {
560 let mut map = Self::empty(on_disk);
561 map.identity = identity;
562
563 if map.on_disk.is_empty() {
564 return Ok((map, None));
565 }
566
567 let parents =
568 parse_dirstate_entries(map.on_disk, |path, entry, copy_source| {
569 let tracked = entry.tracked();
570 let node = Self::get_or_insert_node_inner(
571 map.on_disk,
572 &mut map.unreachable_bytes,
573 &mut map.root,
574 path,
575 WithBasename::to_cow_borrowed,
576 |ancestor| {
577 if tracked {
578 ancestor.tracked_descendants_count += 1
579 }
580 ancestor.descendants_with_entry_count += 1
581 },
582 )?;
583 assert!(
584 !node.data.has_entry(),
585 "duplicate dirstate entry in read"
586 );
587 assert!(
588 node.copy_source.is_none(),
589 "duplicate dirstate entry in read"
590 );
591 node.data = NodeData::Entry(*entry);
592 node.copy_source = copy_source.map(Cow::Borrowed);
593 map.nodes_with_entry_count += 1;
594 if copy_source.is_some() {
595 map.nodes_with_copy_source_count += 1
596 }
597 Ok(())
598 })?;
599 let parents = Some(*parents);
600
601 Ok((map, parents))
602 }
603
604 /// Assuming dirstate-v2 format, returns whether the next write should
605 /// append to the existing data file that contains `self.on_disk` (true),
606 /// or create a new data file from scratch (false).
607 pub(super) fn write_should_append(&self) -> bool {
608 match self.write_mode {
609 DirstateMapWriteMode::ForceAppend => true,
610 DirstateMapWriteMode::ForceNewDataFile => false,
611 DirstateMapWriteMode::Auto => {
612 let ratio =
613 self.unreachable_bytes as f32 / self.on_disk.len() as f32;
614 ratio < ACCEPTABLE_UNREACHABLE_BYTES_RATIO
615 }
616 }
617 }
618
619 fn get_node<'tree>(
620 &'tree self,
621 path: &HgPath,
622 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
623 let mut children = self.root.as_ref();
624 let mut components = path.components();
625 let mut component =
626 components.next().expect("expected at least one components");
627 loop {
628 if let Some(child) = children.get(component, self.on_disk)? {
629 if let Some(next_component) = components.next() {
630 component = next_component;
631 children = child.children(self.on_disk)?;
632 } else {
633 return Ok(Some(child));
634 }
635 } else {
636 return Ok(None);
637 }
638 }
639 }
640
641 pub fn has_node(
642 &self,
643 path: &HgPath,
644 ) -> Result<bool, DirstateV2ParseError> {
645 let node = self.get_node(path)?;
646 Ok(node.is_some())
647 }
648
649 /// Returns a mutable reference to the node at `path` if it exists
650 ///
651 /// `each_ancestor` is a callback that is called for each ancestor node
652 /// when descending the tree. It is used to keep the different counters
653 /// of the `DirstateMap` up-to-date.
654 fn get_node_mut<'tree>(
655 &'tree mut self,
656 path: &HgPath,
657 each_ancestor: impl FnMut(&mut Node),
658 ) -> Result<Option<&'tree mut Node<'on_disk>>, DirstateV2ParseError> {
659 Self::get_node_mut_inner(
660 self.on_disk,
661 &mut self.unreachable_bytes,
662 &mut self.root,
663 path,
664 each_ancestor,
665 )
666 }
667
668 /// Lower-level version of `get_node_mut`.
669 ///
670 /// This takes `root` instead of `&mut self` so that callers can mutate
671 /// other fields while the returned borrow is still valid.
672 ///
673 /// `each_ancestor` is a callback that is called for each ancestor node
674 /// when descending the tree. It is used to keep the different counters
675 /// of the `DirstateMap` up-to-date.
676 fn get_node_mut_inner<'tree>(
677 on_disk: &'on_disk [u8],
678 unreachable_bytes: &mut u32,
679 root: &'tree mut ChildNodes<'on_disk>,
680 path: &HgPath,
681 mut each_ancestor: impl FnMut(&mut Node),
682 ) -> Result<Option<&'tree mut Node<'on_disk>>, DirstateV2ParseError> {
683 let mut children = root;
684 let mut components = path.components();
685 let mut component =
686 components.next().expect("expected at least one components");
687 loop {
688 if let Some(child) = children
689 .make_mut(on_disk, unreachable_bytes)?
690 .get_mut(component)
691 {
692 if let Some(next_component) = components.next() {
693 each_ancestor(child);
694 component = next_component;
695 children = &mut child.children;
696 } else {
697 return Ok(Some(child));
698 }
699 } else {
700 return Ok(None);
701 }
702 }
703 }
704
705 /// Get a mutable reference to the node at `path`, creating it if it does
706 /// not exist.
707 ///
708 /// `each_ancestor` is a callback that is called for each ancestor node
709 /// when descending the tree. It is used to keep the different counters
710 /// of the `DirstateMap` up-to-date.
711 fn get_or_insert_node<'tree, 'path>(
712 &'tree mut self,
713 path: &'path HgPath,
714 each_ancestor: impl FnMut(&mut Node),
715 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
716 Self::get_or_insert_node_inner(
717 self.on_disk,
718 &mut self.unreachable_bytes,
719 &mut self.root,
720 path,
721 WithBasename::to_cow_owned,
722 each_ancestor,
723 )
724 }
725
726 /// Lower-level version of `get_or_insert_node_inner`, which is used when
727 /// parsing disk data to remove allocations for new nodes.
728 fn get_or_insert_node_inner<'tree, 'path>(
729 on_disk: &'on_disk [u8],
730 unreachable_bytes: &mut u32,
731 root: &'tree mut ChildNodes<'on_disk>,
732 path: &'path HgPath,
733 to_cow: impl Fn(
734 WithBasename<&'path HgPath>,
735 ) -> WithBasename<Cow<'on_disk, HgPath>>,
736 mut each_ancestor: impl FnMut(&mut Node),
737 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
738 let mut child_nodes = root;
739 let mut inclusive_ancestor_paths =
740 WithBasename::inclusive_ancestors_of(path);
741 let mut ancestor_path = inclusive_ancestor_paths
742 .next()
743 .expect("expected at least one inclusive ancestor");
744 loop {
745 let (_, child_node) = child_nodes
746 .make_mut(on_disk, unreachable_bytes)?
747 .raw_entry_mut()
748 .from_key(ancestor_path.base_name())
749 .or_insert_with(|| (to_cow(ancestor_path), Node::default()));
750 if let Some(next) = inclusive_ancestor_paths.next() {
751 each_ancestor(child_node);
752 ancestor_path = next;
753 child_nodes = &mut child_node.children;
754 } else {
755 return Ok(child_node);
756 }
757 }
758 }
759
760 #[allow(clippy::too_many_arguments)]
761 fn reset_state(
762 &mut self,
763 filename: &HgPath,
764 old_entry_opt: Option<DirstateEntry>,
765 wc_tracked: bool,
766 p1_tracked: bool,
767 p2_info: bool,
768 has_meaningful_mtime: bool,
769 parent_file_data_opt: Option<ParentFileData>,
770 ) -> Result<(), DirstateError> {
771 let (had_entry, was_tracked) = match old_entry_opt {
772 Some(old_entry) => (true, old_entry.tracked()),
773 None => (false, false),
774 };
775 let node = self.get_or_insert_node(filename, |ancestor| {
776 if !had_entry {
777 ancestor.descendants_with_entry_count += 1;
778 }
779 if was_tracked {
780 if !wc_tracked {
781 ancestor.tracked_descendants_count = ancestor
782 .tracked_descendants_count
783 .checked_sub(1)
784 .expect("tracked count to be >= 0");
785 }
786 } else if wc_tracked {
787 ancestor.tracked_descendants_count += 1;
788 }
789 })?;
790
791 let v2_data = if let Some(parent_file_data) = parent_file_data_opt {
792 DirstateV2Data {
793 wc_tracked,
794 p1_tracked,
795 p2_info,
796 mode_size: parent_file_data.mode_size,
797 mtime: if has_meaningful_mtime {
798 parent_file_data.mtime
799 } else {
800 None
801 },
802 ..Default::default()
803 }
804 } else {
805 DirstateV2Data {
806 wc_tracked,
807 p1_tracked,
808 p2_info,
809 ..Default::default()
810 }
811 };
812 node.data = NodeData::Entry(DirstateEntry::from_v2_data(v2_data));
813 if !had_entry {
814 self.nodes_with_entry_count += 1;
815 }
816 Ok(())
817 }
818
819 fn set_tracked(
820 &mut self,
821 filename: &HgPath,
822 old_entry_opt: Option<DirstateEntry>,
823 ) -> Result<bool, DirstateV2ParseError> {
824 let was_tracked = old_entry_opt.is_some_and(|e| e.tracked());
825 let had_entry = old_entry_opt.is_some();
826 let tracked_count_increment = u32::from(!was_tracked);
827 let mut new = false;
828
829 let node = self.get_or_insert_node(filename, |ancestor| {
830 if !had_entry {
831 ancestor.descendants_with_entry_count += 1;
832 }
833
834 ancestor.tracked_descendants_count += tracked_count_increment;
835 })?;
836 if let Some(old_entry) = old_entry_opt {
837 let mut e = old_entry;
838 if e.tracked() {
839 // XXX
840 // This is probably overkill for more case, but we need this to
841 // fully replace the `normallookup` call with `set_tracked`
842 // one. Consider smoothing this in the future.
843 e.set_possibly_dirty();
844 } else {
845 new = true;
846 e.set_tracked();
847 }
848 node.data = NodeData::Entry(e)
849 } else {
850 node.data = NodeData::Entry(DirstateEntry::new_tracked());
851 self.nodes_with_entry_count += 1;
852 new = true;
853 };
854 Ok(new)
855 }
856
857 /// Set a node as untracked in the dirstate.
858 ///
859 /// It is the responsibility of the caller to remove the copy source and/or
860 /// the entry itself if appropriate.
861 ///
862 /// # Panics
863 ///
864 /// Panics if the node does not exist.
865 fn set_untracked(
866 &mut self,
867 filename: &HgPath,
868 old_entry: DirstateEntry,
869 ) -> Result<(), DirstateV2ParseError> {
870 let node = self
871 .get_node_mut(filename, |ancestor| {
872 ancestor.tracked_descendants_count = ancestor
873 .tracked_descendants_count
874 .checked_sub(1)
875 .expect("tracked_descendants_count should be >= 0");
876 })?
877 .expect("node should exist");
878 let mut new_entry = old_entry;
879 new_entry.set_untracked();
880 node.data = NodeData::Entry(new_entry);
881 Ok(())
882 }
883
884 /// Set a node as clean in the dirstate.
885 ///
886 /// It is the responsibility of the caller to remove the copy source.
887 ///
888 /// # Panics
889 ///
890 /// Panics if the node does not exist.
891 fn set_clean(
892 &mut self,
893 filename: &HgPath,
894 old_entry: DirstateEntry,
895 mode: u32,
896 size: u32,
897 mtime: TruncatedTimestamp,
898 ) -> Result<(), DirstateError> {
899 let node = self
900 .get_node_mut(filename, |ancestor| {
901 if !old_entry.tracked() {
902 ancestor.tracked_descendants_count += 1;
903 }
904 })?
905 .expect("node should exist");
906 let mut new_entry = old_entry;
907 new_entry.set_clean(mode, size, mtime);
908 node.data = NodeData::Entry(new_entry);
909 Ok(())
910 }
911
912 /// Set a node as possibly dirty in the dirstate.
913 ///
914 /// # Panics
915 ///
916 /// Panics if the node does not exist.
917 fn set_possibly_dirty(
918 &mut self,
919 filename: &HgPath,
920 ) -> Result<(), DirstateError> {
921 let node = self
922 .get_node_mut(filename, |_ancestor| {})?
923 .expect("node should exist");
924 let entry = node.data.as_entry_mut().expect("entry should exist");
925 entry.set_possibly_dirty();
926 node.data = NodeData::Entry(*entry);
927 Ok(())
928 }
929
930 /// Clears the cached mtime for the (potential) folder at `path`.
931 pub(super) fn clear_cached_mtime(
932 &mut self,
933 path: &HgPath,
934 ) -> Result<(), DirstateV2ParseError> {
935 let node = match self.get_node_mut(path, |_ancestor| {})? {
936 Some(node) => node,
937 None => return Ok(()),
938 };
939 if let NodeData::CachedDirectory { .. } = &node.data {
940 node.data = NodeData::None
941 }
942 Ok(())
943 }
944
945 /// Sets the cached mtime for the (potential) folder at `path`.
946 pub(super) fn set_cached_mtime(
947 &mut self,
948 path: &HgPath,
949 mtime: TruncatedTimestamp,
950 ) -> Result<(), DirstateV2ParseError> {
951 let node = match self.get_node_mut(path, |_ancestor| {})? {
952 Some(node) => node,
953 None => return Ok(()),
954 };
955 match &node.data {
956 NodeData::Entry(_) => {} // Don’t overwrite an entry
957 NodeData::CachedDirectory { .. } | NodeData::None => {
958 node.data = NodeData::CachedDirectory { mtime }
959 }
960 }
961 Ok(())
962 }
963
964 fn iter_nodes<'tree>(
965 &'tree self,
966 ) -> impl Iterator<
967 Item = Result<NodeRef<'tree, 'on_disk>, DirstateV2ParseError>,
968 > + 'tree {
969 // Depth first tree traversal.
970 //
971 // If we could afford internal iteration and recursion,
972 // this would look like:
973 //
974 // ```
975 // fn traverse_children(
976 // children: &ChildNodes,
977 // each: &mut impl FnMut(&Node),
978 // ) {
979 // for child in children.values() {
980 // traverse_children(&child.children, each);
981 // each(child);
982 // }
983 // }
984 // ```
985 //
986 // However we want an external iterator and therefore can’t use the
987 // call stack. Use an explicit stack instead:
988 let mut stack = Vec::new();
989 let mut iter = self.root.as_ref().iter();
990 std::iter::from_fn(move || {
991 while let Some(child_node) = iter.next() {
992 let children = match child_node.children(self.on_disk) {
993 Ok(children) => children,
994 Err(error) => return Some(Err(error)),
995 };
996 // Pseudo-recursion
997 let new_iter = children.iter();
998 let old_iter = std::mem::replace(&mut iter, new_iter);
999 stack.push((child_node, old_iter));
1000 }
1001 // Found the end of a `children.iter()` iterator.
1002 if let Some((child_node, next_iter)) = stack.pop() {
1003 // "Return" from pseudo-recursion by restoring state from the
1004 // explicit stack
1005 iter = next_iter;
1006
1007 Some(Ok(child_node))
1008 } else {
1009 // Reached the bottom of the stack, we’re done
1010 None
1011 }
1012 })
1013 }
1014
1015 fn count_dropped_path(unreachable_bytes: &mut u32, path: Cow<HgPath>) {
1016 if let Cow::Borrowed(path) = path {
1017 *unreachable_bytes += path.len() as u32
1018 }
1019 }
1020
1021 pub(crate) fn set_write_mode(&mut self, write_mode: DirstateMapWriteMode) {
1022 self.write_mode = write_mode;
1023 }
1024
1025 pub(crate) fn set_tracked_hint(&mut self, tracked_hint: bool) {
1026 self.use_tracked_hint = tracked_hint;
1027 }
1028 }
1029
1030 /// Sets the parameters for resetting a dirstate entry
1031 pub struct DirstateEntryReset<'a> {
1032 /// Which entry are we resetting
1033 pub filename: &'a HgPath,
1034 /// Whether the entry is tracked in the working copy
1035 pub wc_tracked: bool,
1036 /// Whether the entry is tracked in p1
1037 pub p1_tracked: bool,
1038 /// Whether the entry has merge information
1039 pub p2_info: bool,
1040 /// Whether the entry's mtime should be trusted
1041 pub has_meaningful_mtime: bool,
1042 /// Information from the parent file data (from the manifest)
1043 pub parent_file_data_opt: Option<ParentFileData>,
1044 /// Set this to `true` if you are *certain* that there is no old entry for
1045 /// this filename. Yield better performance in cases where we do a lot
1046 /// of additions to the dirstate.
1047 pub from_empty: bool,
1048 }
1049
1050 type DebugDirstateTuple<'a> = (&'a HgPath, (u8, i32, i32, i32));
1051
1052 impl OwningDirstateMap {
1053 pub fn clear(&mut self) {
1054 self.with_dmap_mut(|map| {
1055 map.root = Default::default();
1056 map.nodes_with_entry_count = 0;
1057 map.nodes_with_copy_source_count = 0;
1058 map.unreachable_bytes = map.on_disk.len() as u32;
1059 });
1060 }
1061
1062 pub fn set_tracked(
1063 &mut self,
1064 filename: &HgPath,
1065 ) -> Result<bool, DirstateV2ParseError> {
1066 let old_entry_opt = self.get(filename)?;
1067 self.with_dmap_mut(|map| map.set_tracked(filename, old_entry_opt))
1068 }
1069
1070 pub fn set_untracked(
1071 &mut self,
1072 filename: &HgPath,
1073 ) -> Result<bool, DirstateError> {
1074 let old_entry_opt = self.get(filename)?;
1075 match old_entry_opt {
1076 None => Ok(false),
1077 Some(old_entry) => {
1078 if !old_entry.tracked() {
1079 // `DirstateMap::set_untracked` is not a noop if
1080 // already not tracked as it will decrement the
1081 // tracked counters while going down.
1082 return Ok(true);
1083 }
1084 if old_entry.added() {
1085 // Untracking an "added" entry will just result in a
1086 // worthless entry (and other parts of the code will
1087 // complain about it), just drop it entirely.
1088 self.drop_entry_and_copy_source(filename)?;
1089 return Ok(true);
1090 }
1091 if !old_entry.p2_info() {
1092 self.copy_map_remove(filename)?;
1093 }
1094
1095 self.with_dmap_mut(|map| {
1096 map.set_untracked(filename, old_entry)?;
1097 Ok(true)
1098 })
1099 }
1100 }
1101 }
1102
1103 pub fn set_clean(
1104 &mut self,
1105 filename: &HgPath,
1106 mode: u32,
1107 size: u32,
1108 mtime: TruncatedTimestamp,
1109 ) -> Result<(), DirstateError> {
1110 let old_entry = match self.get(filename)? {
1111 None => {
1112 return Err(
1113 DirstateMapError::PathNotFound(filename.into()).into()
1114 )
1115 }
1116 Some(e) => e,
1117 };
1118 self.copy_map_remove(filename)?;
1119 self.with_dmap_mut(|map| {
1120 map.set_clean(filename, old_entry, mode, size, mtime)
1121 })
1122 }
1123
1124 pub fn set_possibly_dirty(
1125 &mut self,
1126 filename: &HgPath,
1127 ) -> Result<(), DirstateError> {
1128 if self.get(filename)?.is_none() {
1129 return Err(DirstateMapError::PathNotFound(filename.into()).into());
1130 }
1131 self.with_dmap_mut(|map| map.set_possibly_dirty(filename))
1132 }
1133
1134 pub fn reset_state(
1135 &mut self,
1136 reset: DirstateEntryReset,
1137 ) -> Result<bool, DirstateError> {
1138 if !(reset.p1_tracked || reset.p2_info || reset.wc_tracked) {
1139 self.drop_entry_and_copy_source(reset.filename)?;
1140 return Ok(false);
1141 }
1142 if !reset.from_empty {
1143 self.copy_map_remove(reset.filename)?;
1144 }
1145
1146 let old_entry_opt = if reset.from_empty {
1147 None
1148 } else {
1149 self.get(reset.filename)?
1150 };
1151
1152 self.with_dmap_mut(|map| {
1153 map.reset_state(
1154 reset.filename,
1155 old_entry_opt,
1156 reset.wc_tracked,
1157 reset.p1_tracked,
1158 reset.p2_info,
1159 reset.has_meaningful_mtime,
1160 reset.parent_file_data_opt,
1161 )?;
1162 Ok(old_entry_opt.is_none())
1163 })
1164 }
1165
1166 pub fn drop_entry_and_copy_source(
1167 &mut self,
1168 filename: &HgPath,
1169 ) -> Result<(), DirstateError> {
1170 let was_tracked = self.get(filename)?.is_some_and(|e| e.tracked());
1171 struct Dropped {
1172 was_tracked: bool,
1173 had_entry: bool,
1174 had_copy_source: bool,
1175 }
1176
1177 /// If this returns `Ok(Some((dropped, removed)))`, then
1178 ///
1179 /// * `dropped` is about the leaf node that was at `filename`
1180 /// * `removed` is whether this particular level of recursion just
1181 /// removed a node in `nodes`.
1182 fn recur<'on_disk>(
1183 on_disk: &'on_disk [u8],
1184 unreachable_bytes: &mut u32,
1185 nodes: &mut ChildNodes<'on_disk>,
1186 path: &HgPath,
1187 ) -> Result<Option<(Dropped, bool)>, DirstateV2ParseError> {
1188 let (first_path_component, rest_of_path) =
1189 path.split_first_component();
1190 let nodes = nodes.make_mut(on_disk, unreachable_bytes)?;
1191 let node = if let Some(node) = nodes.get_mut(first_path_component) {
1192 node
1193 } else {
1194 return Ok(None);
1195 };
1196 let dropped;
1197 if let Some(rest) = rest_of_path {
1198 if let Some((d, removed)) =
1199 recur(on_disk, unreachable_bytes, &mut node.children, rest)?
1200 {
1201 dropped = d;
1202 if dropped.had_entry {
1203 node.descendants_with_entry_count = node
1204 .descendants_with_entry_count
1205 .checked_sub(1)
1206 .expect(
1207 "descendants_with_entry_count should be >= 0",
1208 );
1209 }
1210 if dropped.was_tracked {
1211 node.tracked_descendants_count = node
1212 .tracked_descendants_count
1213 .checked_sub(1)
1214 .expect("tracked_descendants_count should be >= 0");
1215 }
1216
1217 // Directory caches must be invalidated when removing a
1218 // child node
1219 if removed {
1220 if let NodeData::CachedDirectory { .. } = &node.data {
1221 node.data = NodeData::None
1222 }
1223 }
1224 } else {
1225 return Ok(None);
1226 }
1227 } else {
1228 let entry = node.data.as_entry();
1229 let was_tracked = entry.is_some_and(|entry| entry.tracked());
1230 let had_entry = entry.is_some();
1231 if had_entry {
1232 node.data = NodeData::None
1233 }
1234 let mut had_copy_source = false;
1235 if let Some(source) = &node.copy_source {
1236 DirstateMap::count_dropped_path(
1237 unreachable_bytes,
1238 Cow::Borrowed(source),
1239 );
1240 had_copy_source = true;
1241 node.copy_source = None
1242 }
1243 dropped = Dropped { was_tracked, had_entry, had_copy_source };
1244 }
1245 // After recursion, for both leaf (rest_of_path is None) nodes and
1246 // parent nodes, remove a node if it just became empty.
1247 let remove = !node.data.has_entry()
1248 && node.copy_source.is_none()
1249 && node.children.is_empty();
1250 if remove {
1251 let (key, _) =
1252 nodes.remove_entry(first_path_component).unwrap();
1253 DirstateMap::count_dropped_path(
1254 unreachable_bytes,
1255 Cow::Borrowed(key.full_path()),
1256 )
1257 }
1258 Ok(Some((dropped, remove)))
1259 }
1260
1261 self.with_dmap_mut(|map| {
1262 if let Some((dropped, _removed)) = recur(
1263 map.on_disk,
1264 &mut map.unreachable_bytes,
1265 &mut map.root,
1266 filename,
1267 )? {
1268 if dropped.had_entry {
1269 map.nodes_with_entry_count = map
1270 .nodes_with_entry_count
1271 .checked_sub(1)
1272 .expect("nodes_with_entry_count should be >= 0");
1273 }
1274 if dropped.had_copy_source {
1275 map.nodes_with_copy_source_count = map
1276 .nodes_with_copy_source_count
1277 .checked_sub(1)
1278 .expect("nodes_with_copy_source_count should be >= 0");
1279 }
1280 } else {
1281 debug_assert!(!was_tracked);
1282 }
1283 Ok(())
1284 })
1285 }
1286
1287 pub fn has_tracked_dir(
1288 &mut self,
1289 directory: &HgPath,
1290 ) -> Result<bool, DirstateError> {
1291 self.with_dmap_mut(|map| {
1292 if let Some(node) = map.get_node(directory)? {
1293 // A node without a `DirstateEntry` was created to hold child
1294 // nodes, and is therefore a directory.
1295 let is_dir = node.entry()?.is_none();
1296 Ok(is_dir && node.tracked_descendants_count() > 0)
1297 } else {
1298 Ok(false)
1299 }
1300 })
1301 }
1302
1303 pub fn has_dir(
1304 &mut self,
1305 directory: &HgPath,
1306 ) -> Result<bool, DirstateError> {
1307 self.with_dmap_mut(|map| {
1308 if let Some(node) = map.get_node(directory)? {
1309 // A node without a `DirstateEntry` was created to hold child
1310 // nodes, and is therefore a directory.
1311 let is_dir = node.entry()?.is_none();
1312 Ok(is_dir && node.descendants_with_entry_count() > 0)
1313 } else {
1314 Ok(false)
1315 }
1316 })
1317 }
1318
1319 #[tracing::instrument(level = "debug", skip_all)]
1320 pub fn pack_v1(
1321 &self,
1322 parents: DirstateParents,
1323 ) -> Result<Vec<u8>, DirstateError> {
1324 let map = self.get_map();
1325 // Optizimation (to be measured?): pre-compute size to avoid `Vec`
1326 // reallocations
1327 let mut size = parents.as_bytes().len();
1328 for node in map.iter_nodes() {
1329 let node = node?;
1330 if node.entry()?.is_some() {
1331 size += packed_entry_size(
1332 node.full_path(map.on_disk)?,
1333 node.copy_source(map.on_disk)?,
1334 );
1335 }
1336 }
1337
1338 let mut packed = Vec::with_capacity(size);
1339 packed.extend(parents.as_bytes());
1340
1341 for node in map.iter_nodes() {
1342 let node = node?;
1343 if let Some(entry) = node.entry()? {
1344 pack_entry(
1345 node.full_path(map.on_disk)?,
1346 &entry,
1347 node.copy_source(map.on_disk)?,
1348 &mut packed,
1349 );
1350 }
1351 }
1352 Ok(packed)
1353 }
1354
1355 /// Returns new data and metadata together with whether that data should be
1356 /// appended to the existing data file whose content is at
1357 /// `map.on_disk` (true), instead of written to a new data file
1358 /// (false), and the previous size of data on disk.
1359 #[tracing::instrument(level = "debug", skip_all)]
1360 pub fn pack_v2(
1361 &self,
1362 write_mode: DirstateMapWriteMode,
1363 ) -> Result<(Vec<u8>, on_disk::TreeMetadata, bool, usize), DirstateError>
1364 {
1365 let map = self.get_map();
1366 on_disk::write(map, write_mode)
1367 }
1368
1369 /// `callback` allows the caller to process and do something with the
1370 /// results of the status. This is needed to do so efficiently (i.e.
1371 /// without cloning the `DirstateStatus` object with its paths) because
1372 /// we need to borrow from `Self`.
1373 pub fn with_status<R, C>(
1374 &mut self,
1375 matcher: &impl Matcher,
1376 root_dir: PathBuf,
1377 ignore_files: Vec<PathBuf>,
1378 options: StatusOptions,
1379 callback: C,
1380 ) -> R
1381 where
1382 C: for<'r> FnOnce(
1383 Result<DirstateStatus<'r>, StatusError>,
1384 HgWarningContext,
1385 ) -> R,
1386 {
1387 self.with_dmap_mut(|map| {
1388 let warnings = HgWarningContext::new();
1389 callback(
1390 super::status::status(
1391 map,
1392 matcher,
1393 root_dir,
1394 ignore_files,
1395 options,
1396 warnings.sender(),
1397 ),
1398 warnings,
1399 )
1400 })
1401 }
1402
1403 pub fn copy_map_len(&self) -> usize {
1404 let map = self.get_map();
1405 map.nodes_with_copy_source_count as usize
1406 }
1407
1408 pub fn copy_map_iter(&self) -> CopyMapIter<'_> {
1409 let map = self.get_map();
1410 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1411 Ok(if let Some(source) = node.copy_source(map.on_disk)? {
1412 Some((node.full_path(map.on_disk)?, source))
1413 } else {
1414 None
1415 })
1416 }))
1417 }
1418
1419 pub fn copy_map_contains_key(
1420 &self,
1421 key: &HgPath,
1422 ) -> Result<bool, DirstateV2ParseError> {
1423 let map = self.get_map();
1424 Ok(if let Some(node) = map.get_node(key)? {
1425 node.has_copy_source()
1426 } else {
1427 false
1428 })
1429 }
1430
1431 pub fn copy_map_get(
1432 &self,
1433 key: &HgPath,
1434 ) -> Result<Option<&HgPath>, DirstateV2ParseError> {
1435 let map = self.get_map();
1436 if let Some(node) = map.get_node(key)? {
1437 if let Some(source) = node.copy_source(map.on_disk)? {
1438 return Ok(Some(source));
1439 }
1440 }
1441 Ok(None)
1442 }
1443
1444 pub fn copy_map_remove(
1445 &mut self,
1446 key: &HgPath,
1447 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1448 self.with_dmap_mut(|map| {
1449 let count = &mut map.nodes_with_copy_source_count;
1450 let unreachable_bytes = &mut map.unreachable_bytes;
1451 Ok(DirstateMap::get_node_mut_inner(
1452 map.on_disk,
1453 unreachable_bytes,
1454 &mut map.root,
1455 key,
1456 |_ancestor| {},
1457 )?
1458 .and_then(|node| {
1459 if let Some(source) = &node.copy_source {
1460 *count = count
1461 .checked_sub(1)
1462 .expect("nodes_with_copy_source_count should be >= 0");
1463 DirstateMap::count_dropped_path(
1464 unreachable_bytes,
1465 Cow::Borrowed(source),
1466 );
1467 }
1468 node.copy_source.take().map(Cow::into_owned)
1469 }))
1470 })
1471 }
1472
1473 pub fn copy_map_insert(
1474 &mut self,
1475 key: &HgPath,
1476 value: &HgPath,
1477 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1478 self.with_dmap_mut(|map| {
1479 let node = map.get_or_insert_node(key, |_ancestor| {})?;
1480 let had_copy_source = node.copy_source.is_none();
1481 let old = node
1482 .copy_source
1483 .replace(value.to_owned().into())
1484 .map(Cow::into_owned);
1485 if had_copy_source {
1486 map.nodes_with_copy_source_count += 1
1487 }
1488 Ok(old)
1489 })
1490 }
1491
1492 pub fn len(&self) -> usize {
1493 let map = self.get_map();
1494 map.nodes_with_entry_count as usize
1495 }
1496
1497 pub fn is_empty(&self) -> bool {
1498 self.len() == 0
1499 }
1500
1501 pub fn contains_key(
1502 &self,
1503 key: &HgPath,
1504 ) -> Result<bool, DirstateV2ParseError> {
1505 Ok(self.get(key)?.is_some())
1506 }
1507
1508 pub fn get(
1509 &self,
1510 key: &HgPath,
1511 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
1512 let map = self.get_map();
1513 Ok(if let Some(node) = map.get_node(key)? {
1514 node.entry()?
1515 } else {
1516 None
1517 })
1518 }
1519
1520 pub fn iter(&self) -> StateMapIter<'_> {
1521 let map = self.get_map();
1522 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1523 Ok(if let Some(entry) = node.entry()? {
1524 Some((node.full_path(map.on_disk)?, entry))
1525 } else {
1526 None
1527 })
1528 }))
1529 }
1530
1531 pub fn iter_tracked_dirs(
1532 &mut self,
1533 ) -> Result<
1534 Box<
1535 dyn Iterator<Item = Result<&HgPath, DirstateV2ParseError>>
1536 + Send
1537 + '_,
1538 >,
1539 DirstateError,
1540 > {
1541 let map = self.get_map();
1542 let on_disk = map.on_disk;
1543 Ok(Box::new(filter_map_results(map.iter_nodes(), move |node| {
1544 Ok(if node.tracked_descendants_count() > 0 {
1545 Some(node.full_path(on_disk)?)
1546 } else {
1547 None
1548 })
1549 })))
1550 }
1551
1552 /// Only public because it needs to be exposed to the Python layer.
1553 /// It is not the full `setparents` logic, only the parts that mutate the
1554 /// entries.
1555 pub fn setparents_fixup(
1556 &mut self,
1557 ) -> Result<Vec<(HgPathBuf, HgPathBuf)>, DirstateV2ParseError> {
1558 // XXX
1559 // All the copying and re-querying is quite inefficient, but this is
1560 // still a lot better than doing it from Python.
1561 //
1562 // The better solution is to develop a mechanism for `iter_mut`,
1563 // which will be a lot more involved: we're dealing with a lazy,
1564 // append-mostly, tree-like data structure. This will do for now.
1565 let mut copies = vec![];
1566 let mut files_with_p2_info = vec![];
1567 for res in self.iter() {
1568 let (path, entry) = res?;
1569 if entry.p2_info() {
1570 files_with_p2_info.push(path.to_owned())
1571 }
1572 }
1573 self.with_dmap_mut(|map| {
1574 for path in files_with_p2_info.iter() {
1575 let node = map.get_or_insert_node(path, |_| {})?;
1576 let entry =
1577 node.data.as_entry_mut().expect("entry should exist");
1578 entry.drop_merge_data();
1579 if let Some(source) = node.copy_source.take().as_deref() {
1580 copies.push((path.to_owned(), source.to_owned()));
1581 }
1582 }
1583 Ok(copies)
1584 })
1585 }
1586
1587 pub fn debug_iter(
1588 &self,
1589 all: bool,
1590 ) -> Box<
1591 dyn Iterator<Item = Result<DebugDirstateTuple, DirstateV2ParseError>>
1592 + Send
1593 + '_,
1594 > {
1595 let map = self.get_map();
1596 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1597 let debug_tuple = if let Some(entry) = node.entry()? {
1598 entry.debug_tuple()
1599 } else if !all {
1600 return Ok(None);
1601 } else if let Some(mtime) = node.cached_directory_mtime()? {
1602 (b' ', 0, -1, mtime.truncated_seconds() as i32)
1603 } else {
1604 (b' ', 0, -1, -1)
1605 };
1606 Ok(Some((node.full_path(map.on_disk)?, debug_tuple)))
1607 }))
1608 }
1609 }
1610 #[cfg(test)]
1611 mod tests {
1612 use super::*;
1613
1614 /// Shortcut to return tracked descendants of a path.
1615 /// Panics if the path does not exist.
1616 fn tracked_descendants(map: &OwningDirstateMap, path: &[u8]) -> u32 {
1617 let path = dbg!(HgPath::new(path));
1618 let node = map.get_map().get_node(path);
1619 node.unwrap().unwrap().tracked_descendants_count()
1620 }
1621
1622 /// Shortcut to return descendants with an entry.
1623 /// Panics if the path does not exist.
1624 fn descendants_with_an_entry(map: &OwningDirstateMap, path: &[u8]) -> u32 {
1625 let path = dbg!(HgPath::new(path));
1626 let node = map.get_map().get_node(path);
1627 node.unwrap().unwrap().descendants_with_entry_count()
1628 }
1629
1630 fn assert_does_not_exist(map: &OwningDirstateMap, path: &[u8]) {
1631 let path = dbg!(HgPath::new(path));
1632 let node = map.get_map().get_node(path);
1633 assert!(node.unwrap().is_none());
1634 }
1635
1636 /// Shortcut for path creation in tests
1637 fn p(b: &[u8]) -> &HgPath {
1638 HgPath::new(b)
1639 }
1640
1641 /// Test the very simple case a single tracked file
1642 #[test]
1643 fn test_tracked_descendants_simple() -> Result<(), DirstateError> {
1644 let mut map = OwningDirstateMap::new_empty(vec![], None);
1645 assert_eq!(map.len(), 0);
1646
1647 map.set_tracked(p(b"some/nested/path"))?;
1648
1649 assert_eq!(map.len(), 1);
1650 assert_eq!(tracked_descendants(&map, b"some"), 1);
1651 assert_eq!(tracked_descendants(&map, b"some/nested"), 1);
1652 assert_eq!(tracked_descendants(&map, b"some/nested/path"), 0);
1653
1654 map.set_untracked(p(b"some/nested/path"))?;
1655 assert_eq!(map.len(), 0);
1656 assert!(map.get_map().get_node(p(b"some"))?.is_none());
1657
1658 Ok(())
1659 }
1660
1661 /// Test the simple case of all tracked, but multiple files
1662 #[test]
1663 fn test_tracked_descendants_multiple() -> Result<(), DirstateError> {
1664 let mut map = OwningDirstateMap::new_empty(vec![], None);
1665
1666 map.set_tracked(p(b"some/nested/path"))?;
1667 map.set_tracked(p(b"some/nested/file"))?;
1668 // one layer without any files to test deletion cascade
1669 map.set_tracked(p(b"some/other/nested/path"))?;
1670 map.set_tracked(p(b"root_file"))?;
1671 map.set_tracked(p(b"some/file"))?;
1672 map.set_tracked(p(b"some/file2"))?;
1673 map.set_tracked(p(b"some/file3"))?;
1674
1675 assert_eq!(map.len(), 7);
1676 assert_eq!(tracked_descendants(&map, b"some"), 6);
1677 assert_eq!(tracked_descendants(&map, b"some/nested"), 2);
1678 assert_eq!(tracked_descendants(&map, b"some/other"), 1);
1679 assert_eq!(tracked_descendants(&map, b"some/other/nested"), 1);
1680 assert_eq!(tracked_descendants(&map, b"some/nested/path"), 0);
1681
1682 map.set_untracked(p(b"some/nested/path"))?;
1683 assert_eq!(map.len(), 6);
1684 assert_eq!(tracked_descendants(&map, b"some"), 5);
1685 assert_eq!(tracked_descendants(&map, b"some/nested"), 1);
1686 assert_eq!(tracked_descendants(&map, b"some/other"), 1);
1687 assert_eq!(tracked_descendants(&map, b"some/other/nested"), 1);
1688
1689 map.set_untracked(p(b"some/nested/file"))?;
1690 assert_eq!(map.len(), 5);
1691 assert_eq!(tracked_descendants(&map, b"some"), 4);
1692 assert_eq!(tracked_descendants(&map, b"some/other"), 1);
1693 assert_eq!(tracked_descendants(&map, b"some/other/nested"), 1);
1694 assert_does_not_exist(&map, b"some_nested");
1695
1696 map.set_untracked(p(b"some/other/nested/path"))?;
1697 assert_eq!(map.len(), 4);
1698 assert_eq!(tracked_descendants(&map, b"some"), 3);
1699 assert_does_not_exist(&map, b"some/other");
1700
1701 map.set_untracked(p(b"root_file"))?;
1702 assert_eq!(map.len(), 3);
1703 assert_eq!(tracked_descendants(&map, b"some"), 3);
1704 assert_does_not_exist(&map, b"root_file");
1705
1706 map.set_untracked(p(b"some/file"))?;
1707 assert_eq!(map.len(), 2);
1708 assert_eq!(tracked_descendants(&map, b"some"), 2);
1709 assert_does_not_exist(&map, b"some/file");
1710
1711 map.set_untracked(p(b"some/file2"))?;
1712 assert_eq!(map.len(), 1);
1713 assert_eq!(tracked_descendants(&map, b"some"), 1);
1714 assert_does_not_exist(&map, b"some/file2");
1715
1716 map.set_untracked(p(b"some/file3"))?;
1717 assert_eq!(map.len(), 0);
1718 assert_does_not_exist(&map, b"some/file3");
1719
1720 Ok(())
1721 }
1722
1723 /// Check with a mix of tracked and non-tracked items
1724 #[test]
1725 fn test_tracked_descendants_different() -> Result<(), DirstateError> {
1726 let mut map = OwningDirstateMap::new_empty(vec![], None);
1727
1728 // A file that was just added
1729 map.set_tracked(p(b"some/nested/path"))?;
1730 // This has no information, the dirstate should ignore it
1731 let reset = DirstateEntryReset {
1732 filename: p(b"some/file"),
1733 wc_tracked: false,
1734 p1_tracked: false,
1735 p2_info: false,
1736 has_meaningful_mtime: false,
1737 parent_file_data_opt: None,
1738 from_empty: false,
1739 };
1740 map.reset_state(reset)?;
1741 assert_does_not_exist(&map, b"some/file");
1742
1743 // A file that was removed
1744 let reset = DirstateEntryReset {
1745 filename: p(b"some/nested/file"),
1746 wc_tracked: false,
1747 p1_tracked: true,
1748 p2_info: false,
1749 has_meaningful_mtime: false,
1750 parent_file_data_opt: None,
1751 from_empty: false,
1752 };
1753 map.reset_state(reset)?;
1754 assert!(!map.get(p(b"some/nested/file"))?.unwrap().tracked());
1755 // Only present in p2
1756 let reset = DirstateEntryReset {
1757 filename: p(b"some/file3"),
1758 wc_tracked: false,
1759 p1_tracked: false,
1760 p2_info: true,
1761 has_meaningful_mtime: false,
1762 parent_file_data_opt: None,
1763 from_empty: false,
1764 };
1765 map.reset_state(reset)?;
1766 assert!(!map.get(p(b"some/file3"))?.unwrap().tracked());
1767 // A file that was merged
1768 let reset = DirstateEntryReset {
1769 filename: p(b"root_file"),
1770 wc_tracked: true,
1771 p1_tracked: true,
1772 p2_info: true,
1773 has_meaningful_mtime: false,
1774 parent_file_data_opt: None,
1775 from_empty: false,
1776 };
1777 map.reset_state(reset)?;
1778 assert!(map.get(p(b"root_file"))?.unwrap().tracked());
1779 // A file that is added, with info from p2
1780 // XXX is that actually possible?
1781 let reset = DirstateEntryReset {
1782 filename: p(b"some/file2"),
1783 wc_tracked: true,
1784 p1_tracked: false,
1785 p2_info: true,
1786 has_meaningful_mtime: false,
1787 parent_file_data_opt: None,
1788 from_empty: false,
1789 };
1790 map.reset_state(reset)?;
1791 assert!(map.get(p(b"some/file2"))?.unwrap().tracked());
1792 // A clean file
1793 // One layer without any files to test deletion cascade
1794 let reset = DirstateEntryReset {
1795 filename: p(b"some/other/nested/path"),
1796 wc_tracked: true,
1797 p1_tracked: true,
1798 p2_info: false,
1799 has_meaningful_mtime: false,
1800 parent_file_data_opt: None,
1801 from_empty: false,
1802 };
1803 map.reset_state(reset)?;
1804 assert!(map.get(p(b"some/other/nested/path"))?.unwrap().tracked());
1805
1806 assert_eq!(map.len(), 6);
1807 assert_eq!(tracked_descendants(&map, b"some"), 3);
1808 assert_eq!(descendants_with_an_entry(&map, b"some"), 5);
1809 assert_eq!(tracked_descendants(&map, b"some/other/nested"), 1);
1810 assert_eq!(descendants_with_an_entry(&map, b"some/other/nested"), 1);
1811 assert_eq!(tracked_descendants(&map, b"some/other/nested/path"), 0);
1812 assert_eq!(
1813 descendants_with_an_entry(&map, b"some/other/nested/path"),
1814 0
1815 );
1816 assert_eq!(tracked_descendants(&map, b"some/nested"), 1);
1817 assert_eq!(descendants_with_an_entry(&map, b"some/nested"), 2);
1818
1819 // might as well check this
1820 map.set_untracked(p(b"path/does/not/exist"))?;
1821 assert_eq!(map.len(), 6);
1822
1823 map.set_untracked(p(b"some/other/nested/path"))?;
1824 // It is set untracked but not deleted since it held other information
1825 assert_eq!(map.len(), 6);
1826 assert_eq!(tracked_descendants(&map, b"some"), 2);
1827 assert_eq!(descendants_with_an_entry(&map, b"some"), 5);
1828 assert_eq!(descendants_with_an_entry(&map, b"some/other"), 1);
1829 assert_eq!(descendants_with_an_entry(&map, b"some/other/nested"), 1);
1830 assert_eq!(tracked_descendants(&map, b"some/nested"), 1);
1831 assert_eq!(descendants_with_an_entry(&map, b"some/nested"), 2);
1832
1833 map.set_untracked(p(b"some/nested/path"))?;
1834 // It is set untracked *and* deleted since it was only added
1835 assert_eq!(map.len(), 5);
1836 assert_eq!(tracked_descendants(&map, b"some"), 1);
1837 assert_eq!(descendants_with_an_entry(&map, b"some"), 4);
1838 assert_eq!(tracked_descendants(&map, b"some/nested"), 0);
1839 assert_eq!(descendants_with_an_entry(&map, b"some/nested"), 1);
1840 assert_does_not_exist(&map, b"some/nested/path");
1841
1842 map.set_untracked(p(b"root_file"))?;
1843 // Untracked but not deleted
1844 assert_eq!(map.len(), 5);
1845 assert!(map.get(p(b"root_file"))?.is_some());
1846
1847 map.set_untracked(p(b"some/file2"))?;
1848 assert_eq!(map.len(), 5);
1849 assert_eq!(tracked_descendants(&map, b"some"), 0);
1850 assert!(map.get(p(b"some/file2"))?.is_some());
1851
1852 map.set_untracked(p(b"some/file3"))?;
1853 assert_eq!(map.len(), 5);
1854 assert_eq!(tracked_descendants(&map, b"some"), 0);
1855 assert!(map.get(p(b"some/file3"))?.is_some());
1856
1857 Ok(())
1858 }
1859
1860 /// Check that copies counter is correctly updated
1861 #[test]
1862 fn test_copy_source() -> Result<(), DirstateError> {
1863 let mut map = OwningDirstateMap::new_empty(vec![], None);
1864
1865 // Clean file
1866 let reset = DirstateEntryReset {
1867 filename: p(b"files/clean"),
1868 wc_tracked: true,
1869 p1_tracked: true,
1870 p2_info: false,
1871 has_meaningful_mtime: false,
1872 parent_file_data_opt: None,
1873 from_empty: false,
1874 };
1875 map.reset_state(reset)?;
1876 // Merged file
1877 let reset = DirstateEntryReset {
1878 filename: p(b"files/from_p2"),
1879 wc_tracked: true,
1880 p1_tracked: true,
1881 p2_info: true,
1882 has_meaningful_mtime: false,
1883 parent_file_data_opt: None,
1884 from_empty: false,
1885 };
1886 map.reset_state(reset)?;
1887 // Removed file
1888 let reset = DirstateEntryReset {
1889 filename: p(b"removed"),
1890 wc_tracked: false,
1891 p1_tracked: true,
1892 p2_info: false,
1893 has_meaningful_mtime: false,
1894 parent_file_data_opt: None,
1895 from_empty: false,
1896 };
1897 map.reset_state(reset)?;
1898 // Added file
1899 let reset = DirstateEntryReset {
1900 filename: p(b"files/added"),
1901 wc_tracked: true,
1902 p1_tracked: false,
1903 p2_info: false,
1904 has_meaningful_mtime: false,
1905 parent_file_data_opt: None,
1906 from_empty: false,
1907 };
1908 map.reset_state(reset)?;
1909 // Add copy
1910 map.copy_map_insert(p(b"files/clean"), p(b"clean_copy_source"))?;
1911 assert_eq!(map.copy_map_len(), 1);
1912
1913 // Copy override
1914 map.copy_map_insert(p(b"files/clean"), p(b"other_clean_copy_source"))?;
1915 assert_eq!(map.copy_map_len(), 1);
1916
1917 // Multiple copies
1918 map.copy_map_insert(p(b"removed"), p(b"removed_copy_source"))?;
1919 assert_eq!(map.copy_map_len(), 2);
1920
1921 map.copy_map_insert(p(b"files/added"), p(b"added_copy_source"))?;
1922 assert_eq!(map.copy_map_len(), 3);
1923
1924 // Added, so the entry is completely removed
1925 map.set_untracked(p(b"files/added"))?;
1926 assert_does_not_exist(&map, b"files/added");
1927 assert_eq!(map.copy_map_len(), 2);
1928
1929 // Removed, so the entry is kept around, so is its copy
1930 map.set_untracked(p(b"removed"))?;
1931 assert!(map.get(p(b"removed"))?.is_some());
1932 assert_eq!(map.copy_map_len(), 2);
1933
1934 // Clean, so the entry is kept around, but not its copy
1935 map.set_untracked(p(b"files/clean"))?;
1936 assert!(map.get(p(b"files/clean"))?.is_some());
1937 assert_eq!(map.copy_map_len(), 1);
1938
1939 map.copy_map_insert(p(b"files/from_p2"), p(b"from_p2_copy_source"))?;
1940 assert_eq!(map.copy_map_len(), 2);
1941
1942 // Info from p2, so its copy source info is kept around
1943 map.set_untracked(p(b"files/from_p2"))?;
1944 assert!(map.get(p(b"files/from_p2"))?.is_some());
1945 assert_eq!(map.copy_map_len(), 2);
1946
1947 Ok(())
1948 }
1949
1950 /// Test with "on disk" data. For the sake of this test, the "on disk" data
1951 /// does not actually come from the disk, but it's opaque to the code being
1952 /// tested.
1953 #[test]
1954 fn test_on_disk() -> Result<(), DirstateError> {
1955 // First let's create some data to put "on disk"
1956 let mut map = OwningDirstateMap::new_empty(vec![], None);
1957
1958 // A file that was just added
1959 map.set_tracked(p(b"some/nested/added"))?;
1960 map.copy_map_insert(p(b"some/nested/added"), p(b"added_copy_source"))?;
1961
1962 // A file that was removed
1963 let reset = DirstateEntryReset {
1964 filename: p(b"some/nested/removed"),
1965 wc_tracked: false,
1966 p1_tracked: true,
1967 p2_info: false,
1968 has_meaningful_mtime: false,
1969 parent_file_data_opt: None,
1970 from_empty: false,
1971 };
1972 map.reset_state(reset)?;
1973 // Only present in p2
1974 let reset = DirstateEntryReset {
1975 filename: p(b"other/p2_info_only"),
1976 wc_tracked: false,
1977 p1_tracked: false,
1978 p2_info: true,
1979 has_meaningful_mtime: false,
1980 parent_file_data_opt: None,
1981 from_empty: false,
1982 };
1983 map.reset_state(reset)?;
1984 map.copy_map_insert(
1985 p(b"other/p2_info_only"),
1986 p(b"other/p2_info_copy_source"),
1987 )?;
1988 // A file that was merged
1989 let reset = DirstateEntryReset {
1990 filename: p(b"merged"),
1991 wc_tracked: true,
1992 p1_tracked: true,
1993 p2_info: true,
1994 has_meaningful_mtime: false,
1995 parent_file_data_opt: None,
1996 from_empty: false,
1997 };
1998 map.reset_state(reset)?;
1999 // A file that is added, with info from p2
2000 // XXX is that actually possible?
2001 let reset = DirstateEntryReset {
2002 filename: p(b"other/added_with_p2"),
2003 wc_tracked: true,
2004 p1_tracked: false,
2005 p2_info: true,
2006 has_meaningful_mtime: false,
2007 parent_file_data_opt: None,
2008 from_empty: false,
2009 };
2010 map.reset_state(reset)?;
2011 // One layer without any files to test deletion cascade
2012 // A clean file
2013 let reset = DirstateEntryReset {
2014 filename: p(b"some/other/nested/clean"),
2015 wc_tracked: true,
2016 p1_tracked: true,
2017 p2_info: false,
2018 has_meaningful_mtime: false,
2019 parent_file_data_opt: None,
2020 from_empty: false,
2021 };
2022 map.reset_state(reset)?;
2023
2024 let (packed, metadata, _should_append, _old_data_size) =
2025 map.pack_v2(DirstateMapWriteMode::ForceNewDataFile)?;
2026 let packed_len = packed.len();
2027 assert!(packed_len > 0);
2028
2029 // Recreate "from disk"
2030 let mut map = OwningDirstateMap::new_v2(
2031 packed,
2032 packed_len,
2033 metadata.as_bytes(),
2034 vec![],
2035 None,
2036 )?;
2037
2038 // Check that everything is accounted for
2039 assert!(map.contains_key(p(b"some/nested/added"))?);
2040 assert!(map.contains_key(p(b"some/nested/removed"))?);
2041 assert!(map.contains_key(p(b"merged"))?);
2042 assert!(map.contains_key(p(b"other/p2_info_only"))?);
2043 assert!(map.contains_key(p(b"other/added_with_p2"))?);
2044 assert!(map.contains_key(p(b"some/other/nested/clean"))?);
2045 assert_eq!(
2046 map.copy_map_get(p(b"some/nested/added"))?,
2047 Some(p(b"added_copy_source"))
2048 );
2049 assert_eq!(
2050 map.copy_map_get(p(b"other/p2_info_only"))?,
2051 Some(p(b"other/p2_info_copy_source"))
2052 );
2053 assert_eq!(tracked_descendants(&map, b"some"), 2);
2054 assert_eq!(descendants_with_an_entry(&map, b"some"), 3);
2055 assert_eq!(tracked_descendants(&map, b"other"), 1);
2056 assert_eq!(descendants_with_an_entry(&map, b"other"), 2);
2057 assert_eq!(tracked_descendants(&map, b"some/other"), 1);
2058 assert_eq!(descendants_with_an_entry(&map, b"some/other"), 1);
2059 assert_eq!(tracked_descendants(&map, b"some/other/nested"), 1);
2060 assert_eq!(descendants_with_an_entry(&map, b"some/other/nested"), 1);
2061 assert_eq!(tracked_descendants(&map, b"some/nested"), 1);
2062 assert_eq!(descendants_with_an_entry(&map, b"some/nested"), 2);
2063 assert_eq!(map.len(), 6);
2064 assert_eq!(map.get_map().unreachable_bytes, 0);
2065 assert_eq!(map.copy_map_len(), 2);
2066
2067 // Shouldn't change anything since it's already not tracked
2068 map.set_untracked(p(b"some/nested/removed"))?;
2069 assert_eq!(map.get_map().unreachable_bytes, 0);
2070
2071 if let ChildNodes::InMemory(_) = map.get_map().root {
2072 panic!("root should not have been mutated")
2073 }
2074 // We haven't mutated enough (nothing, actually), we should still be in
2075 // the append strategy
2076 assert!(map.get_map().write_should_append());
2077
2078 // But this mutates the structure, so there should be unreachable_bytes
2079 assert!(map.set_untracked(p(b"some/nested/added"))?);
2080 let unreachable_bytes = map.get_map().unreachable_bytes;
2081 assert!(unreachable_bytes > 0);
2082
2083 if let ChildNodes::OnDisk(_) = map.get_map().root {
2084 panic!("root should have been mutated")
2085 }
2086
2087 // This should not mutate the structure either, since `root` has
2088 // already been mutated along with its direct children.
2089 map.set_untracked(p(b"merged"))?;
2090 assert_eq!(map.get_map().unreachable_bytes, unreachable_bytes);
2091
2092 if let NodeRef::InMemory(_, _) =
2093 map.get_map().get_node(p(b"other/added_with_p2"))?.unwrap()
2094 {
2095 panic!("'other/added_with_p2' should not have been mutated")
2096 }
2097 // But this should, since it's in a different path
2098 // than `<root>some/nested/add`
2099 map.set_untracked(p(b"other/added_with_p2"))?;
2100 assert!(map.get_map().unreachable_bytes > unreachable_bytes);
2101
2102 if let NodeRef::OnDisk(_) =
2103 map.get_map().get_node(p(b"other/added_with_p2"))?.unwrap()
2104 {
2105 panic!("'other/added_with_p2' should have been mutated")
2106 }
2107
2108 // We have rewritten most of the tree, we should create a new file
2109 assert!(!map.get_map().write_should_append());
2110
2111 Ok(())
2112 }
2113 }