| 1 |
// Copyright 2018-2020 Georges Racinet <[email protected]> |
| 2 |
// and Mercurial contributors |
| 3 |
// |
| 4 |
// This software may be used and distributed according to the terms of the |
| 5 |
// GNU General Public License version 2 or any later version. |
| 6 |
//! Indexing facilities for fast retrieval of `Revision` from `Node` |
| 7 |
//! |
| 8 |
//! This provides a variation on the 16-ary radix tree that is |
| 9 |
//! provided as "nodetree" in revlog.c, ready for append-only persistence |
| 10 |
//! on disk. |
| 11 |
//! |
| 12 |
//! Following existing implicit conventions, the "nodemap" terminology |
| 13 |
//! is used in a more abstract context. |
| 14 |
|
| 15 |
use std::cmp::max; |
| 16 |
use std::fmt; |
| 17 |
use std::mem::align_of; |
| 18 |
use std::mem::size_of; |
| 19 |
use std::mem::{self}; |
| 20 |
use std::ops::Deref; |
| 21 |
use std::ops::Index; |
| 22 |
use std::path::Path; |
| 23 |
|
| 24 |
use bytes_cast::unaligned; |
| 25 |
use bytes_cast::BytesCast; |
| 26 |
|
| 27 |
use super::node::NULL_NODE; |
| 28 |
use super::BaseRevision; |
| 29 |
use super::Node; |
| 30 |
use super::NodePrefix; |
| 31 |
use super::Revision; |
| 32 |
use super::RevlogIndex; |
| 33 |
use super::NULL_REVISION; |
| 34 |
use crate::errors::HgError; |
| 35 |
use crate::revlog::NodeMapDocket; |
| 36 |
use crate::vfs::VfsImpl; |
| 37 |
use crate::UncheckedRevision; |
| 38 |
|
| 39 |
type NodeTreeBuffer = Box<dyn Deref<Target = [u8]> + Send + Sync>; |
| 40 |
|
| 41 |
#[derive(Debug, PartialEq, derive_more::Display)] |
| 42 |
pub enum NodeMapError { |
| 43 |
/// A `NodePrefix` matches several [`Revision`]s. |
| 44 |
/// |
| 45 |
/// This can be returned by methods meant for (at most) one match. |
| 46 |
MultipleResults, |
| 47 |
/// A `Revision` stored in the nodemap could not be found in the index |
| 48 |
RevisionNotInIndex(UncheckedRevision), |
| 49 |
} |
| 50 |
|
| 51 |
/// Mapping system from Mercurial nodes to revision numbers. |
| 52 |
/// |
| 53 |
/// ## `RevlogIndex` and `NodeMap` |
| 54 |
/// |
| 55 |
/// One way to think about their relationship is that |
| 56 |
/// the `NodeMap` is a prefix-oriented reverse index of the [`Node`] |
| 57 |
/// information carried by a [`RevlogIndex`]. |
| 58 |
/// |
| 59 |
/// Many of the methods in this trait take a `RevlogIndex` argument |
| 60 |
/// which is used for validation of their results. This index must naturally |
| 61 |
/// be the one the `NodeMap` is about, and it must be consistent. |
| 62 |
/// |
| 63 |
/// Notably, the `NodeMap` must not store |
| 64 |
/// information about more `Revision` values than there are in the index. |
| 65 |
/// In these methods, an encountered `Revision` is not in the index, a |
| 66 |
/// [RevisionNotInIndex](NodeMapError) error is returned. |
| 67 |
/// |
| 68 |
/// In insert operations, the rule is thus that the `NodeMap` must always |
| 69 |
/// be updated after the `RevlogIndex` it is about. |
| 70 |
pub trait NodeMap { |
| 71 |
/// Find the unique `Revision` having the given `Node` |
| 72 |
/// |
| 73 |
/// If no Revision matches the given `Node`, `Ok(None)` is returned. |
| 74 |
fn find_node( |
| 75 |
&self, |
| 76 |
index: &impl RevlogIndex, |
| 77 |
node: &Node, |
| 78 |
) -> Result<Option<Revision>, NodeMapError> { |
| 79 |
self.find_bin(index, node.into()) |
| 80 |
} |
| 81 |
|
| 82 |
/// Find the unique Revision whose `Node` starts with a given binary prefix |
| 83 |
/// |
| 84 |
/// If no Revision matches the given prefix, `Ok(None)` is returned. |
| 85 |
/// |
| 86 |
/// If several Revisions match the given prefix, a |
| 87 |
/// [MultipleResults](NodeMapError) error is returned. |
| 88 |
fn find_bin( |
| 89 |
&self, |
| 90 |
idx: &impl RevlogIndex, |
| 91 |
prefix: NodePrefix, |
| 92 |
) -> Result<Option<Revision>, NodeMapError>; |
| 93 |
|
| 94 |
/// Give the size of the shortest node prefix that determines |
| 95 |
/// the revision uniquely. |
| 96 |
/// |
| 97 |
/// From a binary node prefix, if it is matched in the node map, this |
| 98 |
/// returns the number of hexadecimal digits that would had sufficed |
| 99 |
/// to find the revision uniquely. |
| 100 |
/// |
| 101 |
/// Returns `None` if no [`Revision`] could be found for the prefix. |
| 102 |
/// |
| 103 |
/// If several Revisions match the given prefix, a |
| 104 |
/// [MultipleResults](NodeMapError) error is returned. |
| 105 |
fn unique_prefix_len_bin( |
| 106 |
&self, |
| 107 |
idx: &impl RevlogIndex, |
| 108 |
node_prefix: NodePrefix, |
| 109 |
) -> Result<Option<usize>, NodeMapError>; |
| 110 |
|
| 111 |
/// Same as [unique_prefix_len_bin](Self::unique_prefix_len_bin), with |
| 112 |
/// a full [`Node`] as input |
| 113 |
fn unique_prefix_len_node( |
| 114 |
&self, |
| 115 |
idx: &impl RevlogIndex, |
| 116 |
node: &Node, |
| 117 |
) -> Result<Option<usize>, NodeMapError> { |
| 118 |
self.unique_prefix_len_bin(idx, node.into()) |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
pub trait MutableNodeMap: NodeMap { |
| 123 |
fn insert<I: RevlogIndex>( |
| 124 |
&mut self, |
| 125 |
index: &I, |
| 126 |
node: &Node, |
| 127 |
rev: Revision, |
| 128 |
) -> Result<(), NodeMapError>; |
| 129 |
} |
| 130 |
|
| 131 |
/// Low level NodeTree [`Block`] elements |
| 132 |
/// |
| 133 |
/// These are exactly as for instance on persistent storage. |
| 134 |
type RawElement = unaligned::I32Be; |
| 135 |
|
| 136 |
/// High level representation of values in NodeTree |
| 137 |
/// [`Blocks`](struct.Block.html) |
| 138 |
/// |
| 139 |
/// This is the high level representation that most algorithms should |
| 140 |
/// use. |
| 141 |
#[derive(Clone, Debug, Eq, PartialEq)] |
| 142 |
enum Element { |
| 143 |
// This is not a Mercurial revision. It's a `i32` because this is the |
| 144 |
// right type for this structure. |
| 145 |
Rev(i32), |
| 146 |
Block(usize), |
| 147 |
None, |
| 148 |
} |
| 149 |
|
| 150 |
impl From<RawElement> for Element { |
| 151 |
/// Conversion from low level representation, after endianness conversion. |
| 152 |
/// |
| 153 |
/// See [`Block`](struct.Block.html) for explanation about the encoding. |
| 154 |
fn from(raw: RawElement) -> Element { |
| 155 |
let int = raw.get(); |
| 156 |
if int >= 0 { |
| 157 |
Element::Block(int as usize) |
| 158 |
} else if int == -1 { |
| 159 |
Element::None |
| 160 |
} else { |
| 161 |
Element::Rev(-int - 2) |
| 162 |
} |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
impl From<Element> for RawElement { |
| 167 |
fn from(element: Element) -> RawElement { |
| 168 |
RawElement::from(match element { |
| 169 |
Element::None => 0, |
| 170 |
Element::Block(i) => i as i32, |
| 171 |
Element::Rev(rev) => -rev - 2, |
| 172 |
}) |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
const ELEMENTS_PER_BLOCK: usize = 16; // number of different values in a nybble |
| 177 |
|
| 178 |
/// A logical block of the [`NodeTree`], packed with a fixed size. |
| 179 |
/// |
| 180 |
/// These are always used in container types implementing `Index<Block>`, |
| 181 |
/// such as `&Block` |
| 182 |
/// |
| 183 |
/// As an array of integers, its ith element encodes that the |
| 184 |
/// ith potential edge from the block, representing the ith hexadecimal digit |
| 185 |
/// (nybble) `i` is either: |
| 186 |
/// |
| 187 |
/// - absent (value -1) |
| 188 |
/// - another `Block` in the same indexable container (value ≥ 0) |
| 189 |
/// - a [`Revision`] leaf (value ≤ -2) |
| 190 |
/// |
| 191 |
/// Endianness has to be fixed for consistency on shared storage across |
| 192 |
/// different architectures. |
| 193 |
/// |
| 194 |
/// A key difference with the C `nodetree` is that we need to be |
| 195 |
/// able to represent the [`Block`] at index 0, hence -1 is the empty marker |
| 196 |
/// rather than 0 and the [`Revision`] range upper limit of -2 instead of -1. |
| 197 |
/// |
| 198 |
/// Another related difference is that `NULL_REVISION` (-1) is not |
| 199 |
/// represented at all, because we want an immutable empty nodetree |
| 200 |
/// to be valid. |
| 201 |
#[derive(Copy, Clone, BytesCast, PartialEq)] |
| 202 |
#[repr(transparent)] |
| 203 |
pub struct Block([RawElement; ELEMENTS_PER_BLOCK]); |
| 204 |
|
| 205 |
impl Block { |
| 206 |
fn new() -> Self { |
| 207 |
let absent_node = RawElement::from(-1); |
| 208 |
Block([absent_node; ELEMENTS_PER_BLOCK]) |
| 209 |
} |
| 210 |
|
| 211 |
fn get(&self, nybble: u8) -> Element { |
| 212 |
self.0[nybble as usize].into() |
| 213 |
} |
| 214 |
|
| 215 |
fn set(&mut self, nybble: u8, element: Element) { |
| 216 |
self.0[nybble as usize] = element.into() |
| 217 |
} |
| 218 |
} |
| 219 |
|
| 220 |
impl fmt::Debug for Block { |
| 221 |
/// sparse representation for testing and debugging purposes |
| 222 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 223 |
f.debug_map() |
| 224 |
.entries((0..16).filter_map(|i| match self.get(i) { |
| 225 |
Element::None => None, |
| 226 |
element => Some((i, element)), |
| 227 |
})) |
| 228 |
.finish() |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
/// A mutable 16-radix tree with the root block logically at the end |
| 233 |
/// |
| 234 |
/// Because of the append only nature of our node trees, we need to |
| 235 |
/// keep the original untouched and store new blocks separately. |
| 236 |
/// |
| 237 |
/// The mutable root [`Block`] is kept apart so that we don't have to rebump |
| 238 |
/// it on each insertion. |
| 239 |
pub struct NodeTree { |
| 240 |
readonly: Box<dyn Deref<Target = [Block]> + Send + Sync>, |
| 241 |
growable: Vec<Block>, |
| 242 |
root: Block, |
| 243 |
masked_inner_blocks: usize, |
| 244 |
} |
| 245 |
|
| 246 |
impl Index<usize> for NodeTree { |
| 247 |
type Output = Block; |
| 248 |
|
| 249 |
fn index(&self, i: usize) -> &Block { |
| 250 |
let ro_len = self.readonly.len(); |
| 251 |
if i < ro_len { |
| 252 |
&self.readonly[i] |
| 253 |
} else if i == ro_len + self.growable.len() { |
| 254 |
&self.root |
| 255 |
} else { |
| 256 |
&self.growable[i - ro_len] |
| 257 |
} |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
/// Return `None` unless the [`Node`] for `rev` has given prefix in `idx`. |
| 262 |
fn has_prefix_or_none( |
| 263 |
idx: &impl RevlogIndex, |
| 264 |
prefix: NodePrefix, |
| 265 |
rev: UncheckedRevision, |
| 266 |
) -> Result<Option<Revision>, NodeMapError> { |
| 267 |
if rev.is_nullrev() { |
| 268 |
return Ok(None); |
| 269 |
} |
| 270 |
match idx.check_revision(rev) { |
| 271 |
Some(checked) => Ok(if prefix.is_prefix_of(idx.node(checked)) { |
| 272 |
Some(checked) |
| 273 |
} else { |
| 274 |
None |
| 275 |
}), |
| 276 |
None => Err(NodeMapError::RevisionNotInIndex(rev)), |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
/// validate that the candidate's node starts indeed with given prefix, |
| 281 |
/// and treat ambiguities related to [`NULL_REVISION`]. |
| 282 |
/// |
| 283 |
/// From the data in the NodeTree, one can only conclude that some |
| 284 |
/// revision is the only one for a *subprefix* of the one being looked up. |
| 285 |
fn validate_candidate( |
| 286 |
idx: &impl RevlogIndex, |
| 287 |
prefix: NodePrefix, |
| 288 |
candidate: (Option<UncheckedRevision>, usize), |
| 289 |
) -> Result<(Option<Revision>, usize), NodeMapError> { |
| 290 |
let (rev, steps) = candidate; |
| 291 |
if let Some(nz_nybble) = prefix.first_different_nybble(&NULL_NODE) { |
| 292 |
rev.map_or(Ok((None, steps)), |r| { |
| 293 |
has_prefix_or_none(idx, prefix, r) |
| 294 |
.map(|opt| (opt, max(steps, nz_nybble + 1))) |
| 295 |
}) |
| 296 |
} else { |
| 297 |
// the prefix is only made of zeros; NULL_REVISION always matches it |
| 298 |
// and any other *valid* result is an ambiguity |
| 299 |
match rev { |
| 300 |
None => Ok((Some(NULL_REVISION), steps + 1)), |
| 301 |
Some(r) => match has_prefix_or_none(idx, prefix, r)? { |
| 302 |
None => Ok((Some(NULL_REVISION), steps + 1)), |
| 303 |
_ => Err(NodeMapError::MultipleResults), |
| 304 |
}, |
| 305 |
} |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
/// Read the persistent nodemap corresponding to the `index` at `index_path`. |
| 310 |
/// `index` and `index_path` MUST reference the same index. |
| 311 |
pub(super) fn read_persistent_nodemap( |
| 312 |
store_vfs: &VfsImpl, |
| 313 |
index_path: &Path, |
| 314 |
index: &impl RevlogIndex, |
| 315 |
) -> Result<Option<NodeTree>, HgError> { |
| 316 |
if let Some((docket, data)) = |
| 317 |
NodeMapDocket::read_from_file(store_vfs, index_path)? |
| 318 |
{ |
| 319 |
let mut nodemap = |
| 320 |
NodeTree::load_bytes(Box::new(data), docket.data_length); |
| 321 |
if let Some(valid_tip_rev) = index.check_revision(docket.tip_rev) { |
| 322 |
let valid_node = index.node(valid_tip_rev) == &docket.tip_node; |
| 323 |
if valid_node && (valid_tip_rev.0 as usize) < index.len() { |
| 324 |
// The index moved forward but wasn't rewritten |
| 325 |
nodemap |
| 326 |
.catch_up_to_index(index, valid_tip_rev) |
| 327 |
.map_err(|e| HgError::abort_simple(e.to_string()))?; |
| 328 |
return Ok(Some(nodemap)); |
| 329 |
} |
| 330 |
} |
| 331 |
if !index.is_empty() { |
| 332 |
// The nodemap exists but is invalid somehow (strip, corruption...) |
| 333 |
// so we rebuild it from scratch. |
| 334 |
let mut nodemap = NodeTree::new(Box::<Vec<_>>::default()); |
| 335 |
nodemap |
| 336 |
.catch_up_to_index(index, Revision(0)) |
| 337 |
.map_err(|e| HgError::abort_simple(e.to_string()))?; |
| 338 |
return Ok(Some(nodemap)); |
| 339 |
} |
| 340 |
} |
| 341 |
Ok(None) |
| 342 |
} |
| 343 |
|
| 344 |
impl NodeTree { |
| 345 |
/// Initiate a NodeTree from an immutable slice-like of `Block` |
| 346 |
/// |
| 347 |
/// We keep `readonly` and clone its root block if it isn't empty. |
| 348 |
fn new(readonly: Box<dyn Deref<Target = [Block]> + Send + Sync>) -> Self { |
| 349 |
let root = readonly.last().cloned().unwrap_or_else(Block::new); |
| 350 |
NodeTree { |
| 351 |
readonly, |
| 352 |
growable: Vec::new(), |
| 353 |
root, |
| 354 |
masked_inner_blocks: 0, |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
/// Create from an opaque bunch of bytes |
| 359 |
/// |
| 360 |
/// The created [`NodeTreeBytes`] from `bytes`, |
| 361 |
/// of which exactly `amount` bytes are used. |
| 362 |
/// |
| 363 |
/// - `buffer` could be derived from `PyBuffer` and `Mmap` objects. |
| 364 |
/// - `amount` is expressed in bytes, and is not automatically derived from |
| 365 |
/// `bytes`, so that a caller that manages them atomically can perform |
| 366 |
/// temporary disk serializations and still rollback easily if needed. |
| 367 |
/// First use-case for this would be to support Mercurial shell hooks. |
| 368 |
/// |
| 369 |
/// panics if `buffer` is smaller than `amount` |
| 370 |
pub fn load_bytes(bytes: NodeTreeBuffer, amount: usize) -> Self { |
| 371 |
NodeTree::new(Box::new(NodeTreeBytes::new(bytes, amount))) |
| 372 |
} |
| 373 |
|
| 374 |
/// Retrieve added [`Block`]s and the original immutable data |
| 375 |
pub fn into_readonly_and_added( |
| 376 |
self, |
| 377 |
) -> (Box<dyn Deref<Target = [Block]> + Send + Sync>, Vec<Block>) { |
| 378 |
let mut vec = self.growable; |
| 379 |
let readonly = self.readonly; |
| 380 |
if readonly.last() != Some(&self.root) { |
| 381 |
vec.push(self.root); |
| 382 |
} |
| 383 |
(readonly, vec) |
| 384 |
} |
| 385 |
|
| 386 |
/// Retrieve added [`Block]s as bytes, ready to be written to persistent |
| 387 |
/// storage |
| 388 |
pub fn into_readonly_and_added_bytes( |
| 389 |
self, |
| 390 |
) -> (Box<dyn Deref<Target = [Block]> + Send + Sync>, Vec<u8>) { |
| 391 |
let (readonly, vec) = self.into_readonly_and_added(); |
| 392 |
// Prevent running `v`'s destructor so we are in complete control |
| 393 |
// of the allocation. |
| 394 |
let vec = mem::ManuallyDrop::new(vec); |
| 395 |
|
| 396 |
// Transmute the `Vec<Block>` to a `Vec<u8>`. Blocks are contiguous |
| 397 |
// bytes, so this is perfectly safe. |
| 398 |
let bytes = unsafe { |
| 399 |
// Check for compatible allocation layout. |
| 400 |
// (Optimized away by constant-folding + dead code elimination.) |
| 401 |
assert_eq!(size_of::<Block>(), 64); |
| 402 |
assert_eq!(align_of::<Block>(), 1); |
| 403 |
|
| 404 |
// /!\ Any use of `vec` after this is use-after-free. |
| 405 |
// TODO: use `into_raw_parts` once stabilized |
| 406 |
Vec::from_raw_parts( |
| 407 |
vec.as_ptr() as *mut u8, |
| 408 |
vec.len() * size_of::<Block>(), |
| 409 |
vec.capacity() * size_of::<Block>(), |
| 410 |
) |
| 411 |
}; |
| 412 |
(readonly, bytes) |
| 413 |
} |
| 414 |
|
| 415 |
/// Total number of blocks |
| 416 |
fn len(&self) -> usize { |
| 417 |
self.readonly.len() + self.growable.len() + 1 |
| 418 |
} |
| 419 |
|
| 420 |
/// Implemented for completeness |
| 421 |
/// |
| 422 |
/// A `NodeTree` always has at least the mutable root block. |
| 423 |
#[allow(dead_code)] |
| 424 |
fn is_empty(&self) -> bool { |
| 425 |
false |
| 426 |
} |
| 427 |
|
| 428 |
/// Main working method for `NodeTree` searches |
| 429 |
/// |
| 430 |
/// The first returned value is the result of analysing `NodeTree` data |
| 431 |
/// *alone*: whereas `None` guarantees that the given prefix is absent |
| 432 |
/// from the [`NodeTree`] data (but still could match [`NULL_NODE`]), with |
| 433 |
/// `Some(rev)`, it is to be understood that `rev` is the unique |
| 434 |
/// [`Revision`] that could match the prefix. Actually, all that can |
| 435 |
/// be inferred from |
| 436 |
/// the `NodeTree` data is that `rev` is the revision with the longest |
| 437 |
/// common node prefix with the given prefix. |
| 438 |
/// We return an [`UncheckedRevision`] because we have no guarantee that |
| 439 |
/// the revision we found is valid for the index. |
| 440 |
/// |
| 441 |
/// The second returned value is the size of the smallest subprefix |
| 442 |
/// of `prefix` that would give the same result, i.e. not the |
| 443 |
/// [MultipleResults](NodeMapError) error variant (again, using only the |
| 444 |
/// data of the [`NodeTree`]). |
| 445 |
fn lookup( |
| 446 |
&self, |
| 447 |
prefix: NodePrefix, |
| 448 |
) -> Result<(Option<UncheckedRevision>, usize), NodeMapError> { |
| 449 |
for (i, visit_item) in self.visit(prefix).enumerate() { |
| 450 |
if let Some(opt) = visit_item.final_revision() { |
| 451 |
return Ok((opt, i + 1)); |
| 452 |
} |
| 453 |
} |
| 454 |
Err(NodeMapError::MultipleResults) |
| 455 |
} |
| 456 |
|
| 457 |
fn visit(&self, prefix: NodePrefix) -> NodeTreeVisitor { |
| 458 |
NodeTreeVisitor { |
| 459 |
nt: self, |
| 460 |
prefix, |
| 461 |
visit: self.len() - 1, |
| 462 |
nybble_idx: 0, |
| 463 |
done: false, |
| 464 |
} |
| 465 |
} |
| 466 |
/// Return a mutable reference for `Block` at index `idx`. |
| 467 |
/// |
| 468 |
/// If `idx` lies in the immutable area, then the reference is to |
| 469 |
/// a newly appended copy. |
| 470 |
/// |
| 471 |
/// Returns (new_idx, glen, mut_ref) where |
| 472 |
/// |
| 473 |
/// - `new_idx` is the index of the mutable `Block` |
| 474 |
/// - `mut_ref` is a mutable reference to the mutable Block. |
| 475 |
/// - `glen` is the new length of `self.growable` |
| 476 |
/// |
| 477 |
/// Note: the caller wouldn't be allowed to query `self.growable.len()` |
| 478 |
/// itself because of the mutable borrow taken with the returned `Block` |
| 479 |
fn mutable_block(&mut self, idx: usize) -> (usize, &mut Block, usize) { |
| 480 |
let ro_blocks = &self.readonly; |
| 481 |
let ro_len = ro_blocks.len(); |
| 482 |
let glen = self.growable.len(); |
| 483 |
if idx < ro_len { |
| 484 |
self.masked_inner_blocks += 1; |
| 485 |
self.growable.push(ro_blocks[idx]); |
| 486 |
(glen + ro_len, &mut self.growable[glen], glen + 1) |
| 487 |
} else if glen + ro_len == idx { |
| 488 |
(idx, &mut self.root, glen) |
| 489 |
} else { |
| 490 |
(idx, &mut self.growable[idx - ro_len], glen) |
| 491 |
} |
| 492 |
} |
| 493 |
|
| 494 |
/// Main insertion method |
| 495 |
/// |
| 496 |
/// This will dive in the node tree to find the deepest `Block` for |
| 497 |
/// `node`, split it as much as needed and record `node` in there. |
| 498 |
/// The method then backtracks, updating references in all the visited |
| 499 |
/// blocks from the root. |
| 500 |
/// |
| 501 |
/// All the mutated `Block` are copied first to the growable part if |
| 502 |
/// needed. That happens for those in the immutable part except the root. |
| 503 |
pub fn insert<I: RevlogIndex>( |
| 504 |
&mut self, |
| 505 |
index: &I, |
| 506 |
node: &Node, |
| 507 |
rev: Revision, |
| 508 |
) -> Result<(), NodeMapError> { |
| 509 |
self.insert_single(index, node, rev, &mut vec![]) |
| 510 |
} |
| 511 |
|
| 512 |
/// See [`Self::insert`] and [`Self::insert_many`] for public interfaces |
| 513 |
fn insert_single<I: RevlogIndex>( |
| 514 |
&mut self, |
| 515 |
index: &I, |
| 516 |
node: &Node, |
| 517 |
rev: Revision, |
| 518 |
visit_steps: &mut Vec<NodeTreeVisitItem>, |
| 519 |
) -> Result<(), NodeMapError> { |
| 520 |
let ro_len = &self.readonly.len(); |
| 521 |
|
| 522 |
visit_steps.extend(self.visit(node.into())); |
| 523 |
let read_nybbles = visit_steps.len(); |
| 524 |
// visit_steps cannot be empty, since we always visit the root block |
| 525 |
let deepest = visit_steps.pop().unwrap(); |
| 526 |
|
| 527 |
let (mut block_idx, mut block, mut glen) = |
| 528 |
self.mutable_block(deepest.block_idx); |
| 529 |
|
| 530 |
if let Element::Rev(old_rev) = deepest.element { |
| 531 |
let o_rev = match index.check_revision(old_rev.into()) { |
| 532 |
None => { |
| 533 |
return Err(NodeMapError::RevisionNotInIndex( |
| 534 |
old_rev.into(), |
| 535 |
)) |
| 536 |
} |
| 537 |
Some(rev) => rev, |
| 538 |
}; |
| 539 |
let old_node = index.node(o_rev); |
| 540 |
if old_node == node { |
| 541 |
return Ok(()); // avoid creating lots of useless blocks |
| 542 |
} |
| 543 |
|
| 544 |
// Looping over the tail of nybbles in both nodes, creating |
| 545 |
// new blocks until we find the difference |
| 546 |
let mut new_block_idx = ro_len + glen; |
| 547 |
let mut nybble = deepest.nybble; |
| 548 |
for nybble_pos in read_nybbles..node.nybbles_len() { |
| 549 |
block.set(nybble, Element::Block(new_block_idx)); |
| 550 |
|
| 551 |
let new_nybble = node.get_nybble(nybble_pos); |
| 552 |
let old_nybble = old_node.get_nybble(nybble_pos); |
| 553 |
|
| 554 |
if old_nybble == new_nybble { |
| 555 |
self.growable.push(Block::new()); |
| 556 |
block = &mut self.growable[glen]; |
| 557 |
glen += 1; |
| 558 |
new_block_idx += 1; |
| 559 |
nybble = new_nybble; |
| 560 |
} else { |
| 561 |
let mut new_block = Block::new(); |
| 562 |
new_block.set(old_nybble, Element::Rev(old_rev)); |
| 563 |
new_block.set(new_nybble, Element::Rev(rev.0)); |
| 564 |
self.growable.push(new_block); |
| 565 |
break; |
| 566 |
} |
| 567 |
} |
| 568 |
} else { |
| 569 |
// Free slot in the deepest block: no splitting has to be done |
| 570 |
block.set(deepest.nybble, Element::Rev(rev.0)); |
| 571 |
} |
| 572 |
|
| 573 |
// Backtrack over visit steps to update references |
| 574 |
while let Some(visited) = visit_steps.pop() { |
| 575 |
let to_write = Element::Block(block_idx); |
| 576 |
if visit_steps.is_empty() { |
| 577 |
self.root.set(visited.nybble, to_write); |
| 578 |
break; |
| 579 |
} |
| 580 |
let (new_idx, block, _) = self.mutable_block(visited.block_idx); |
| 581 |
if block.get(visited.nybble) == to_write { |
| 582 |
break; |
| 583 |
} |
| 584 |
block.set(visited.nybble, to_write); |
| 585 |
block_idx = new_idx; |
| 586 |
} |
| 587 |
Ok(()) |
| 588 |
} |
| 589 |
|
| 590 |
/// Batched insertion method (see [`Self::insert`] for single insertions) |
| 591 |
/// |
| 592 |
/// This exists for performance reasons, implemented in a future patch. |
| 593 |
pub fn insert_many<I: RevlogIndex>( |
| 594 |
&mut self, |
| 595 |
index: &I, |
| 596 |
from: Revision, |
| 597 |
to: Revision, |
| 598 |
) -> Result<(), NodeMapError> { |
| 599 |
let revisions_to_add = 0.max(to.0 - from.0) as usize; |
| 600 |
// There are about 5 blocks per revision for all persistent nodemaps |
| 601 |
// observed in the wild, so we over-allocate slightly with 6. |
| 602 |
const FACTOR: usize = 6; |
| 603 |
self.growable.reserve(revisions_to_add * FACTOR); |
| 604 |
|
| 605 |
// Reuse this vec for all visit planning to save a ton of allocations |
| 606 |
// (about 5 per revision) |
| 607 |
let mut visit_vec = vec![]; |
| 608 |
for revnum in from.0..=to.0 { |
| 609 |
let rev = Revision(revnum); |
| 610 |
self.insert_single(index, index.node(rev), rev, &mut visit_vec)?; |
| 611 |
visit_vec.clear(); |
| 612 |
} |
| 613 |
Ok(()) |
| 614 |
} |
| 615 |
|
| 616 |
/// Insert all [`Revision`] from `from` inclusive, up to |
| 617 |
/// [`RevlogIndex::len`] exclusive. |
| 618 |
/// |
| 619 |
/// `from` must be a valid revision for `index`, most likely should be the |
| 620 |
/// tip of the nodemap docket. |
| 621 |
/// |
| 622 |
/// Useful for updating the [`NodeTree`] when the index has moved forward. |
| 623 |
pub fn catch_up_to_index( |
| 624 |
&mut self, |
| 625 |
index: &impl RevlogIndex, |
| 626 |
from: Revision, |
| 627 |
) -> Result<(), NodeMapError> { |
| 628 |
let to = Revision(0.max(index.len() - 1) as BaseRevision); |
| 629 |
self.insert_many(index, from, to) |
| 630 |
} |
| 631 |
|
| 632 |
/// Make the whole `NodeTree` logically empty, without touching the |
| 633 |
/// immutable part. |
| 634 |
pub fn invalidate_all(&mut self) { |
| 635 |
self.root = Block::new(); |
| 636 |
self.growable = Vec::new(); |
| 637 |
self.masked_inner_blocks = self.readonly.len(); |
| 638 |
} |
| 639 |
|
| 640 |
/// Return the number of blocks in the readonly part that are currently |
| 641 |
/// masked in the mutable part. |
| 642 |
/// |
| 643 |
/// The `NodeTree` structure has no efficient way to know how many blocks |
| 644 |
/// are already unreachable in the readonly part. |
| 645 |
/// |
| 646 |
/// After a call to `invalidate_all()`, the returned number can be actually |
| 647 |
/// bigger than the whole readonly part, a conventional way to mean that |
| 648 |
/// all the readonly blocks have been masked. This is what is really |
| 649 |
/// useful to the caller and does not require to know how many were |
| 650 |
/// actually unreachable to begin with. |
| 651 |
pub fn masked_readonly_blocks(&self) -> usize { |
| 652 |
if let Some(readonly_root) = self.readonly.last() { |
| 653 |
if readonly_root == &self.root { |
| 654 |
return 0; |
| 655 |
} |
| 656 |
} else { |
| 657 |
return 0; |
| 658 |
} |
| 659 |
self.masked_inner_blocks + 1 |
| 660 |
} |
| 661 |
} |
| 662 |
|
| 663 |
pub struct NodeTreeBytes { |
| 664 |
buffer: NodeTreeBuffer, |
| 665 |
len_in_blocks: usize, |
| 666 |
} |
| 667 |
|
| 668 |
impl NodeTreeBytes { |
| 669 |
fn new(buffer: NodeTreeBuffer, amount: usize) -> Self { |
| 670 |
assert!(buffer.len() >= amount); |
| 671 |
let len_in_blocks = amount / size_of::<Block>(); |
| 672 |
NodeTreeBytes { buffer, len_in_blocks } |
| 673 |
} |
| 674 |
} |
| 675 |
|
| 676 |
impl Deref for NodeTreeBytes { |
| 677 |
type Target = [Block]; |
| 678 |
|
| 679 |
fn deref(&self) -> &[Block] { |
| 680 |
Block::slice_from_bytes(&self.buffer, self.len_in_blocks) |
| 681 |
// `NodeTreeBytes::new` already asserted that `self.buffer` is |
| 682 |
// large enough. |
| 683 |
.unwrap() |
| 684 |
.0 |
| 685 |
} |
| 686 |
} |
| 687 |
|
| 688 |
struct NodeTreeVisitor<'n> { |
| 689 |
nt: &'n NodeTree, |
| 690 |
prefix: NodePrefix, |
| 691 |
visit: usize, |
| 692 |
nybble_idx: usize, |
| 693 |
done: bool, |
| 694 |
} |
| 695 |
|
| 696 |
#[derive(Debug, PartialEq, Clone)] |
| 697 |
struct NodeTreeVisitItem { |
| 698 |
block_idx: usize, |
| 699 |
nybble: u8, |
| 700 |
element: Element, |
| 701 |
} |
| 702 |
|
| 703 |
impl Iterator for NodeTreeVisitor<'_> { |
| 704 |
type Item = NodeTreeVisitItem; |
| 705 |
|
| 706 |
fn next(&mut self) -> Option<Self::Item> { |
| 707 |
if self.done || self.nybble_idx >= self.prefix.nybbles_len() { |
| 708 |
return None; |
| 709 |
} |
| 710 |
|
| 711 |
let nybble = self.prefix.get_nybble(self.nybble_idx); |
| 712 |
self.nybble_idx += 1; |
| 713 |
|
| 714 |
let visit = self.visit; |
| 715 |
let element = self.nt[visit].get(nybble); |
| 716 |
if let Element::Block(idx) = element { |
| 717 |
self.visit = idx; |
| 718 |
} else { |
| 719 |
self.done = true; |
| 720 |
} |
| 721 |
|
| 722 |
Some(NodeTreeVisitItem { block_idx: visit, nybble, element }) |
| 723 |
} |
| 724 |
} |
| 725 |
|
| 726 |
impl NodeTreeVisitItem { |
| 727 |
// Return `Some(opt)` if this item is final, with `opt` being the |
| 728 |
// `UncheckedRevision` that it may represent. |
| 729 |
// |
| 730 |
// If the item is not terminal, return `None` |
| 731 |
fn final_revision(&self) -> Option<Option<UncheckedRevision>> { |
| 732 |
match self.element { |
| 733 |
Element::Block(_) => None, |
| 734 |
Element::Rev(r) => Some(Some(r.into())), |
| 735 |
Element::None => Some(None), |
| 736 |
} |
| 737 |
} |
| 738 |
} |
| 739 |
|
| 740 |
impl From<Vec<Block>> for NodeTree { |
| 741 |
fn from(vec: Vec<Block>) -> Self { |
| 742 |
Self::new(Box::new(vec)) |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
impl fmt::Debug for NodeTree { |
| 747 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 748 |
let readonly: &[Block] = &self.readonly; |
| 749 |
write!( |
| 750 |
f, |
| 751 |
"readonly: {:?}, growable: {:?}, root: {:?}", |
| 752 |
readonly, self.growable, self.root |
| 753 |
) |
| 754 |
} |
| 755 |
} |
| 756 |
|
| 757 |
impl Default for NodeTree { |
| 758 |
/// Create a fully mutable empty NodeTree |
| 759 |
fn default() -> Self { |
| 760 |
NodeTree::new(Box::<Vec<_>>::default()) |
| 761 |
} |
| 762 |
} |
| 763 |
|
| 764 |
impl NodeMap for NodeTree { |
| 765 |
fn find_bin<'a>( |
| 766 |
&self, |
| 767 |
idx: &impl RevlogIndex, |
| 768 |
prefix: NodePrefix, |
| 769 |
) -> Result<Option<Revision>, NodeMapError> { |
| 770 |
validate_candidate(idx, prefix, self.lookup(prefix)?) |
| 771 |
.map(|(opt, _shortest)| opt) |
| 772 |
} |
| 773 |
|
| 774 |
fn unique_prefix_len_bin<'a>( |
| 775 |
&self, |
| 776 |
idx: &impl RevlogIndex, |
| 777 |
prefix: NodePrefix, |
| 778 |
) -> Result<Option<usize>, NodeMapError> { |
| 779 |
validate_candidate(idx, prefix, self.lookup(prefix)?) |
| 780 |
.map(|(opt, shortest)| opt.map(|_rev| shortest)) |
| 781 |
} |
| 782 |
} |
| 783 |
|
| 784 |
#[cfg(test)] |
| 785 |
pub mod tests { |
| 786 |
use std::collections::HashMap; |
| 787 |
|
| 788 |
use super::NodeMapError::*; |
| 789 |
use super::*; |
| 790 |
use crate::revlog::node::hex_pad_right; |
| 791 |
use crate::revlog::node::Node; |
| 792 |
|
| 793 |
/// Creates a `Block` using a syntax close to the `Debug` output |
| 794 |
macro_rules! block { |
| 795 |
{$($nybble:tt : $variant:ident($val:tt)),*} => ( |
| 796 |
{ |
| 797 |
let mut block = Block::new(); |
| 798 |
$(block.set($nybble, Element::$variant($val)));*; |
| 799 |
block |
| 800 |
} |
| 801 |
) |
| 802 |
} |
| 803 |
|
| 804 |
/// Shorthand to reduce boilerplate when creating [`Revision`] for testing |
| 805 |
macro_rules! R { |
| 806 |
($revision:literal) => { |
| 807 |
Revision($revision) |
| 808 |
}; |
| 809 |
} |
| 810 |
|
| 811 |
#[test] |
| 812 |
fn test_block_debug() { |
| 813 |
let mut block = Block::new(); |
| 814 |
block.set(1, Element::Rev(3)); |
| 815 |
block.set(10, Element::Block(0)); |
| 816 |
assert_eq!(format!("{:?}", block), "{1: Rev(3), 10: Block(0)}"); |
| 817 |
} |
| 818 |
|
| 819 |
#[test] |
| 820 |
fn test_block_macro() { |
| 821 |
let block = block! {5: Block(2)}; |
| 822 |
assert_eq!(format!("{:?}", block), "{5: Block(2)}"); |
| 823 |
|
| 824 |
let block = block! {13: Rev(15), 5: Block(2)}; |
| 825 |
assert_eq!(format!("{:?}", block), "{5: Block(2), 13: Rev(15)}"); |
| 826 |
} |
| 827 |
|
| 828 |
#[test] |
| 829 |
fn test_raw_block() { |
| 830 |
let mut raw = [255u8; 64]; |
| 831 |
|
| 832 |
let mut counter = 0; |
| 833 |
for val in [0_i32, 15, -2, -1, -3].iter() { |
| 834 |
for byte in val.to_be_bytes().iter() { |
| 835 |
raw[counter] = *byte; |
| 836 |
counter += 1; |
| 837 |
} |
| 838 |
} |
| 839 |
let (block, _) = Block::from_bytes(&raw).unwrap(); |
| 840 |
assert_eq!(block.get(0), Element::Block(0)); |
| 841 |
assert_eq!(block.get(1), Element::Block(15)); |
| 842 |
assert_eq!(block.get(3), Element::None); |
| 843 |
assert_eq!(block.get(2), Element::Rev(0)); |
| 844 |
assert_eq!(block.get(4), Element::Rev(1)); |
| 845 |
} |
| 846 |
|
| 847 |
type TestIndex = HashMap<UncheckedRevision, Node>; |
| 848 |
|
| 849 |
impl RevlogIndex for TestIndex { |
| 850 |
fn node(&self, rev: Revision) -> &Node { |
| 851 |
self.get(&rev.into()).unwrap_or(&NULL_NODE) |
| 852 |
} |
| 853 |
|
| 854 |
fn len(&self) -> usize { |
| 855 |
self.len() |
| 856 |
} |
| 857 |
|
| 858 |
fn check_revision(&self, rev: UncheckedRevision) -> Option<Revision> { |
| 859 |
if rev.is_nullrev() { |
| 860 |
// return Some(NULL_REVISION) |
| 861 |
return None; |
| 862 |
} |
| 863 |
self.get(&rev).map(|_| Revision(rev.0)) |
| 864 |
} |
| 865 |
} |
| 866 |
|
| 867 |
/// Pad hexadecimal Node prefix with zeros on the right |
| 868 |
/// |
| 869 |
/// This avoids having to repeatedly write very long hexadecimal |
| 870 |
/// strings for test data, and brings actual hash size independency. |
| 871 |
#[cfg(test)] |
| 872 |
fn pad_node(hex: &str) -> Node { |
| 873 |
Node::from_hex(hex_pad_right(hex)).unwrap() |
| 874 |
} |
| 875 |
|
| 876 |
/// Pad hexadecimal Node prefix with zeros on the right, then insert |
| 877 |
fn pad_insert(idx: &mut TestIndex, rev: Revision, hex: &str) { |
| 878 |
idx.insert(rev.into(), pad_node(hex)); |
| 879 |
} |
| 880 |
|
| 881 |
fn sample_nodetree() -> NodeTree { |
| 882 |
NodeTree::from(vec![ |
| 883 |
block![0: Rev(9)], |
| 884 |
block![0: Rev(0), 1: Rev(9)], |
| 885 |
block![0: Block(1), 1:Rev(1)], |
| 886 |
]) |
| 887 |
} |
| 888 |
|
| 889 |
fn hex(s: &str) -> NodePrefix { |
| 890 |
NodePrefix::from_hex(s).unwrap() |
| 891 |
} |
| 892 |
|
| 893 |
#[test] |
| 894 |
fn test_nt_debug() { |
| 895 |
let nt = sample_nodetree(); |
| 896 |
assert_eq!( |
| 897 |
format!("{:?}", nt), |
| 898 |
"readonly: \ |
| 899 |
[{0: Rev(9)}, {0: Rev(0), 1: Rev(9)}, {0: Block(1), 1: Rev(1)}], \ |
| 900 |
growable: [], \ |
| 901 |
root: {0: Block(1), 1: Rev(1)}", |
| 902 |
); |
| 903 |
} |
| 904 |
|
| 905 |
#[test] |
| 906 |
fn test_immutable_find_simplest() -> Result<(), NodeMapError> { |
| 907 |
let mut idx: TestIndex = HashMap::new(); |
| 908 |
pad_insert(&mut idx, R!(1), "1234deadcafe"); |
| 909 |
|
| 910 |
let nt = NodeTree::from(vec![block! {1: Rev(1)}]); |
| 911 |
assert_eq!(nt.find_bin(&idx, hex("1"))?, Some(R!(1))); |
| 912 |
assert_eq!(nt.find_bin(&idx, hex("12"))?, Some(R!(1))); |
| 913 |
assert_eq!(nt.find_bin(&idx, hex("1234de"))?, Some(R!(1))); |
| 914 |
assert_eq!(nt.find_bin(&idx, hex("1a"))?, None); |
| 915 |
assert_eq!(nt.find_bin(&idx, hex("ab"))?, None); |
| 916 |
|
| 917 |
// and with full binary Nodes |
| 918 |
assert_eq!( |
| 919 |
nt.find_node(&idx, idx.get(&1.into()).unwrap())?, |
| 920 |
Some(R!(1)) |
| 921 |
); |
| 922 |
let unknown = Node::from_hex(hex_pad_right("3d")).unwrap(); |
| 923 |
assert_eq!(nt.find_node(&idx, &unknown)?, None); |
| 924 |
Ok(()) |
| 925 |
} |
| 926 |
|
| 927 |
#[test] |
| 928 |
fn test_immutable_find_one_jump() { |
| 929 |
let mut idx = TestIndex::new(); |
| 930 |
pad_insert(&mut idx, R!(9), "012"); |
| 931 |
pad_insert(&mut idx, R!(0), "00a"); |
| 932 |
|
| 933 |
let nt = sample_nodetree(); |
| 934 |
|
| 935 |
assert_eq!(nt.find_bin(&idx, hex("0")), Err(MultipleResults)); |
| 936 |
assert_eq!(nt.find_bin(&idx, hex("01")), Ok(Some(R!(9)))); |
| 937 |
assert_eq!(nt.find_bin(&idx, hex("00")), Err(MultipleResults)); |
| 938 |
assert_eq!(nt.find_bin(&idx, hex("00a")), Ok(Some(R!(0)))); |
| 939 |
assert_eq!(nt.unique_prefix_len_bin(&idx, hex("00a")), Ok(Some(3))); |
| 940 |
assert_eq!(nt.find_bin(&idx, hex("000")), Ok(Some(NULL_REVISION))); |
| 941 |
} |
| 942 |
|
| 943 |
#[test] |
| 944 |
fn test_mutated_find() -> Result<(), NodeMapError> { |
| 945 |
let mut idx = TestIndex::new(); |
| 946 |
pad_insert(&mut idx, R!(9), "012"); |
| 947 |
pad_insert(&mut idx, R!(0), "00a"); |
| 948 |
pad_insert(&mut idx, R!(2), "cafe"); |
| 949 |
pad_insert(&mut idx, R!(3), "15"); |
| 950 |
pad_insert(&mut idx, R!(1), "10"); |
| 951 |
|
| 952 |
let nt = NodeTree { |
| 953 |
readonly: sample_nodetree().readonly, |
| 954 |
growable: vec![block![0: Rev(1), 5: Rev(3)]], |
| 955 |
root: block![0: Block(1), 1:Block(3), 12: Rev(2)], |
| 956 |
masked_inner_blocks: 1, |
| 957 |
}; |
| 958 |
assert_eq!(nt.find_bin(&idx, hex("10"))?, Some(R!(1))); |
| 959 |
assert_eq!(nt.find_bin(&idx, hex("c"))?, Some(R!(2))); |
| 960 |
assert_eq!(nt.unique_prefix_len_bin(&idx, hex("c"))?, Some(1)); |
| 961 |
assert_eq!(nt.find_bin(&idx, hex("00")), Err(MultipleResults)); |
| 962 |
assert_eq!(nt.find_bin(&idx, hex("000"))?, Some(NULL_REVISION)); |
| 963 |
assert_eq!(nt.unique_prefix_len_bin(&idx, hex("000"))?, Some(3)); |
| 964 |
assert_eq!(nt.find_bin(&idx, hex("01"))?, Some(R!(9))); |
| 965 |
assert_eq!(nt.masked_readonly_blocks(), 2); |
| 966 |
Ok(()) |
| 967 |
} |
| 968 |
|
| 969 |
pub struct TestNtIndex { |
| 970 |
pub index: TestIndex, |
| 971 |
pub nt: NodeTree, |
| 972 |
} |
| 973 |
|
| 974 |
impl TestNtIndex { |
| 975 |
pub fn new() -> Self { |
| 976 |
TestNtIndex { index: HashMap::new(), nt: NodeTree::default() } |
| 977 |
} |
| 978 |
|
| 979 |
pub fn insert_node( |
| 980 |
&mut self, |
| 981 |
rev: Revision, |
| 982 |
node: Node, |
| 983 |
) -> Result<(), NodeMapError> { |
| 984 |
self.index.insert(rev.into(), node); |
| 985 |
self.nt.insert(&self.index, &node, rev)?; |
| 986 |
Ok(()) |
| 987 |
} |
| 988 |
|
| 989 |
pub fn insert( |
| 990 |
&mut self, |
| 991 |
rev: Revision, |
| 992 |
hex: &str, |
| 993 |
) -> Result<(), NodeMapError> { |
| 994 |
let node = pad_node(hex); |
| 995 |
self.insert_node(rev, node) |
| 996 |
} |
| 997 |
|
| 998 |
fn find_hex( |
| 999 |
&self, |
| 1000 |
prefix: &str, |
| 1001 |
) -> Result<Option<Revision>, NodeMapError> { |
| 1002 |
self.nt.find_bin(&self.index, hex(prefix)) |
| 1003 |
} |
| 1004 |
|
| 1005 |
fn unique_prefix_len_hex( |
| 1006 |
&self, |
| 1007 |
prefix: &str, |
| 1008 |
) -> Result<Option<usize>, NodeMapError> { |
| 1009 |
self.nt.unique_prefix_len_bin(&self.index, hex(prefix)) |
| 1010 |
} |
| 1011 |
|
| 1012 |
/// Drain `added` and restart a new one |
| 1013 |
fn commit(self) -> Self { |
| 1014 |
let mut as_vec: Vec<Block> = |
| 1015 |
self.nt.readonly.iter().copied().collect(); |
| 1016 |
as_vec.extend(self.nt.growable); |
| 1017 |
as_vec.push(self.nt.root); |
| 1018 |
|
| 1019 |
Self { index: self.index, nt: NodeTree::from(as_vec) } |
| 1020 |
} |
| 1021 |
} |
| 1022 |
|
| 1023 |
impl Default for TestNtIndex { |
| 1024 |
fn default() -> Self { |
| 1025 |
Self::new() |
| 1026 |
} |
| 1027 |
} |
| 1028 |
|
| 1029 |
#[test] |
| 1030 |
fn test_insert_full_mutable() -> Result<(), NodeMapError> { |
| 1031 |
let mut idx = TestNtIndex::new(); |
| 1032 |
idx.insert(Revision(0), "1234")?; |
| 1033 |
assert_eq!(idx.find_hex("1")?, Some(R!(0))); |
| 1034 |
assert_eq!(idx.find_hex("12")?, Some(R!(0))); |
| 1035 |
|
| 1036 |
// let's trigger a simple split |
| 1037 |
idx.insert(Revision(1), "1a34")?; |
| 1038 |
assert_eq!(idx.nt.growable.len(), 1); |
| 1039 |
assert_eq!(idx.find_hex("12")?, Some(R!(0))); |
| 1040 |
assert_eq!(idx.find_hex("1a")?, Some(R!(1))); |
| 1041 |
|
| 1042 |
// reinserting is a no_op |
| 1043 |
idx.insert(Revision(1), "1a34")?; |
| 1044 |
assert_eq!(idx.nt.growable.len(), 1); |
| 1045 |
assert_eq!(idx.find_hex("12")?, Some(R!(0))); |
| 1046 |
assert_eq!(idx.find_hex("1a")?, Some(R!(1))); |
| 1047 |
|
| 1048 |
idx.insert(Revision(2), "1a01")?; |
| 1049 |
assert_eq!(idx.nt.growable.len(), 2); |
| 1050 |
assert_eq!(idx.find_hex("1a"), Err(NodeMapError::MultipleResults)); |
| 1051 |
assert_eq!(idx.find_hex("12")?, Some(R!(0))); |
| 1052 |
assert_eq!(idx.find_hex("1a3")?, Some(R!(1))); |
| 1053 |
assert_eq!(idx.find_hex("1a0")?, Some(R!(2))); |
| 1054 |
assert_eq!(idx.find_hex("1a12")?, None); |
| 1055 |
|
| 1056 |
// now let's make it split and create more than one additional block |
| 1057 |
idx.insert(Revision(3), "1a345")?; |
| 1058 |
assert_eq!(idx.nt.growable.len(), 4); |
| 1059 |
assert_eq!(idx.find_hex("1a340")?, Some(R!(1))); |
| 1060 |
assert_eq!(idx.find_hex("1a345")?, Some(R!(3))); |
| 1061 |
assert_eq!(idx.find_hex("1a341")?, None); |
| 1062 |
|
| 1063 |
// there's no readonly block to mask |
| 1064 |
assert_eq!(idx.nt.masked_readonly_blocks(), 0); |
| 1065 |
Ok(()) |
| 1066 |
} |
| 1067 |
|
| 1068 |
#[test] |
| 1069 |
fn test_unique_prefix_len_zero_prefix() { |
| 1070 |
let mut idx = TestNtIndex::new(); |
| 1071 |
idx.insert(Revision(0), "00000abcd").unwrap(); |
| 1072 |
|
| 1073 |
assert_eq!(idx.find_hex("000"), Err(NodeMapError::MultipleResults)); |
| 1074 |
// in the nodetree proper, this will be found at the first nybble |
| 1075 |
// yet the correct answer for unique_prefix_len is not 1, nor 1+1, |
| 1076 |
// but the first difference with `NULL_NODE` |
| 1077 |
assert_eq!(idx.unique_prefix_len_hex("00000a"), Ok(Some(6))); |
| 1078 |
assert_eq!(idx.unique_prefix_len_hex("00000ab"), Ok(Some(6))); |
| 1079 |
|
| 1080 |
// same with odd result |
| 1081 |
idx.insert(Revision(1), "00123").unwrap(); |
| 1082 |
assert_eq!(idx.unique_prefix_len_hex("001"), Ok(Some(3))); |
| 1083 |
assert_eq!(idx.unique_prefix_len_hex("0012"), Ok(Some(3))); |
| 1084 |
|
| 1085 |
// these are unchanged of course |
| 1086 |
assert_eq!(idx.unique_prefix_len_hex("00000a"), Ok(Some(6))); |
| 1087 |
assert_eq!(idx.unique_prefix_len_hex("00000ab"), Ok(Some(6))); |
| 1088 |
} |
| 1089 |
|
| 1090 |
#[test] |
| 1091 |
fn test_insert_extreme_splitting() -> Result<(), NodeMapError> { |
| 1092 |
// check that the splitting loop is long enough |
| 1093 |
let mut nt_idx = TestNtIndex::new(); |
| 1094 |
let nt = &mut nt_idx.nt; |
| 1095 |
let idx = &mut nt_idx.index; |
| 1096 |
|
| 1097 |
let node0_hex = hex_pad_right("444444"); |
| 1098 |
let mut node1_hex = hex_pad_right("444444"); |
| 1099 |
node1_hex.pop(); |
| 1100 |
node1_hex.push('5'); |
| 1101 |
let node0 = Node::from_hex(node0_hex).unwrap(); |
| 1102 |
let node1 = Node::from_hex(&node1_hex).unwrap(); |
| 1103 |
|
| 1104 |
idx.insert(0.into(), node0); |
| 1105 |
nt.insert(idx, &node0, R!(0))?; |
| 1106 |
idx.insert(1.into(), node1); |
| 1107 |
nt.insert(idx, &node1, R!(1))?; |
| 1108 |
|
| 1109 |
assert_eq!(nt.find_bin(idx, (&node0).into())?, Some(R!(0))); |
| 1110 |
assert_eq!(nt.find_bin(idx, (&node1).into())?, Some(R!(1))); |
| 1111 |
Ok(()) |
| 1112 |
} |
| 1113 |
|
| 1114 |
#[test] |
| 1115 |
fn test_insert_partly_immutable() -> Result<(), NodeMapError> { |
| 1116 |
let mut idx = TestNtIndex::new(); |
| 1117 |
idx.insert(Revision(0), "1234")?; |
| 1118 |
idx.insert(Revision(1), "1235")?; |
| 1119 |
idx.insert(Revision(2), "131")?; |
| 1120 |
idx.insert(Revision(3), "cafe")?; |
| 1121 |
let mut idx = idx.commit(); |
| 1122 |
assert_eq!(idx.find_hex("1234")?, Some(R!(0))); |
| 1123 |
assert_eq!(idx.find_hex("1235")?, Some(R!(1))); |
| 1124 |
assert_eq!(idx.find_hex("131")?, Some(R!(2))); |
| 1125 |
assert_eq!(idx.find_hex("cafe")?, Some(R!(3))); |
| 1126 |
// we did not add anything since init from readonly |
| 1127 |
assert_eq!(idx.nt.masked_readonly_blocks(), 0); |
| 1128 |
|
| 1129 |
idx.insert(Revision(4), "123A")?; |
| 1130 |
assert_eq!(idx.find_hex("1234")?, Some(R!(0))); |
| 1131 |
assert_eq!(idx.find_hex("1235")?, Some(R!(1))); |
| 1132 |
assert_eq!(idx.find_hex("131")?, Some(R!(2))); |
| 1133 |
assert_eq!(idx.find_hex("cafe")?, Some(R!(3))); |
| 1134 |
assert_eq!(idx.find_hex("123A")?, Some(R!(4))); |
| 1135 |
// we masked blocks for all prefixes of "123", including the root |
| 1136 |
assert_eq!(idx.nt.masked_readonly_blocks(), 4); |
| 1137 |
|
| 1138 |
eprintln!("{:?}", idx.nt); |
| 1139 |
idx.insert(Revision(5), "c0")?; |
| 1140 |
assert_eq!(idx.find_hex("cafe")?, Some(R!(3))); |
| 1141 |
assert_eq!(idx.find_hex("c0")?, Some(R!(5))); |
| 1142 |
assert_eq!(idx.find_hex("c1")?, None); |
| 1143 |
assert_eq!(idx.find_hex("1234")?, Some(R!(0))); |
| 1144 |
// inserting "c0" is just splitting the 'c' slot of the mutable root, |
| 1145 |
// it doesn't mask anything |
| 1146 |
assert_eq!(idx.nt.masked_readonly_blocks(), 4); |
| 1147 |
|
| 1148 |
Ok(()) |
| 1149 |
} |
| 1150 |
|
| 1151 |
#[test] |
| 1152 |
fn test_invalidate_all() -> Result<(), NodeMapError> { |
| 1153 |
let mut idx = TestNtIndex::new(); |
| 1154 |
idx.insert(Revision(0), "1234")?; |
| 1155 |
idx.insert(Revision(1), "1235")?; |
| 1156 |
idx.insert(Revision(2), "131")?; |
| 1157 |
idx.insert(Revision(3), "cafe")?; |
| 1158 |
let mut idx = idx.commit(); |
| 1159 |
|
| 1160 |
idx.nt.invalidate_all(); |
| 1161 |
|
| 1162 |
assert_eq!(idx.find_hex("1234")?, None); |
| 1163 |
assert_eq!(idx.find_hex("1235")?, None); |
| 1164 |
assert_eq!(idx.find_hex("131")?, None); |
| 1165 |
assert_eq!(idx.find_hex("cafe")?, None); |
| 1166 |
// all the readonly blocks have been masked, this is the |
| 1167 |
// conventional expected response |
| 1168 |
assert_eq!(idx.nt.masked_readonly_blocks(), idx.nt.readonly.len() + 1); |
| 1169 |
Ok(()) |
| 1170 |
} |
| 1171 |
|
| 1172 |
#[test] |
| 1173 |
fn test_into_added_empty() { |
| 1174 |
assert!(sample_nodetree().into_readonly_and_added().1.is_empty()); |
| 1175 |
assert!(sample_nodetree().into_readonly_and_added_bytes().1.is_empty()); |
| 1176 |
} |
| 1177 |
|
| 1178 |
#[test] |
| 1179 |
fn test_into_added_bytes() -> Result<(), NodeMapError> { |
| 1180 |
let mut idx = TestNtIndex::new(); |
| 1181 |
idx.insert(Revision(0), "1234")?; |
| 1182 |
let mut idx = idx.commit(); |
| 1183 |
idx.insert(Revision(4), "cafe")?; |
| 1184 |
let (_, bytes) = idx.nt.into_readonly_and_added_bytes(); |
| 1185 |
|
| 1186 |
// only the root block has been changed |
| 1187 |
assert_eq!(bytes.len(), size_of::<Block>()); |
| 1188 |
// big endian for -2 |
| 1189 |
assert_eq!(&bytes[4..2 * 4], [255, 255, 255, 254]); |
| 1190 |
// big endian for -6 |
| 1191 |
assert_eq!(&bytes[12 * 4..13 * 4], [255, 255, 255, 250]); |
| 1192 |
Ok(()) |
| 1193 |
} |
| 1194 |
} |