##// END OF EJS Templates
rust-dirstate: panic if the DirstateMap counters go below 0...
Raphaël Gomès -
r49865:2593873c stable
parent child Browse files
Show More
@@ -1,1180 +1,1196 b''
1 use bytes_cast::BytesCast;
1 use bytes_cast::BytesCast;
2 use micro_timer::timed;
2 use micro_timer::timed;
3 use std::borrow::Cow;
3 use std::borrow::Cow;
4 use std::path::PathBuf;
4 use std::path::PathBuf;
5
5
6 use super::on_disk;
6 use super::on_disk;
7 use super::on_disk::DirstateV2ParseError;
7 use super::on_disk::DirstateV2ParseError;
8 use super::owning::OwningDirstateMap;
8 use super::owning::OwningDirstateMap;
9 use super::path_with_basename::WithBasename;
9 use super::path_with_basename::WithBasename;
10 use crate::dirstate::parsers::pack_entry;
10 use crate::dirstate::parsers::pack_entry;
11 use crate::dirstate::parsers::packed_entry_size;
11 use crate::dirstate::parsers::packed_entry_size;
12 use crate::dirstate::parsers::parse_dirstate_entries;
12 use crate::dirstate::parsers::parse_dirstate_entries;
13 use crate::dirstate::CopyMapIter;
13 use crate::dirstate::CopyMapIter;
14 use crate::dirstate::StateMapIter;
14 use crate::dirstate::StateMapIter;
15 use crate::dirstate::TruncatedTimestamp;
15 use crate::dirstate::TruncatedTimestamp;
16 use crate::dirstate::SIZE_FROM_OTHER_PARENT;
16 use crate::dirstate::SIZE_FROM_OTHER_PARENT;
17 use crate::dirstate::SIZE_NON_NORMAL;
17 use crate::dirstate::SIZE_NON_NORMAL;
18 use crate::matchers::Matcher;
18 use crate::matchers::Matcher;
19 use crate::utils::hg_path::{HgPath, HgPathBuf};
19 use crate::utils::hg_path::{HgPath, HgPathBuf};
20 use crate::DirstateEntry;
20 use crate::DirstateEntry;
21 use crate::DirstateError;
21 use crate::DirstateError;
22 use crate::DirstateParents;
22 use crate::DirstateParents;
23 use crate::DirstateStatus;
23 use crate::DirstateStatus;
24 use crate::EntryState;
24 use crate::EntryState;
25 use crate::FastHashMap;
25 use crate::FastHashMap;
26 use crate::PatternFileWarning;
26 use crate::PatternFileWarning;
27 use crate::StatusError;
27 use crate::StatusError;
28 use crate::StatusOptions;
28 use crate::StatusOptions;
29
29
30 /// Append to an existing data file if the amount of unreachable data (not used
30 /// Append to an existing data file if the amount of unreachable data (not used
31 /// anymore) is less than this fraction of the total amount of existing data.
31 /// anymore) is less than this fraction of the total amount of existing data.
32 const ACCEPTABLE_UNREACHABLE_BYTES_RATIO: f32 = 0.5;
32 const ACCEPTABLE_UNREACHABLE_BYTES_RATIO: f32 = 0.5;
33
33
34 pub struct DirstateMap<'on_disk> {
34 pub struct DirstateMap<'on_disk> {
35 /// Contents of the `.hg/dirstate` file
35 /// Contents of the `.hg/dirstate` file
36 pub(super) on_disk: &'on_disk [u8],
36 pub(super) on_disk: &'on_disk [u8],
37
37
38 pub(super) root: ChildNodes<'on_disk>,
38 pub(super) root: ChildNodes<'on_disk>,
39
39
40 /// Number of nodes anywhere in the tree that have `.entry.is_some()`.
40 /// Number of nodes anywhere in the tree that have `.entry.is_some()`.
41 pub(super) nodes_with_entry_count: u32,
41 pub(super) nodes_with_entry_count: u32,
42
42
43 /// Number of nodes anywhere in the tree that have
43 /// Number of nodes anywhere in the tree that have
44 /// `.copy_source.is_some()`.
44 /// `.copy_source.is_some()`.
45 pub(super) nodes_with_copy_source_count: u32,
45 pub(super) nodes_with_copy_source_count: u32,
46
46
47 /// See on_disk::Header
47 /// See on_disk::Header
48 pub(super) ignore_patterns_hash: on_disk::IgnorePatternsHash,
48 pub(super) ignore_patterns_hash: on_disk::IgnorePatternsHash,
49
49
50 /// How many bytes of `on_disk` are not used anymore
50 /// How many bytes of `on_disk` are not used anymore
51 pub(super) unreachable_bytes: u32,
51 pub(super) unreachable_bytes: u32,
52 }
52 }
53
53
54 /// Using a plain `HgPathBuf` of the full path from the repository root as a
54 /// Using a plain `HgPathBuf` of the full path from the repository root as a
55 /// map key would also work: all paths in a given map have the same parent
55 /// map key would also work: all paths in a given map have the same parent
56 /// path, so comparing full paths gives the same result as comparing base
56 /// path, so comparing full paths gives the same result as comparing base
57 /// names. However `HashMap` would waste time always re-hashing the same
57 /// names. However `HashMap` would waste time always re-hashing the same
58 /// string prefix.
58 /// string prefix.
59 pub(super) type NodeKey<'on_disk> = WithBasename<Cow<'on_disk, HgPath>>;
59 pub(super) type NodeKey<'on_disk> = WithBasename<Cow<'on_disk, HgPath>>;
60
60
61 /// Similar to `&'tree Cow<'on_disk, HgPath>`, but can also be returned
61 /// Similar to `&'tree Cow<'on_disk, HgPath>`, but can also be returned
62 /// for on-disk nodes that don’t actually have a `Cow` to borrow.
62 /// for on-disk nodes that don’t actually have a `Cow` to borrow.
63 pub(super) enum BorrowedPath<'tree, 'on_disk> {
63 pub(super) enum BorrowedPath<'tree, 'on_disk> {
64 InMemory(&'tree HgPathBuf),
64 InMemory(&'tree HgPathBuf),
65 OnDisk(&'on_disk HgPath),
65 OnDisk(&'on_disk HgPath),
66 }
66 }
67
67
68 pub(super) enum ChildNodes<'on_disk> {
68 pub(super) enum ChildNodes<'on_disk> {
69 InMemory(FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
69 InMemory(FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
70 OnDisk(&'on_disk [on_disk::Node]),
70 OnDisk(&'on_disk [on_disk::Node]),
71 }
71 }
72
72
73 pub(super) enum ChildNodesRef<'tree, 'on_disk> {
73 pub(super) enum ChildNodesRef<'tree, 'on_disk> {
74 InMemory(&'tree FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
74 InMemory(&'tree FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>),
75 OnDisk(&'on_disk [on_disk::Node]),
75 OnDisk(&'on_disk [on_disk::Node]),
76 }
76 }
77
77
78 pub(super) enum NodeRef<'tree, 'on_disk> {
78 pub(super) enum NodeRef<'tree, 'on_disk> {
79 InMemory(&'tree NodeKey<'on_disk>, &'tree Node<'on_disk>),
79 InMemory(&'tree NodeKey<'on_disk>, &'tree Node<'on_disk>),
80 OnDisk(&'on_disk on_disk::Node),
80 OnDisk(&'on_disk on_disk::Node),
81 }
81 }
82
82
83 impl<'tree, 'on_disk> BorrowedPath<'tree, 'on_disk> {
83 impl<'tree, 'on_disk> BorrowedPath<'tree, 'on_disk> {
84 pub fn detach_from_tree(&self) -> Cow<'on_disk, HgPath> {
84 pub fn detach_from_tree(&self) -> Cow<'on_disk, HgPath> {
85 match *self {
85 match *self {
86 BorrowedPath::InMemory(in_memory) => Cow::Owned(in_memory.clone()),
86 BorrowedPath::InMemory(in_memory) => Cow::Owned(in_memory.clone()),
87 BorrowedPath::OnDisk(on_disk) => Cow::Borrowed(on_disk),
87 BorrowedPath::OnDisk(on_disk) => Cow::Borrowed(on_disk),
88 }
88 }
89 }
89 }
90 }
90 }
91
91
92 impl<'tree, 'on_disk> std::ops::Deref for BorrowedPath<'tree, 'on_disk> {
92 impl<'tree, 'on_disk> std::ops::Deref for BorrowedPath<'tree, 'on_disk> {
93 type Target = HgPath;
93 type Target = HgPath;
94
94
95 fn deref(&self) -> &HgPath {
95 fn deref(&self) -> &HgPath {
96 match *self {
96 match *self {
97 BorrowedPath::InMemory(in_memory) => in_memory,
97 BorrowedPath::InMemory(in_memory) => in_memory,
98 BorrowedPath::OnDisk(on_disk) => on_disk,
98 BorrowedPath::OnDisk(on_disk) => on_disk,
99 }
99 }
100 }
100 }
101 }
101 }
102
102
103 impl Default for ChildNodes<'_> {
103 impl Default for ChildNodes<'_> {
104 fn default() -> Self {
104 fn default() -> Self {
105 ChildNodes::InMemory(Default::default())
105 ChildNodes::InMemory(Default::default())
106 }
106 }
107 }
107 }
108
108
109 impl<'on_disk> ChildNodes<'on_disk> {
109 impl<'on_disk> ChildNodes<'on_disk> {
110 pub(super) fn as_ref<'tree>(
110 pub(super) fn as_ref<'tree>(
111 &'tree self,
111 &'tree self,
112 ) -> ChildNodesRef<'tree, 'on_disk> {
112 ) -> ChildNodesRef<'tree, 'on_disk> {
113 match self {
113 match self {
114 ChildNodes::InMemory(nodes) => ChildNodesRef::InMemory(nodes),
114 ChildNodes::InMemory(nodes) => ChildNodesRef::InMemory(nodes),
115 ChildNodes::OnDisk(nodes) => ChildNodesRef::OnDisk(nodes),
115 ChildNodes::OnDisk(nodes) => ChildNodesRef::OnDisk(nodes),
116 }
116 }
117 }
117 }
118
118
119 pub(super) fn is_empty(&self) -> bool {
119 pub(super) fn is_empty(&self) -> bool {
120 match self {
120 match self {
121 ChildNodes::InMemory(nodes) => nodes.is_empty(),
121 ChildNodes::InMemory(nodes) => nodes.is_empty(),
122 ChildNodes::OnDisk(nodes) => nodes.is_empty(),
122 ChildNodes::OnDisk(nodes) => nodes.is_empty(),
123 }
123 }
124 }
124 }
125
125
126 fn make_mut(
126 fn make_mut(
127 &mut self,
127 &mut self,
128 on_disk: &'on_disk [u8],
128 on_disk: &'on_disk [u8],
129 unreachable_bytes: &mut u32,
129 unreachable_bytes: &mut u32,
130 ) -> Result<
130 ) -> Result<
131 &mut FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>,
131 &mut FastHashMap<NodeKey<'on_disk>, Node<'on_disk>>,
132 DirstateV2ParseError,
132 DirstateV2ParseError,
133 > {
133 > {
134 match self {
134 match self {
135 ChildNodes::InMemory(nodes) => Ok(nodes),
135 ChildNodes::InMemory(nodes) => Ok(nodes),
136 ChildNodes::OnDisk(nodes) => {
136 ChildNodes::OnDisk(nodes) => {
137 *unreachable_bytes +=
137 *unreachable_bytes +=
138 std::mem::size_of_val::<[on_disk::Node]>(nodes) as u32;
138 std::mem::size_of_val::<[on_disk::Node]>(nodes) as u32;
139 let nodes = nodes
139 let nodes = nodes
140 .iter()
140 .iter()
141 .map(|node| {
141 .map(|node| {
142 Ok((
142 Ok((
143 node.path(on_disk)?,
143 node.path(on_disk)?,
144 node.to_in_memory_node(on_disk)?,
144 node.to_in_memory_node(on_disk)?,
145 ))
145 ))
146 })
146 })
147 .collect::<Result<_, _>>()?;
147 .collect::<Result<_, _>>()?;
148 *self = ChildNodes::InMemory(nodes);
148 *self = ChildNodes::InMemory(nodes);
149 match self {
149 match self {
150 ChildNodes::InMemory(nodes) => Ok(nodes),
150 ChildNodes::InMemory(nodes) => Ok(nodes),
151 ChildNodes::OnDisk(_) => unreachable!(),
151 ChildNodes::OnDisk(_) => unreachable!(),
152 }
152 }
153 }
153 }
154 }
154 }
155 }
155 }
156 }
156 }
157
157
158 impl<'tree, 'on_disk> ChildNodesRef<'tree, 'on_disk> {
158 impl<'tree, 'on_disk> ChildNodesRef<'tree, 'on_disk> {
159 pub(super) fn get(
159 pub(super) fn get(
160 &self,
160 &self,
161 base_name: &HgPath,
161 base_name: &HgPath,
162 on_disk: &'on_disk [u8],
162 on_disk: &'on_disk [u8],
163 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
163 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
164 match self {
164 match self {
165 ChildNodesRef::InMemory(nodes) => Ok(nodes
165 ChildNodesRef::InMemory(nodes) => Ok(nodes
166 .get_key_value(base_name)
166 .get_key_value(base_name)
167 .map(|(k, v)| NodeRef::InMemory(k, v))),
167 .map(|(k, v)| NodeRef::InMemory(k, v))),
168 ChildNodesRef::OnDisk(nodes) => {
168 ChildNodesRef::OnDisk(nodes) => {
169 let mut parse_result = Ok(());
169 let mut parse_result = Ok(());
170 let search_result = nodes.binary_search_by(|node| {
170 let search_result = nodes.binary_search_by(|node| {
171 match node.base_name(on_disk) {
171 match node.base_name(on_disk) {
172 Ok(node_base_name) => node_base_name.cmp(base_name),
172 Ok(node_base_name) => node_base_name.cmp(base_name),
173 Err(e) => {
173 Err(e) => {
174 parse_result = Err(e);
174 parse_result = Err(e);
175 // Dummy comparison result, `search_result` won’t
175 // Dummy comparison result, `search_result` won’t
176 // be used since `parse_result` is an error
176 // be used since `parse_result` is an error
177 std::cmp::Ordering::Equal
177 std::cmp::Ordering::Equal
178 }
178 }
179 }
179 }
180 });
180 });
181 parse_result.map(|()| {
181 parse_result.map(|()| {
182 search_result.ok().map(|i| NodeRef::OnDisk(&nodes[i]))
182 search_result.ok().map(|i| NodeRef::OnDisk(&nodes[i]))
183 })
183 })
184 }
184 }
185 }
185 }
186 }
186 }
187
187
188 /// Iterate in undefined order
188 /// Iterate in undefined order
189 pub(super) fn iter(
189 pub(super) fn iter(
190 &self,
190 &self,
191 ) -> impl Iterator<Item = NodeRef<'tree, 'on_disk>> {
191 ) -> impl Iterator<Item = NodeRef<'tree, 'on_disk>> {
192 match self {
192 match self {
193 ChildNodesRef::InMemory(nodes) => itertools::Either::Left(
193 ChildNodesRef::InMemory(nodes) => itertools::Either::Left(
194 nodes.iter().map(|(k, v)| NodeRef::InMemory(k, v)),
194 nodes.iter().map(|(k, v)| NodeRef::InMemory(k, v)),
195 ),
195 ),
196 ChildNodesRef::OnDisk(nodes) => {
196 ChildNodesRef::OnDisk(nodes) => {
197 itertools::Either::Right(nodes.iter().map(NodeRef::OnDisk))
197 itertools::Either::Right(nodes.iter().map(NodeRef::OnDisk))
198 }
198 }
199 }
199 }
200 }
200 }
201
201
202 /// Iterate in parallel in undefined order
202 /// Iterate in parallel in undefined order
203 pub(super) fn par_iter(
203 pub(super) fn par_iter(
204 &self,
204 &self,
205 ) -> impl rayon::iter::ParallelIterator<Item = NodeRef<'tree, 'on_disk>>
205 ) -> impl rayon::iter::ParallelIterator<Item = NodeRef<'tree, 'on_disk>>
206 {
206 {
207 use rayon::prelude::*;
207 use rayon::prelude::*;
208 match self {
208 match self {
209 ChildNodesRef::InMemory(nodes) => rayon::iter::Either::Left(
209 ChildNodesRef::InMemory(nodes) => rayon::iter::Either::Left(
210 nodes.par_iter().map(|(k, v)| NodeRef::InMemory(k, v)),
210 nodes.par_iter().map(|(k, v)| NodeRef::InMemory(k, v)),
211 ),
211 ),
212 ChildNodesRef::OnDisk(nodes) => rayon::iter::Either::Right(
212 ChildNodesRef::OnDisk(nodes) => rayon::iter::Either::Right(
213 nodes.par_iter().map(NodeRef::OnDisk),
213 nodes.par_iter().map(NodeRef::OnDisk),
214 ),
214 ),
215 }
215 }
216 }
216 }
217
217
218 pub(super) fn sorted(&self) -> Vec<NodeRef<'tree, 'on_disk>> {
218 pub(super) fn sorted(&self) -> Vec<NodeRef<'tree, 'on_disk>> {
219 match self {
219 match self {
220 ChildNodesRef::InMemory(nodes) => {
220 ChildNodesRef::InMemory(nodes) => {
221 let mut vec: Vec<_> = nodes
221 let mut vec: Vec<_> = nodes
222 .iter()
222 .iter()
223 .map(|(k, v)| NodeRef::InMemory(k, v))
223 .map(|(k, v)| NodeRef::InMemory(k, v))
224 .collect();
224 .collect();
225 fn sort_key<'a>(node: &'a NodeRef) -> &'a HgPath {
225 fn sort_key<'a>(node: &'a NodeRef) -> &'a HgPath {
226 match node {
226 match node {
227 NodeRef::InMemory(path, _node) => path.base_name(),
227 NodeRef::InMemory(path, _node) => path.base_name(),
228 NodeRef::OnDisk(_) => unreachable!(),
228 NodeRef::OnDisk(_) => unreachable!(),
229 }
229 }
230 }
230 }
231 // `sort_unstable_by_key` doesn’t allow keys borrowing from the
231 // `sort_unstable_by_key` doesn’t allow keys borrowing from the
232 // value: https://github.com/rust-lang/rust/issues/34162
232 // value: https://github.com/rust-lang/rust/issues/34162
233 vec.sort_unstable_by(|a, b| sort_key(a).cmp(sort_key(b)));
233 vec.sort_unstable_by(|a, b| sort_key(a).cmp(sort_key(b)));
234 vec
234 vec
235 }
235 }
236 ChildNodesRef::OnDisk(nodes) => {
236 ChildNodesRef::OnDisk(nodes) => {
237 // Nodes on disk are already sorted
237 // Nodes on disk are already sorted
238 nodes.iter().map(NodeRef::OnDisk).collect()
238 nodes.iter().map(NodeRef::OnDisk).collect()
239 }
239 }
240 }
240 }
241 }
241 }
242 }
242 }
243
243
244 impl<'tree, 'on_disk> NodeRef<'tree, 'on_disk> {
244 impl<'tree, 'on_disk> NodeRef<'tree, 'on_disk> {
245 pub(super) fn full_path(
245 pub(super) fn full_path(
246 &self,
246 &self,
247 on_disk: &'on_disk [u8],
247 on_disk: &'on_disk [u8],
248 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
248 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
249 match self {
249 match self {
250 NodeRef::InMemory(path, _node) => Ok(path.full_path()),
250 NodeRef::InMemory(path, _node) => Ok(path.full_path()),
251 NodeRef::OnDisk(node) => node.full_path(on_disk),
251 NodeRef::OnDisk(node) => node.full_path(on_disk),
252 }
252 }
253 }
253 }
254
254
255 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
255 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
256 /// HgPath>` detached from `'tree`
256 /// HgPath>` detached from `'tree`
257 pub(super) fn full_path_borrowed(
257 pub(super) fn full_path_borrowed(
258 &self,
258 &self,
259 on_disk: &'on_disk [u8],
259 on_disk: &'on_disk [u8],
260 ) -> Result<BorrowedPath<'tree, 'on_disk>, DirstateV2ParseError> {
260 ) -> Result<BorrowedPath<'tree, 'on_disk>, DirstateV2ParseError> {
261 match self {
261 match self {
262 NodeRef::InMemory(path, _node) => match path.full_path() {
262 NodeRef::InMemory(path, _node) => match path.full_path() {
263 Cow::Borrowed(on_disk) => Ok(BorrowedPath::OnDisk(on_disk)),
263 Cow::Borrowed(on_disk) => Ok(BorrowedPath::OnDisk(on_disk)),
264 Cow::Owned(in_memory) => Ok(BorrowedPath::InMemory(in_memory)),
264 Cow::Owned(in_memory) => Ok(BorrowedPath::InMemory(in_memory)),
265 },
265 },
266 NodeRef::OnDisk(node) => {
266 NodeRef::OnDisk(node) => {
267 Ok(BorrowedPath::OnDisk(node.full_path(on_disk)?))
267 Ok(BorrowedPath::OnDisk(node.full_path(on_disk)?))
268 }
268 }
269 }
269 }
270 }
270 }
271
271
272 pub(super) fn base_name(
272 pub(super) fn base_name(
273 &self,
273 &self,
274 on_disk: &'on_disk [u8],
274 on_disk: &'on_disk [u8],
275 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
275 ) -> Result<&'tree HgPath, DirstateV2ParseError> {
276 match self {
276 match self {
277 NodeRef::InMemory(path, _node) => Ok(path.base_name()),
277 NodeRef::InMemory(path, _node) => Ok(path.base_name()),
278 NodeRef::OnDisk(node) => node.base_name(on_disk),
278 NodeRef::OnDisk(node) => node.base_name(on_disk),
279 }
279 }
280 }
280 }
281
281
282 pub(super) fn children(
282 pub(super) fn children(
283 &self,
283 &self,
284 on_disk: &'on_disk [u8],
284 on_disk: &'on_disk [u8],
285 ) -> Result<ChildNodesRef<'tree, 'on_disk>, DirstateV2ParseError> {
285 ) -> Result<ChildNodesRef<'tree, 'on_disk>, DirstateV2ParseError> {
286 match self {
286 match self {
287 NodeRef::InMemory(_path, node) => Ok(node.children.as_ref()),
287 NodeRef::InMemory(_path, node) => Ok(node.children.as_ref()),
288 NodeRef::OnDisk(node) => {
288 NodeRef::OnDisk(node) => {
289 Ok(ChildNodesRef::OnDisk(node.children(on_disk)?))
289 Ok(ChildNodesRef::OnDisk(node.children(on_disk)?))
290 }
290 }
291 }
291 }
292 }
292 }
293
293
294 pub(super) fn has_copy_source(&self) -> bool {
294 pub(super) fn has_copy_source(&self) -> bool {
295 match self {
295 match self {
296 NodeRef::InMemory(_path, node) => node.copy_source.is_some(),
296 NodeRef::InMemory(_path, node) => node.copy_source.is_some(),
297 NodeRef::OnDisk(node) => node.has_copy_source(),
297 NodeRef::OnDisk(node) => node.has_copy_source(),
298 }
298 }
299 }
299 }
300
300
301 pub(super) fn copy_source(
301 pub(super) fn copy_source(
302 &self,
302 &self,
303 on_disk: &'on_disk [u8],
303 on_disk: &'on_disk [u8],
304 ) -> Result<Option<&'tree HgPath>, DirstateV2ParseError> {
304 ) -> Result<Option<&'tree HgPath>, DirstateV2ParseError> {
305 match self {
305 match self {
306 NodeRef::InMemory(_path, node) => {
306 NodeRef::InMemory(_path, node) => {
307 Ok(node.copy_source.as_ref().map(|s| &**s))
307 Ok(node.copy_source.as_ref().map(|s| &**s))
308 }
308 }
309 NodeRef::OnDisk(node) => node.copy_source(on_disk),
309 NodeRef::OnDisk(node) => node.copy_source(on_disk),
310 }
310 }
311 }
311 }
312 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
312 /// Returns a `BorrowedPath`, which can be turned into a `Cow<'on_disk,
313 /// HgPath>` detached from `'tree`
313 /// HgPath>` detached from `'tree`
314 pub(super) fn copy_source_borrowed(
314 pub(super) fn copy_source_borrowed(
315 &self,
315 &self,
316 on_disk: &'on_disk [u8],
316 on_disk: &'on_disk [u8],
317 ) -> Result<Option<BorrowedPath<'tree, 'on_disk>>, DirstateV2ParseError>
317 ) -> Result<Option<BorrowedPath<'tree, 'on_disk>>, DirstateV2ParseError>
318 {
318 {
319 Ok(match self {
319 Ok(match self {
320 NodeRef::InMemory(_path, node) => {
320 NodeRef::InMemory(_path, node) => {
321 node.copy_source.as_ref().map(|source| match source {
321 node.copy_source.as_ref().map(|source| match source {
322 Cow::Borrowed(on_disk) => BorrowedPath::OnDisk(on_disk),
322 Cow::Borrowed(on_disk) => BorrowedPath::OnDisk(on_disk),
323 Cow::Owned(in_memory) => BorrowedPath::InMemory(in_memory),
323 Cow::Owned(in_memory) => BorrowedPath::InMemory(in_memory),
324 })
324 })
325 }
325 }
326 NodeRef::OnDisk(node) => node
326 NodeRef::OnDisk(node) => node
327 .copy_source(on_disk)?
327 .copy_source(on_disk)?
328 .map(|source| BorrowedPath::OnDisk(source)),
328 .map(|source| BorrowedPath::OnDisk(source)),
329 })
329 })
330 }
330 }
331
331
332 pub(super) fn entry(
332 pub(super) fn entry(
333 &self,
333 &self,
334 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
334 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
335 match self {
335 match self {
336 NodeRef::InMemory(_path, node) => {
336 NodeRef::InMemory(_path, node) => {
337 Ok(node.data.as_entry().copied())
337 Ok(node.data.as_entry().copied())
338 }
338 }
339 NodeRef::OnDisk(node) => node.entry(),
339 NodeRef::OnDisk(node) => node.entry(),
340 }
340 }
341 }
341 }
342
342
343 pub(super) fn state(
343 pub(super) fn state(
344 &self,
344 &self,
345 ) -> Result<Option<EntryState>, DirstateV2ParseError> {
345 ) -> Result<Option<EntryState>, DirstateV2ParseError> {
346 Ok(self.entry()?.map(|e| e.state()))
346 Ok(self.entry()?.map(|e| e.state()))
347 }
347 }
348
348
349 pub(super) fn cached_directory_mtime(
349 pub(super) fn cached_directory_mtime(
350 &self,
350 &self,
351 ) -> Result<Option<TruncatedTimestamp>, DirstateV2ParseError> {
351 ) -> Result<Option<TruncatedTimestamp>, DirstateV2ParseError> {
352 match self {
352 match self {
353 NodeRef::InMemory(_path, node) => Ok(match node.data {
353 NodeRef::InMemory(_path, node) => Ok(match node.data {
354 NodeData::CachedDirectory { mtime } => Some(mtime),
354 NodeData::CachedDirectory { mtime } => Some(mtime),
355 _ => None,
355 _ => None,
356 }),
356 }),
357 NodeRef::OnDisk(node) => node.cached_directory_mtime(),
357 NodeRef::OnDisk(node) => node.cached_directory_mtime(),
358 }
358 }
359 }
359 }
360
360
361 pub(super) fn descendants_with_entry_count(&self) -> u32 {
361 pub(super) fn descendants_with_entry_count(&self) -> u32 {
362 match self {
362 match self {
363 NodeRef::InMemory(_path, node) => {
363 NodeRef::InMemory(_path, node) => {
364 node.descendants_with_entry_count
364 node.descendants_with_entry_count
365 }
365 }
366 NodeRef::OnDisk(node) => node.descendants_with_entry_count.get(),
366 NodeRef::OnDisk(node) => node.descendants_with_entry_count.get(),
367 }
367 }
368 }
368 }
369
369
370 pub(super) fn tracked_descendants_count(&self) -> u32 {
370 pub(super) fn tracked_descendants_count(&self) -> u32 {
371 match self {
371 match self {
372 NodeRef::InMemory(_path, node) => node.tracked_descendants_count,
372 NodeRef::InMemory(_path, node) => node.tracked_descendants_count,
373 NodeRef::OnDisk(node) => node.tracked_descendants_count.get(),
373 NodeRef::OnDisk(node) => node.tracked_descendants_count.get(),
374 }
374 }
375 }
375 }
376 }
376 }
377
377
378 /// Represents a file or a directory
378 /// Represents a file or a directory
379 #[derive(Default)]
379 #[derive(Default)]
380 pub(super) struct Node<'on_disk> {
380 pub(super) struct Node<'on_disk> {
381 pub(super) data: NodeData,
381 pub(super) data: NodeData,
382
382
383 pub(super) copy_source: Option<Cow<'on_disk, HgPath>>,
383 pub(super) copy_source: Option<Cow<'on_disk, HgPath>>,
384
384
385 pub(super) children: ChildNodes<'on_disk>,
385 pub(super) children: ChildNodes<'on_disk>,
386
386
387 /// How many (non-inclusive) descendants of this node have an entry.
387 /// How many (non-inclusive) descendants of this node have an entry.
388 pub(super) descendants_with_entry_count: u32,
388 pub(super) descendants_with_entry_count: u32,
389
389
390 /// How many (non-inclusive) descendants of this node have an entry whose
390 /// How many (non-inclusive) descendants of this node have an entry whose
391 /// state is "tracked".
391 /// state is "tracked".
392 pub(super) tracked_descendants_count: u32,
392 pub(super) tracked_descendants_count: u32,
393 }
393 }
394
394
395 pub(super) enum NodeData {
395 pub(super) enum NodeData {
396 Entry(DirstateEntry),
396 Entry(DirstateEntry),
397 CachedDirectory { mtime: TruncatedTimestamp },
397 CachedDirectory { mtime: TruncatedTimestamp },
398 None,
398 None,
399 }
399 }
400
400
401 impl Default for NodeData {
401 impl Default for NodeData {
402 fn default() -> Self {
402 fn default() -> Self {
403 NodeData::None
403 NodeData::None
404 }
404 }
405 }
405 }
406
406
407 impl NodeData {
407 impl NodeData {
408 fn has_entry(&self) -> bool {
408 fn has_entry(&self) -> bool {
409 match self {
409 match self {
410 NodeData::Entry(_) => true,
410 NodeData::Entry(_) => true,
411 _ => false,
411 _ => false,
412 }
412 }
413 }
413 }
414
414
415 fn as_entry(&self) -> Option<&DirstateEntry> {
415 fn as_entry(&self) -> Option<&DirstateEntry> {
416 match self {
416 match self {
417 NodeData::Entry(entry) => Some(entry),
417 NodeData::Entry(entry) => Some(entry),
418 _ => None,
418 _ => None,
419 }
419 }
420 }
420 }
421 }
421 }
422
422
423 impl<'on_disk> DirstateMap<'on_disk> {
423 impl<'on_disk> DirstateMap<'on_disk> {
424 pub(super) fn empty(on_disk: &'on_disk [u8]) -> Self {
424 pub(super) fn empty(on_disk: &'on_disk [u8]) -> Self {
425 Self {
425 Self {
426 on_disk,
426 on_disk,
427 root: ChildNodes::default(),
427 root: ChildNodes::default(),
428 nodes_with_entry_count: 0,
428 nodes_with_entry_count: 0,
429 nodes_with_copy_source_count: 0,
429 nodes_with_copy_source_count: 0,
430 ignore_patterns_hash: [0; on_disk::IGNORE_PATTERNS_HASH_LEN],
430 ignore_patterns_hash: [0; on_disk::IGNORE_PATTERNS_HASH_LEN],
431 unreachable_bytes: 0,
431 unreachable_bytes: 0,
432 }
432 }
433 }
433 }
434
434
435 #[timed]
435 #[timed]
436 pub fn new_v2(
436 pub fn new_v2(
437 on_disk: &'on_disk [u8],
437 on_disk: &'on_disk [u8],
438 data_size: usize,
438 data_size: usize,
439 metadata: &[u8],
439 metadata: &[u8],
440 ) -> Result<Self, DirstateError> {
440 ) -> Result<Self, DirstateError> {
441 if let Some(data) = on_disk.get(..data_size) {
441 if let Some(data) = on_disk.get(..data_size) {
442 Ok(on_disk::read(data, metadata)?)
442 Ok(on_disk::read(data, metadata)?)
443 } else {
443 } else {
444 Err(DirstateV2ParseError.into())
444 Err(DirstateV2ParseError.into())
445 }
445 }
446 }
446 }
447
447
448 #[timed]
448 #[timed]
449 pub fn new_v1(
449 pub fn new_v1(
450 on_disk: &'on_disk [u8],
450 on_disk: &'on_disk [u8],
451 ) -> Result<(Self, Option<DirstateParents>), DirstateError> {
451 ) -> Result<(Self, Option<DirstateParents>), DirstateError> {
452 let mut map = Self::empty(on_disk);
452 let mut map = Self::empty(on_disk);
453 if map.on_disk.is_empty() {
453 if map.on_disk.is_empty() {
454 return Ok((map, None));
454 return Ok((map, None));
455 }
455 }
456
456
457 let parents = parse_dirstate_entries(
457 let parents = parse_dirstate_entries(
458 map.on_disk,
458 map.on_disk,
459 |path, entry, copy_source| {
459 |path, entry, copy_source| {
460 let tracked = entry.state().is_tracked();
460 let tracked = entry.state().is_tracked();
461 let node = Self::get_or_insert_node(
461 let node = Self::get_or_insert_node(
462 map.on_disk,
462 map.on_disk,
463 &mut map.unreachable_bytes,
463 &mut map.unreachable_bytes,
464 &mut map.root,
464 &mut map.root,
465 path,
465 path,
466 WithBasename::to_cow_borrowed,
466 WithBasename::to_cow_borrowed,
467 |ancestor| {
467 |ancestor| {
468 if tracked {
468 if tracked {
469 ancestor.tracked_descendants_count += 1
469 ancestor.tracked_descendants_count += 1
470 }
470 }
471 ancestor.descendants_with_entry_count += 1
471 ancestor.descendants_with_entry_count += 1
472 },
472 },
473 )?;
473 )?;
474 assert!(
474 assert!(
475 !node.data.has_entry(),
475 !node.data.has_entry(),
476 "duplicate dirstate entry in read"
476 "duplicate dirstate entry in read"
477 );
477 );
478 assert!(
478 assert!(
479 node.copy_source.is_none(),
479 node.copy_source.is_none(),
480 "duplicate dirstate entry in read"
480 "duplicate dirstate entry in read"
481 );
481 );
482 node.data = NodeData::Entry(*entry);
482 node.data = NodeData::Entry(*entry);
483 node.copy_source = copy_source.map(Cow::Borrowed);
483 node.copy_source = copy_source.map(Cow::Borrowed);
484 map.nodes_with_entry_count += 1;
484 map.nodes_with_entry_count += 1;
485 if copy_source.is_some() {
485 if copy_source.is_some() {
486 map.nodes_with_copy_source_count += 1
486 map.nodes_with_copy_source_count += 1
487 }
487 }
488 Ok(())
488 Ok(())
489 },
489 },
490 )?;
490 )?;
491 let parents = Some(parents.clone());
491 let parents = Some(parents.clone());
492
492
493 Ok((map, parents))
493 Ok((map, parents))
494 }
494 }
495
495
496 /// Assuming dirstate-v2 format, returns whether the next write should
496 /// Assuming dirstate-v2 format, returns whether the next write should
497 /// append to the existing data file that contains `self.on_disk` (true),
497 /// append to the existing data file that contains `self.on_disk` (true),
498 /// or create a new data file from scratch (false).
498 /// or create a new data file from scratch (false).
499 pub(super) fn write_should_append(&self) -> bool {
499 pub(super) fn write_should_append(&self) -> bool {
500 let ratio = self.unreachable_bytes as f32 / self.on_disk.len() as f32;
500 let ratio = self.unreachable_bytes as f32 / self.on_disk.len() as f32;
501 ratio < ACCEPTABLE_UNREACHABLE_BYTES_RATIO
501 ratio < ACCEPTABLE_UNREACHABLE_BYTES_RATIO
502 }
502 }
503
503
504 fn get_node<'tree>(
504 fn get_node<'tree>(
505 &'tree self,
505 &'tree self,
506 path: &HgPath,
506 path: &HgPath,
507 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
507 ) -> Result<Option<NodeRef<'tree, 'on_disk>>, DirstateV2ParseError> {
508 let mut children = self.root.as_ref();
508 let mut children = self.root.as_ref();
509 let mut components = path.components();
509 let mut components = path.components();
510 let mut component =
510 let mut component =
511 components.next().expect("expected at least one components");
511 components.next().expect("expected at least one components");
512 loop {
512 loop {
513 if let Some(child) = children.get(component, self.on_disk)? {
513 if let Some(child) = children.get(component, self.on_disk)? {
514 if let Some(next_component) = components.next() {
514 if let Some(next_component) = components.next() {
515 component = next_component;
515 component = next_component;
516 children = child.children(self.on_disk)?;
516 children = child.children(self.on_disk)?;
517 } else {
517 } else {
518 return Ok(Some(child));
518 return Ok(Some(child));
519 }
519 }
520 } else {
520 } else {
521 return Ok(None);
521 return Ok(None);
522 }
522 }
523 }
523 }
524 }
524 }
525
525
526 /// Returns a mutable reference to the node at `path` if it exists
526 /// Returns a mutable reference to the node at `path` if it exists
527 ///
527 ///
528 /// This takes `root` instead of `&mut self` so that callers can mutate
528 /// This takes `root` instead of `&mut self` so that callers can mutate
529 /// other fields while the returned borrow is still valid
529 /// other fields while the returned borrow is still valid
530 fn get_node_mut<'tree>(
530 fn get_node_mut<'tree>(
531 on_disk: &'on_disk [u8],
531 on_disk: &'on_disk [u8],
532 unreachable_bytes: &mut u32,
532 unreachable_bytes: &mut u32,
533 root: &'tree mut ChildNodes<'on_disk>,
533 root: &'tree mut ChildNodes<'on_disk>,
534 path: &HgPath,
534 path: &HgPath,
535 ) -> Result<Option<&'tree mut Node<'on_disk>>, DirstateV2ParseError> {
535 ) -> Result<Option<&'tree mut Node<'on_disk>>, DirstateV2ParseError> {
536 let mut children = root;
536 let mut children = root;
537 let mut components = path.components();
537 let mut components = path.components();
538 let mut component =
538 let mut component =
539 components.next().expect("expected at least one components");
539 components.next().expect("expected at least one components");
540 loop {
540 loop {
541 if let Some(child) = children
541 if let Some(child) = children
542 .make_mut(on_disk, unreachable_bytes)?
542 .make_mut(on_disk, unreachable_bytes)?
543 .get_mut(component)
543 .get_mut(component)
544 {
544 {
545 if let Some(next_component) = components.next() {
545 if let Some(next_component) = components.next() {
546 component = next_component;
546 component = next_component;
547 children = &mut child.children;
547 children = &mut child.children;
548 } else {
548 } else {
549 return Ok(Some(child));
549 return Ok(Some(child));
550 }
550 }
551 } else {
551 } else {
552 return Ok(None);
552 return Ok(None);
553 }
553 }
554 }
554 }
555 }
555 }
556
556
557 pub(super) fn get_or_insert<'tree, 'path>(
557 pub(super) fn get_or_insert<'tree, 'path>(
558 &'tree mut self,
558 &'tree mut self,
559 path: &HgPath,
559 path: &HgPath,
560 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
560 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
561 Self::get_or_insert_node(
561 Self::get_or_insert_node(
562 self.on_disk,
562 self.on_disk,
563 &mut self.unreachable_bytes,
563 &mut self.unreachable_bytes,
564 &mut self.root,
564 &mut self.root,
565 path,
565 path,
566 WithBasename::to_cow_owned,
566 WithBasename::to_cow_owned,
567 |_| {},
567 |_| {},
568 )
568 )
569 }
569 }
570
570
571 fn get_or_insert_node<'tree, 'path>(
571 fn get_or_insert_node<'tree, 'path>(
572 on_disk: &'on_disk [u8],
572 on_disk: &'on_disk [u8],
573 unreachable_bytes: &mut u32,
573 unreachable_bytes: &mut u32,
574 root: &'tree mut ChildNodes<'on_disk>,
574 root: &'tree mut ChildNodes<'on_disk>,
575 path: &'path HgPath,
575 path: &'path HgPath,
576 to_cow: impl Fn(
576 to_cow: impl Fn(
577 WithBasename<&'path HgPath>,
577 WithBasename<&'path HgPath>,
578 ) -> WithBasename<Cow<'on_disk, HgPath>>,
578 ) -> WithBasename<Cow<'on_disk, HgPath>>,
579 mut each_ancestor: impl FnMut(&mut Node),
579 mut each_ancestor: impl FnMut(&mut Node),
580 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
580 ) -> Result<&'tree mut Node<'on_disk>, DirstateV2ParseError> {
581 let mut child_nodes = root;
581 let mut child_nodes = root;
582 let mut inclusive_ancestor_paths =
582 let mut inclusive_ancestor_paths =
583 WithBasename::inclusive_ancestors_of(path);
583 WithBasename::inclusive_ancestors_of(path);
584 let mut ancestor_path = inclusive_ancestor_paths
584 let mut ancestor_path = inclusive_ancestor_paths
585 .next()
585 .next()
586 .expect("expected at least one inclusive ancestor");
586 .expect("expected at least one inclusive ancestor");
587 loop {
587 loop {
588 // TODO: can we avoid allocating an owned key in cases where the
588 // TODO: can we avoid allocating an owned key in cases where the
589 // map already contains that key, without introducing double
589 // map already contains that key, without introducing double
590 // lookup?
590 // lookup?
591 let child_node = child_nodes
591 let child_node = child_nodes
592 .make_mut(on_disk, unreachable_bytes)?
592 .make_mut(on_disk, unreachable_bytes)?
593 .entry(to_cow(ancestor_path))
593 .entry(to_cow(ancestor_path))
594 .or_default();
594 .or_default();
595 if let Some(next) = inclusive_ancestor_paths.next() {
595 if let Some(next) = inclusive_ancestor_paths.next() {
596 each_ancestor(child_node);
596 each_ancestor(child_node);
597 ancestor_path = next;
597 ancestor_path = next;
598 child_nodes = &mut child_node.children;
598 child_nodes = &mut child_node.children;
599 } else {
599 } else {
600 return Ok(child_node);
600 return Ok(child_node);
601 }
601 }
602 }
602 }
603 }
603 }
604
604
605 fn add_or_remove_file(
605 fn add_or_remove_file(
606 &mut self,
606 &mut self,
607 path: &HgPath,
607 path: &HgPath,
608 old_state: Option<EntryState>,
608 old_state: Option<EntryState>,
609 new_entry: DirstateEntry,
609 new_entry: DirstateEntry,
610 ) -> Result<(), DirstateV2ParseError> {
610 ) -> Result<(), DirstateV2ParseError> {
611 let had_entry = old_state.is_some();
611 let had_entry = old_state.is_some();
612 let was_tracked = old_state.map_or(false, |s| s.is_tracked());
612 let was_tracked = old_state.map_or(false, |s| s.is_tracked());
613 let tracked_count_increment =
613 let tracked_count_increment =
614 match (was_tracked, new_entry.state().is_tracked()) {
614 match (was_tracked, new_entry.state().is_tracked()) {
615 (false, true) => 1,
615 (false, true) => 1,
616 (true, false) => -1,
616 (true, false) => -1,
617 _ => 0,
617 _ => 0,
618 };
618 };
619
619
620 let node = Self::get_or_insert_node(
620 let node = Self::get_or_insert_node(
621 self.on_disk,
621 self.on_disk,
622 &mut self.unreachable_bytes,
622 &mut self.unreachable_bytes,
623 &mut self.root,
623 &mut self.root,
624 path,
624 path,
625 WithBasename::to_cow_owned,
625 WithBasename::to_cow_owned,
626 |ancestor| {
626 |ancestor| {
627 if !had_entry {
627 if !had_entry {
628 ancestor.descendants_with_entry_count += 1;
628 ancestor.descendants_with_entry_count += 1;
629 }
629 }
630
630
631 // We can’t use `+= increment` because the counter is unsigned,
631 // We can’t use `+= increment` because the counter is unsigned,
632 // and we want debug builds to detect accidental underflow
632 // and we want debug builds to detect accidental underflow
633 // through zero
633 // through zero
634 match tracked_count_increment {
634 match tracked_count_increment {
635 1 => ancestor.tracked_descendants_count += 1,
635 1 => ancestor.tracked_descendants_count += 1,
636 -1 => ancestor.tracked_descendants_count -= 1,
636 -1 => ancestor.tracked_descendants_count -= 1,
637 _ => {}
637 _ => {}
638 }
638 }
639 },
639 },
640 )?;
640 )?;
641 if !had_entry {
641 if !had_entry {
642 self.nodes_with_entry_count += 1
642 self.nodes_with_entry_count += 1
643 }
643 }
644 node.data = NodeData::Entry(new_entry);
644 node.data = NodeData::Entry(new_entry);
645 Ok(())
645 Ok(())
646 }
646 }
647
647
648 fn iter_nodes<'tree>(
648 fn iter_nodes<'tree>(
649 &'tree self,
649 &'tree self,
650 ) -> impl Iterator<
650 ) -> impl Iterator<
651 Item = Result<NodeRef<'tree, 'on_disk>, DirstateV2ParseError>,
651 Item = Result<NodeRef<'tree, 'on_disk>, DirstateV2ParseError>,
652 > + 'tree {
652 > + 'tree {
653 // Depth first tree traversal.
653 // Depth first tree traversal.
654 //
654 //
655 // If we could afford internal iteration and recursion,
655 // If we could afford internal iteration and recursion,
656 // this would look like:
656 // this would look like:
657 //
657 //
658 // ```
658 // ```
659 // fn traverse_children(
659 // fn traverse_children(
660 // children: &ChildNodes,
660 // children: &ChildNodes,
661 // each: &mut impl FnMut(&Node),
661 // each: &mut impl FnMut(&Node),
662 // ) {
662 // ) {
663 // for child in children.values() {
663 // for child in children.values() {
664 // traverse_children(&child.children, each);
664 // traverse_children(&child.children, each);
665 // each(child);
665 // each(child);
666 // }
666 // }
667 // }
667 // }
668 // ```
668 // ```
669 //
669 //
670 // However we want an external iterator and therefore can’t use the
670 // However we want an external iterator and therefore can’t use the
671 // call stack. Use an explicit stack instead:
671 // call stack. Use an explicit stack instead:
672 let mut stack = Vec::new();
672 let mut stack = Vec::new();
673 let mut iter = self.root.as_ref().iter();
673 let mut iter = self.root.as_ref().iter();
674 std::iter::from_fn(move || {
674 std::iter::from_fn(move || {
675 while let Some(child_node) = iter.next() {
675 while let Some(child_node) = iter.next() {
676 let children = match child_node.children(self.on_disk) {
676 let children = match child_node.children(self.on_disk) {
677 Ok(children) => children,
677 Ok(children) => children,
678 Err(error) => return Some(Err(error)),
678 Err(error) => return Some(Err(error)),
679 };
679 };
680 // Pseudo-recursion
680 // Pseudo-recursion
681 let new_iter = children.iter();
681 let new_iter = children.iter();
682 let old_iter = std::mem::replace(&mut iter, new_iter);
682 let old_iter = std::mem::replace(&mut iter, new_iter);
683 stack.push((child_node, old_iter));
683 stack.push((child_node, old_iter));
684 }
684 }
685 // Found the end of a `children.iter()` iterator.
685 // Found the end of a `children.iter()` iterator.
686 if let Some((child_node, next_iter)) = stack.pop() {
686 if let Some((child_node, next_iter)) = stack.pop() {
687 // "Return" from pseudo-recursion by restoring state from the
687 // "Return" from pseudo-recursion by restoring state from the
688 // explicit stack
688 // explicit stack
689 iter = next_iter;
689 iter = next_iter;
690
690
691 Some(Ok(child_node))
691 Some(Ok(child_node))
692 } else {
692 } else {
693 // Reached the bottom of the stack, we’re done
693 // Reached the bottom of the stack, we’re done
694 None
694 None
695 }
695 }
696 })
696 })
697 }
697 }
698
698
699 fn count_dropped_path(unreachable_bytes: &mut u32, path: &Cow<HgPath>) {
699 fn count_dropped_path(unreachable_bytes: &mut u32, path: &Cow<HgPath>) {
700 if let Cow::Borrowed(path) = path {
700 if let Cow::Borrowed(path) = path {
701 *unreachable_bytes += path.len() as u32
701 *unreachable_bytes += path.len() as u32
702 }
702 }
703 }
703 }
704 }
704 }
705
705
706 /// Like `Iterator::filter_map`, but over a fallible iterator of `Result`s.
706 /// Like `Iterator::filter_map`, but over a fallible iterator of `Result`s.
707 ///
707 ///
708 /// The callback is only called for incoming `Ok` values. Errors are passed
708 /// The callback is only called for incoming `Ok` values. Errors are passed
709 /// through as-is. In order to let it use the `?` operator the callback is
709 /// through as-is. In order to let it use the `?` operator the callback is
710 /// expected to return a `Result` of `Option`, instead of an `Option` of
710 /// expected to return a `Result` of `Option`, instead of an `Option` of
711 /// `Result`.
711 /// `Result`.
712 fn filter_map_results<'a, I, F, A, B, E>(
712 fn filter_map_results<'a, I, F, A, B, E>(
713 iter: I,
713 iter: I,
714 f: F,
714 f: F,
715 ) -> impl Iterator<Item = Result<B, E>> + 'a
715 ) -> impl Iterator<Item = Result<B, E>> + 'a
716 where
716 where
717 I: Iterator<Item = Result<A, E>> + 'a,
717 I: Iterator<Item = Result<A, E>> + 'a,
718 F: Fn(A) -> Result<Option<B>, E> + 'a,
718 F: Fn(A) -> Result<Option<B>, E> + 'a,
719 {
719 {
720 iter.filter_map(move |result| match result {
720 iter.filter_map(move |result| match result {
721 Ok(node) => f(node).transpose(),
721 Ok(node) => f(node).transpose(),
722 Err(e) => Some(Err(e)),
722 Err(e) => Some(Err(e)),
723 })
723 })
724 }
724 }
725
725
726 impl OwningDirstateMap {
726 impl OwningDirstateMap {
727 pub fn clear(&mut self) {
727 pub fn clear(&mut self) {
728 self.with_dmap_mut(|map| {
728 self.with_dmap_mut(|map| {
729 map.root = Default::default();
729 map.root = Default::default();
730 map.nodes_with_entry_count = 0;
730 map.nodes_with_entry_count = 0;
731 map.nodes_with_copy_source_count = 0;
731 map.nodes_with_copy_source_count = 0;
732 });
732 });
733 }
733 }
734
734
735 pub fn set_entry(
735 pub fn set_entry(
736 &mut self,
736 &mut self,
737 filename: &HgPath,
737 filename: &HgPath,
738 entry: DirstateEntry,
738 entry: DirstateEntry,
739 ) -> Result<(), DirstateV2ParseError> {
739 ) -> Result<(), DirstateV2ParseError> {
740 self.with_dmap_mut(|map| {
740 self.with_dmap_mut(|map| {
741 map.get_or_insert(&filename)?.data = NodeData::Entry(entry);
741 map.get_or_insert(&filename)?.data = NodeData::Entry(entry);
742 Ok(())
742 Ok(())
743 })
743 })
744 }
744 }
745
745
746 pub fn add_file(
746 pub fn add_file(
747 &mut self,
747 &mut self,
748 filename: &HgPath,
748 filename: &HgPath,
749 entry: DirstateEntry,
749 entry: DirstateEntry,
750 ) -> Result<(), DirstateError> {
750 ) -> Result<(), DirstateError> {
751 let old_state = self.get(filename)?.map(|e| e.state());
751 let old_state = self.get(filename)?.map(|e| e.state());
752 self.with_dmap_mut(|map| {
752 self.with_dmap_mut(|map| {
753 Ok(map.add_or_remove_file(filename, old_state, entry)?)
753 Ok(map.add_or_remove_file(filename, old_state, entry)?)
754 })
754 })
755 }
755 }
756
756
757 pub fn remove_file(
757 pub fn remove_file(
758 &mut self,
758 &mut self,
759 filename: &HgPath,
759 filename: &HgPath,
760 in_merge: bool,
760 in_merge: bool,
761 ) -> Result<(), DirstateError> {
761 ) -> Result<(), DirstateError> {
762 let old_entry_opt = self.get(filename)?;
762 let old_entry_opt = self.get(filename)?;
763 let old_state = old_entry_opt.map(|e| e.state());
763 let old_state = old_entry_opt.map(|e| e.state());
764 let mut size = 0;
764 let mut size = 0;
765 if in_merge {
765 if in_merge {
766 // XXX we should not be able to have 'm' state and 'FROM_P2' if not
766 // XXX we should not be able to have 'm' state and 'FROM_P2' if not
767 // during a merge. So I (marmoute) am not sure we need the
767 // during a merge. So I (marmoute) am not sure we need the
768 // conditionnal at all. Adding double checking this with assert
768 // conditionnal at all. Adding double checking this with assert
769 // would be nice.
769 // would be nice.
770 if let Some(old_entry) = old_entry_opt {
770 if let Some(old_entry) = old_entry_opt {
771 // backup the previous state
771 // backup the previous state
772 if old_entry.state() == EntryState::Merged {
772 if old_entry.state() == EntryState::Merged {
773 size = SIZE_NON_NORMAL;
773 size = SIZE_NON_NORMAL;
774 } else if old_entry.state() == EntryState::Normal
774 } else if old_entry.state() == EntryState::Normal
775 && old_entry.size() == SIZE_FROM_OTHER_PARENT
775 && old_entry.size() == SIZE_FROM_OTHER_PARENT
776 {
776 {
777 // other parent
777 // other parent
778 size = SIZE_FROM_OTHER_PARENT;
778 size = SIZE_FROM_OTHER_PARENT;
779 }
779 }
780 }
780 }
781 }
781 }
782 if size == 0 {
782 if size == 0 {
783 self.copy_map_remove(filename)?;
783 self.copy_map_remove(filename)?;
784 }
784 }
785 self.with_dmap_mut(|map| {
785 self.with_dmap_mut(|map| {
786 let entry = DirstateEntry::new_removed(size);
786 let entry = DirstateEntry::new_removed(size);
787 Ok(map.add_or_remove_file(filename, old_state, entry)?)
787 Ok(map.add_or_remove_file(filename, old_state, entry)?)
788 })
788 })
789 }
789 }
790
790
791 pub fn drop_entry_and_copy_source(
791 pub fn drop_entry_and_copy_source(
792 &mut self,
792 &mut self,
793 filename: &HgPath,
793 filename: &HgPath,
794 ) -> Result<(), DirstateError> {
794 ) -> Result<(), DirstateError> {
795 let was_tracked = self
795 let was_tracked = self
796 .get(filename)?
796 .get(filename)?
797 .map_or(false, |e| e.state().is_tracked());
797 .map_or(false, |e| e.state().is_tracked());
798 struct Dropped {
798 struct Dropped {
799 was_tracked: bool,
799 was_tracked: bool,
800 had_entry: bool,
800 had_entry: bool,
801 had_copy_source: bool,
801 had_copy_source: bool,
802 }
802 }
803
803
804 /// If this returns `Ok(Some((dropped, removed)))`, then
804 /// If this returns `Ok(Some((dropped, removed)))`, then
805 ///
805 ///
806 /// * `dropped` is about the leaf node that was at `filename`
806 /// * `dropped` is about the leaf node that was at `filename`
807 /// * `removed` is whether this particular level of recursion just
807 /// * `removed` is whether this particular level of recursion just
808 /// removed a node in `nodes`.
808 /// removed a node in `nodes`.
809 fn recur<'on_disk>(
809 fn recur<'on_disk>(
810 on_disk: &'on_disk [u8],
810 on_disk: &'on_disk [u8],
811 unreachable_bytes: &mut u32,
811 unreachable_bytes: &mut u32,
812 nodes: &mut ChildNodes<'on_disk>,
812 nodes: &mut ChildNodes<'on_disk>,
813 path: &HgPath,
813 path: &HgPath,
814 ) -> Result<Option<(Dropped, bool)>, DirstateV2ParseError> {
814 ) -> Result<Option<(Dropped, bool)>, DirstateV2ParseError> {
815 let (first_path_component, rest_of_path) =
815 let (first_path_component, rest_of_path) =
816 path.split_first_component();
816 path.split_first_component();
817 let nodes = nodes.make_mut(on_disk, unreachable_bytes)?;
817 let nodes = nodes.make_mut(on_disk, unreachable_bytes)?;
818 let node = if let Some(node) = nodes.get_mut(first_path_component)
818 let node = if let Some(node) = nodes.get_mut(first_path_component)
819 {
819 {
820 node
820 node
821 } else {
821 } else {
822 return Ok(None);
822 return Ok(None);
823 };
823 };
824 let dropped;
824 let dropped;
825 if let Some(rest) = rest_of_path {
825 if let Some(rest) = rest_of_path {
826 if let Some((d, removed)) = recur(
826 if let Some((d, removed)) = recur(
827 on_disk,
827 on_disk,
828 unreachable_bytes,
828 unreachable_bytes,
829 &mut node.children,
829 &mut node.children,
830 rest,
830 rest,
831 )? {
831 )? {
832 dropped = d;
832 dropped = d;
833 if dropped.had_entry {
833 if dropped.had_entry {
834 node.descendants_with_entry_count -= 1;
834 node.descendants_with_entry_count = node
835 .descendants_with_entry_count
836 .checked_sub(1)
837 .expect(
838 "descendants_with_entry_count should be >= 0",
839 );
835 }
840 }
836 if dropped.was_tracked {
841 if dropped.was_tracked {
837 node.tracked_descendants_count -= 1;
842 node.tracked_descendants_count = node
843 .tracked_descendants_count
844 .checked_sub(1)
845 .expect(
846 "tracked_descendants_count should be >= 0",
847 );
838 }
848 }
839
849
840 // Directory caches must be invalidated when removing a
850 // Directory caches must be invalidated when removing a
841 // child node
851 // child node
842 if removed {
852 if removed {
843 if let NodeData::CachedDirectory { .. } = &node.data {
853 if let NodeData::CachedDirectory { .. } = &node.data {
844 node.data = NodeData::None
854 node.data = NodeData::None
845 }
855 }
846 }
856 }
847 } else {
857 } else {
848 return Ok(None);
858 return Ok(None);
849 }
859 }
850 } else {
860 } else {
851 let had_entry = node.data.has_entry();
861 let had_entry = node.data.has_entry();
852 if had_entry {
862 if had_entry {
853 node.data = NodeData::None
863 node.data = NodeData::None
854 }
864 }
855 if let Some(source) = &node.copy_source {
865 if let Some(source) = &node.copy_source {
856 DirstateMap::count_dropped_path(unreachable_bytes, source);
866 DirstateMap::count_dropped_path(unreachable_bytes, source);
857 node.copy_source = None
867 node.copy_source = None
858 }
868 }
859 dropped = Dropped {
869 dropped = Dropped {
860 was_tracked: node
870 was_tracked: node
861 .data
871 .data
862 .as_entry()
872 .as_entry()
863 .map_or(false, |entry| entry.state().is_tracked()),
873 .map_or(false, |entry| entry.state().is_tracked()),
864 had_entry,
874 had_entry,
865 had_copy_source: node.copy_source.take().is_some(),
875 had_copy_source: node.copy_source.take().is_some(),
866 };
876 };
867 }
877 }
868 // After recursion, for both leaf (rest_of_path is None) nodes and
878 // After recursion, for both leaf (rest_of_path is None) nodes and
869 // parent nodes, remove a node if it just became empty.
879 // parent nodes, remove a node if it just became empty.
870 let remove = !node.data.has_entry()
880 let remove = !node.data.has_entry()
871 && node.copy_source.is_none()
881 && node.copy_source.is_none()
872 && node.children.is_empty();
882 && node.children.is_empty();
873 if remove {
883 if remove {
874 let (key, _) =
884 let (key, _) =
875 nodes.remove_entry(first_path_component).unwrap();
885 nodes.remove_entry(first_path_component).unwrap();
876 DirstateMap::count_dropped_path(
886 DirstateMap::count_dropped_path(
877 unreachable_bytes,
887 unreachable_bytes,
878 key.full_path(),
888 key.full_path(),
879 )
889 )
880 }
890 }
881 Ok(Some((dropped, remove)))
891 Ok(Some((dropped, remove)))
882 }
892 }
883
893
884 self.with_dmap_mut(|map| {
894 self.with_dmap_mut(|map| {
885 if let Some((dropped, _removed)) = recur(
895 if let Some((dropped, _removed)) = recur(
886 map.on_disk,
896 map.on_disk,
887 &mut map.unreachable_bytes,
897 &mut map.unreachable_bytes,
888 &mut map.root,
898 &mut map.root,
889 filename,
899 filename,
890 )? {
900 )? {
891 if dropped.had_entry {
901 if dropped.had_entry {
892 map.nodes_with_entry_count -= 1
902 map.nodes_with_entry_count = map
903 .nodes_with_entry_count
904 .checked_sub(1)
905 .expect("nodes_with_entry_count should be >= 0");
893 }
906 }
894 if dropped.had_copy_source {
907 if dropped.had_copy_source {
895 map.nodes_with_copy_source_count -= 1
908 map.nodes_with_copy_source_count = map
909 .nodes_with_copy_source_count
910 .checked_sub(1)
911 .expect("nodes_with_copy_source_count should be >= 0");
896 }
912 }
897 } else {
913 } else {
898 debug_assert!(!was_tracked);
914 debug_assert!(!was_tracked);
899 }
915 }
900 Ok(())
916 Ok(())
901 })
917 })
902 }
918 }
903
919
904 pub fn has_tracked_dir(
920 pub fn has_tracked_dir(
905 &mut self,
921 &mut self,
906 directory: &HgPath,
922 directory: &HgPath,
907 ) -> Result<bool, DirstateError> {
923 ) -> Result<bool, DirstateError> {
908 self.with_dmap_mut(|map| {
924 self.with_dmap_mut(|map| {
909 if let Some(node) = map.get_node(directory)? {
925 if let Some(node) = map.get_node(directory)? {
910 // A node without a `DirstateEntry` was created to hold child
926 // A node without a `DirstateEntry` was created to hold child
911 // nodes, and is therefore a directory.
927 // nodes, and is therefore a directory.
912 let state = node.state()?;
928 let state = node.state()?;
913 Ok(state.is_none() && node.tracked_descendants_count() > 0)
929 Ok(state.is_none() && node.tracked_descendants_count() > 0)
914 } else {
930 } else {
915 Ok(false)
931 Ok(false)
916 }
932 }
917 })
933 })
918 }
934 }
919
935
920 pub fn has_dir(
936 pub fn has_dir(
921 &mut self,
937 &mut self,
922 directory: &HgPath,
938 directory: &HgPath,
923 ) -> Result<bool, DirstateError> {
939 ) -> Result<bool, DirstateError> {
924 self.with_dmap_mut(|map| {
940 self.with_dmap_mut(|map| {
925 if let Some(node) = map.get_node(directory)? {
941 if let Some(node) = map.get_node(directory)? {
926 // A node without a `DirstateEntry` was created to hold child
942 // A node without a `DirstateEntry` was created to hold child
927 // nodes, and is therefore a directory.
943 // nodes, and is therefore a directory.
928 let state = node.state()?;
944 let state = node.state()?;
929 Ok(state.is_none() && node.descendants_with_entry_count() > 0)
945 Ok(state.is_none() && node.descendants_with_entry_count() > 0)
930 } else {
946 } else {
931 Ok(false)
947 Ok(false)
932 }
948 }
933 })
949 })
934 }
950 }
935
951
936 #[timed]
952 #[timed]
937 pub fn pack_v1(
953 pub fn pack_v1(
938 &self,
954 &self,
939 parents: DirstateParents,
955 parents: DirstateParents,
940 ) -> Result<Vec<u8>, DirstateError> {
956 ) -> Result<Vec<u8>, DirstateError> {
941 let map = self.get_map();
957 let map = self.get_map();
942 // Optizimation (to be measured?): pre-compute size to avoid `Vec`
958 // Optizimation (to be measured?): pre-compute size to avoid `Vec`
943 // reallocations
959 // reallocations
944 let mut size = parents.as_bytes().len();
960 let mut size = parents.as_bytes().len();
945 for node in map.iter_nodes() {
961 for node in map.iter_nodes() {
946 let node = node?;
962 let node = node?;
947 if node.entry()?.is_some() {
963 if node.entry()?.is_some() {
948 size += packed_entry_size(
964 size += packed_entry_size(
949 node.full_path(map.on_disk)?,
965 node.full_path(map.on_disk)?,
950 node.copy_source(map.on_disk)?,
966 node.copy_source(map.on_disk)?,
951 );
967 );
952 }
968 }
953 }
969 }
954
970
955 let mut packed = Vec::with_capacity(size);
971 let mut packed = Vec::with_capacity(size);
956 packed.extend(parents.as_bytes());
972 packed.extend(parents.as_bytes());
957
973
958 for node in map.iter_nodes() {
974 for node in map.iter_nodes() {
959 let node = node?;
975 let node = node?;
960 if let Some(entry) = node.entry()? {
976 if let Some(entry) = node.entry()? {
961 pack_entry(
977 pack_entry(
962 node.full_path(map.on_disk)?,
978 node.full_path(map.on_disk)?,
963 &entry,
979 &entry,
964 node.copy_source(map.on_disk)?,
980 node.copy_source(map.on_disk)?,
965 &mut packed,
981 &mut packed,
966 );
982 );
967 }
983 }
968 }
984 }
969 Ok(packed)
985 Ok(packed)
970 }
986 }
971
987
972 /// Returns new data and metadata together with whether that data should be
988 /// Returns new data and metadata together with whether that data should be
973 /// appended to the existing data file whose content is at
989 /// appended to the existing data file whose content is at
974 /// `map.on_disk` (true), instead of written to a new data file
990 /// `map.on_disk` (true), instead of written to a new data file
975 /// (false).
991 /// (false).
976 #[timed]
992 #[timed]
977 pub fn pack_v2(
993 pub fn pack_v2(
978 &self,
994 &self,
979 can_append: bool,
995 can_append: bool,
980 ) -> Result<(Vec<u8>, on_disk::TreeMetadata, bool), DirstateError> {
996 ) -> Result<(Vec<u8>, on_disk::TreeMetadata, bool), DirstateError> {
981 let map = self.get_map();
997 let map = self.get_map();
982 on_disk::write(map, can_append)
998 on_disk::write(map, can_append)
983 }
999 }
984
1000
985 /// `callback` allows the caller to process and do something with the
1001 /// `callback` allows the caller to process and do something with the
986 /// results of the status. This is needed to do so efficiently (i.e.
1002 /// results of the status. This is needed to do so efficiently (i.e.
987 /// without cloning the `DirstateStatus` object with its paths) because
1003 /// without cloning the `DirstateStatus` object with its paths) because
988 /// we need to borrow from `Self`.
1004 /// we need to borrow from `Self`.
989 pub fn with_status<R>(
1005 pub fn with_status<R>(
990 &mut self,
1006 &mut self,
991 matcher: &(dyn Matcher + Sync),
1007 matcher: &(dyn Matcher + Sync),
992 root_dir: PathBuf,
1008 root_dir: PathBuf,
993 ignore_files: Vec<PathBuf>,
1009 ignore_files: Vec<PathBuf>,
994 options: StatusOptions,
1010 options: StatusOptions,
995 callback: impl for<'r> FnOnce(
1011 callback: impl for<'r> FnOnce(
996 Result<(DirstateStatus<'r>, Vec<PatternFileWarning>), StatusError>,
1012 Result<(DirstateStatus<'r>, Vec<PatternFileWarning>), StatusError>,
997 ) -> R,
1013 ) -> R,
998 ) -> R {
1014 ) -> R {
999 self.with_dmap_mut(|map| {
1015 self.with_dmap_mut(|map| {
1000 callback(super::status::status(
1016 callback(super::status::status(
1001 map,
1017 map,
1002 matcher,
1018 matcher,
1003 root_dir,
1019 root_dir,
1004 ignore_files,
1020 ignore_files,
1005 options,
1021 options,
1006 ))
1022 ))
1007 })
1023 })
1008 }
1024 }
1009
1025
1010 pub fn copy_map_len(&self) -> usize {
1026 pub fn copy_map_len(&self) -> usize {
1011 let map = self.get_map();
1027 let map = self.get_map();
1012 map.nodes_with_copy_source_count as usize
1028 map.nodes_with_copy_source_count as usize
1013 }
1029 }
1014
1030
1015 pub fn copy_map_iter(&self) -> CopyMapIter<'_> {
1031 pub fn copy_map_iter(&self) -> CopyMapIter<'_> {
1016 let map = self.get_map();
1032 let map = self.get_map();
1017 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1033 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1018 Ok(if let Some(source) = node.copy_source(map.on_disk)? {
1034 Ok(if let Some(source) = node.copy_source(map.on_disk)? {
1019 Some((node.full_path(map.on_disk)?, source))
1035 Some((node.full_path(map.on_disk)?, source))
1020 } else {
1036 } else {
1021 None
1037 None
1022 })
1038 })
1023 }))
1039 }))
1024 }
1040 }
1025
1041
1026 pub fn copy_map_contains_key(
1042 pub fn copy_map_contains_key(
1027 &self,
1043 &self,
1028 key: &HgPath,
1044 key: &HgPath,
1029 ) -> Result<bool, DirstateV2ParseError> {
1045 ) -> Result<bool, DirstateV2ParseError> {
1030 let map = self.get_map();
1046 let map = self.get_map();
1031 Ok(if let Some(node) = map.get_node(key)? {
1047 Ok(if let Some(node) = map.get_node(key)? {
1032 node.has_copy_source()
1048 node.has_copy_source()
1033 } else {
1049 } else {
1034 false
1050 false
1035 })
1051 })
1036 }
1052 }
1037
1053
1038 pub fn copy_map_get(
1054 pub fn copy_map_get(
1039 &self,
1055 &self,
1040 key: &HgPath,
1056 key: &HgPath,
1041 ) -> Result<Option<&HgPath>, DirstateV2ParseError> {
1057 ) -> Result<Option<&HgPath>, DirstateV2ParseError> {
1042 let map = self.get_map();
1058 let map = self.get_map();
1043 if let Some(node) = map.get_node(key)? {
1059 if let Some(node) = map.get_node(key)? {
1044 if let Some(source) = node.copy_source(map.on_disk)? {
1060 if let Some(source) = node.copy_source(map.on_disk)? {
1045 return Ok(Some(source));
1061 return Ok(Some(source));
1046 }
1062 }
1047 }
1063 }
1048 Ok(None)
1064 Ok(None)
1049 }
1065 }
1050
1066
1051 pub fn copy_map_remove(
1067 pub fn copy_map_remove(
1052 &mut self,
1068 &mut self,
1053 key: &HgPath,
1069 key: &HgPath,
1054 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1070 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1055 self.with_dmap_mut(|map| {
1071 self.with_dmap_mut(|map| {
1056 let count = &mut map.nodes_with_copy_source_count;
1072 let count = &mut map.nodes_with_copy_source_count;
1057 let unreachable_bytes = &mut map.unreachable_bytes;
1073 let unreachable_bytes = &mut map.unreachable_bytes;
1058 Ok(DirstateMap::get_node_mut(
1074 Ok(DirstateMap::get_node_mut(
1059 map.on_disk,
1075 map.on_disk,
1060 unreachable_bytes,
1076 unreachable_bytes,
1061 &mut map.root,
1077 &mut map.root,
1062 key,
1078 key,
1063 )?
1079 )?
1064 .and_then(|node| {
1080 .and_then(|node| {
1065 if let Some(source) = &node.copy_source {
1081 if let Some(source) = &node.copy_source {
1066 *count -= 1;
1082 *count -= 1;
1067 DirstateMap::count_dropped_path(unreachable_bytes, source);
1083 DirstateMap::count_dropped_path(unreachable_bytes, source);
1068 }
1084 }
1069 node.copy_source.take().map(Cow::into_owned)
1085 node.copy_source.take().map(Cow::into_owned)
1070 }))
1086 }))
1071 })
1087 })
1072 }
1088 }
1073
1089
1074 pub fn copy_map_insert(
1090 pub fn copy_map_insert(
1075 &mut self,
1091 &mut self,
1076 key: HgPathBuf,
1092 key: HgPathBuf,
1077 value: HgPathBuf,
1093 value: HgPathBuf,
1078 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1094 ) -> Result<Option<HgPathBuf>, DirstateV2ParseError> {
1079 self.with_dmap_mut(|map| {
1095 self.with_dmap_mut(|map| {
1080 let node = DirstateMap::get_or_insert_node(
1096 let node = DirstateMap::get_or_insert_node(
1081 map.on_disk,
1097 map.on_disk,
1082 &mut map.unreachable_bytes,
1098 &mut map.unreachable_bytes,
1083 &mut map.root,
1099 &mut map.root,
1084 &key,
1100 &key,
1085 WithBasename::to_cow_owned,
1101 WithBasename::to_cow_owned,
1086 |_ancestor| {},
1102 |_ancestor| {},
1087 )?;
1103 )?;
1088 if node.copy_source.is_none() {
1104 if node.copy_source.is_none() {
1089 map.nodes_with_copy_source_count += 1
1105 map.nodes_with_copy_source_count += 1
1090 }
1106 }
1091 Ok(node.copy_source.replace(value.into()).map(Cow::into_owned))
1107 Ok(node.copy_source.replace(value.into()).map(Cow::into_owned))
1092 })
1108 })
1093 }
1109 }
1094
1110
1095 pub fn len(&self) -> usize {
1111 pub fn len(&self) -> usize {
1096 let map = self.get_map();
1112 let map = self.get_map();
1097 map.nodes_with_entry_count as usize
1113 map.nodes_with_entry_count as usize
1098 }
1114 }
1099
1115
1100 pub fn contains_key(
1116 pub fn contains_key(
1101 &self,
1117 &self,
1102 key: &HgPath,
1118 key: &HgPath,
1103 ) -> Result<bool, DirstateV2ParseError> {
1119 ) -> Result<bool, DirstateV2ParseError> {
1104 Ok(self.get(key)?.is_some())
1120 Ok(self.get(key)?.is_some())
1105 }
1121 }
1106
1122
1107 pub fn get(
1123 pub fn get(
1108 &self,
1124 &self,
1109 key: &HgPath,
1125 key: &HgPath,
1110 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
1126 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
1111 let map = self.get_map();
1127 let map = self.get_map();
1112 Ok(if let Some(node) = map.get_node(key)? {
1128 Ok(if let Some(node) = map.get_node(key)? {
1113 node.entry()?
1129 node.entry()?
1114 } else {
1130 } else {
1115 None
1131 None
1116 })
1132 })
1117 }
1133 }
1118
1134
1119 pub fn iter(&self) -> StateMapIter<'_> {
1135 pub fn iter(&self) -> StateMapIter<'_> {
1120 let map = self.get_map();
1136 let map = self.get_map();
1121 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1137 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1122 Ok(if let Some(entry) = node.entry()? {
1138 Ok(if let Some(entry) = node.entry()? {
1123 Some((node.full_path(map.on_disk)?, entry))
1139 Some((node.full_path(map.on_disk)?, entry))
1124 } else {
1140 } else {
1125 None
1141 None
1126 })
1142 })
1127 }))
1143 }))
1128 }
1144 }
1129
1145
1130 pub fn iter_tracked_dirs(
1146 pub fn iter_tracked_dirs(
1131 &mut self,
1147 &mut self,
1132 ) -> Result<
1148 ) -> Result<
1133 Box<
1149 Box<
1134 dyn Iterator<Item = Result<&HgPath, DirstateV2ParseError>>
1150 dyn Iterator<Item = Result<&HgPath, DirstateV2ParseError>>
1135 + Send
1151 + Send
1136 + '_,
1152 + '_,
1137 >,
1153 >,
1138 DirstateError,
1154 DirstateError,
1139 > {
1155 > {
1140 let map = self.get_map();
1156 let map = self.get_map();
1141 let on_disk = map.on_disk;
1157 let on_disk = map.on_disk;
1142 Ok(Box::new(filter_map_results(
1158 Ok(Box::new(filter_map_results(
1143 map.iter_nodes(),
1159 map.iter_nodes(),
1144 move |node| {
1160 move |node| {
1145 Ok(if node.tracked_descendants_count() > 0 {
1161 Ok(if node.tracked_descendants_count() > 0 {
1146 Some(node.full_path(on_disk)?)
1162 Some(node.full_path(on_disk)?)
1147 } else {
1163 } else {
1148 None
1164 None
1149 })
1165 })
1150 },
1166 },
1151 )))
1167 )))
1152 }
1168 }
1153
1169
1154 pub fn debug_iter(
1170 pub fn debug_iter(
1155 &self,
1171 &self,
1156 all: bool,
1172 all: bool,
1157 ) -> Box<
1173 ) -> Box<
1158 dyn Iterator<
1174 dyn Iterator<
1159 Item = Result<
1175 Item = Result<
1160 (&HgPath, (u8, i32, i32, i32)),
1176 (&HgPath, (u8, i32, i32, i32)),
1161 DirstateV2ParseError,
1177 DirstateV2ParseError,
1162 >,
1178 >,
1163 > + Send
1179 > + Send
1164 + '_,
1180 + '_,
1165 > {
1181 > {
1166 let map = self.get_map();
1182 let map = self.get_map();
1167 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1183 Box::new(filter_map_results(map.iter_nodes(), move |node| {
1168 let debug_tuple = if let Some(entry) = node.entry()? {
1184 let debug_tuple = if let Some(entry) = node.entry()? {
1169 entry.debug_tuple()
1185 entry.debug_tuple()
1170 } else if !all {
1186 } else if !all {
1171 return Ok(None);
1187 return Ok(None);
1172 } else if let Some(mtime) = node.cached_directory_mtime()? {
1188 } else if let Some(mtime) = node.cached_directory_mtime()? {
1173 (b' ', 0, -1, mtime.truncated_seconds() as i32)
1189 (b' ', 0, -1, mtime.truncated_seconds() as i32)
1174 } else {
1190 } else {
1175 (b' ', 0, -1, -1)
1191 (b' ', 0, -1, -1)
1176 };
1192 };
1177 Ok(Some((node.full_path(map.on_disk)?, debug_tuple)))
1193 Ok(Some((node.full_path(map.on_disk)?, debug_tuple)))
1178 }))
1194 }))
1179 }
1195 }
1180 }
1196 }
General Comments 0
You need to be logged in to leave comments. Login now