| 1 |
//! A layer of lower-level revlog functionality to encapsulate most of the |
| 2 |
//! IO work and expensive operations. |
| 3 |
use std::borrow::Cow; |
| 4 |
use std::io::ErrorKind; |
| 5 |
use std::io::Seek; |
| 6 |
use std::io::SeekFrom; |
| 7 |
use std::io::Write; |
| 8 |
use std::ops::Deref; |
| 9 |
use std::ops::DerefMut; |
| 10 |
use std::path::PathBuf; |
| 11 |
use std::sync::atomic::AtomicUsize; |
| 12 |
use std::sync::atomic::Ordering; |
| 13 |
use std::sync::Arc; |
| 14 |
use std::sync::Mutex; |
| 15 |
use std::sync::RwLock; |
| 16 |
|
| 17 |
use schnellru::LruMap; |
| 18 |
use sha1::Digest; |
| 19 |
use sha1::Sha1; |
| 20 |
|
| 21 |
use super::compression::uncompressed_zstd_data; |
| 22 |
use super::compression::CompressionConfig; |
| 23 |
use super::compression::Compressor; |
| 24 |
use super::compression::NoneCompressor; |
| 25 |
use super::compression::ZlibCompressor; |
| 26 |
use super::compression::ZstdCompressor; |
| 27 |
use super::compression::ZLIB_BYTE; |
| 28 |
use super::compression::ZSTD_BYTE; |
| 29 |
use super::diff; |
| 30 |
use super::diff::text_delta_with_offset; |
| 31 |
use super::file_io::DelayedBuffer; |
| 32 |
use super::file_io::FileHandle; |
| 33 |
use super::file_io::RandomAccessFile; |
| 34 |
use super::file_io::WriteHandles; |
| 35 |
use super::index::Index; |
| 36 |
use super::index::IndexHeader; |
| 37 |
use super::index::INDEX_ENTRY_SIZE; |
| 38 |
use super::manifest; |
| 39 |
use super::node::NODE_BYTES_LENGTH; |
| 40 |
use super::node::NULL_NODE; |
| 41 |
use super::options::RevlogDataConfig; |
| 42 |
use super::options::RevlogDeltaConfig; |
| 43 |
use super::options::RevlogFeatureConfig; |
| 44 |
use super::patch; |
| 45 |
use super::patch::DeltaPiece; |
| 46 |
use super::patch::PlainDeltaPiece; |
| 47 |
use super::BaseRevision; |
| 48 |
use super::Revision; |
| 49 |
use super::RevlogEntry; |
| 50 |
use super::RevlogError; |
| 51 |
use super::RevlogIndex; |
| 52 |
use super::UncheckedRevision; |
| 53 |
use super::NULL_REVISION; |
| 54 |
use super::NULL_REVLOG_ENTRY_FLAGS; |
| 55 |
use crate::dyn_bytes::DynBytes; |
| 56 |
use crate::errors::HgError; |
| 57 |
use crate::errors::IoResultExt; |
| 58 |
use crate::exit_codes; |
| 59 |
use crate::revlog::index::RevisionDataParams; |
| 60 |
use crate::revlog::nodemap::NodeMap; |
| 61 |
use crate::revlog::nodemap::NodeMapError; |
| 62 |
use crate::revlog::nodemap::NodeTree; |
| 63 |
use crate::revlog::RevlogIndexNodeLookup; |
| 64 |
use crate::revlog::RevlogType; |
| 65 |
use crate::transaction::Transaction; |
| 66 |
use crate::utils::u32_u; |
| 67 |
use crate::utils::u_i32; |
| 68 |
use crate::utils::ByTotalChunksSize; |
| 69 |
use crate::utils::RawData; |
| 70 |
use crate::vfs::Vfs; |
| 71 |
use crate::Node; |
| 72 |
use crate::NodePrefix; |
| 73 |
|
| 74 |
/// Matches the `_InnerRevlog` class in the Python code, as an arbitrary |
| 75 |
/// boundary to incrementally rewrite higher-level revlog functionality in |
| 76 |
/// Rust. |
| 77 |
pub struct InnerRevlog { |
| 78 |
/// When index and data are not interleaved: bytes of the revlog index. |
| 79 |
/// When index and data are interleaved (inline revlog): bytes of the |
| 80 |
/// revlog index and data. |
| 81 |
pub index: Index, |
| 82 |
/// The store vfs that is used to interact with the filesystem |
| 83 |
vfs: Box<dyn Vfs>, |
| 84 |
/// The index file path, relative to the vfs root |
| 85 |
pub index_file: PathBuf, |
| 86 |
/// The data file path, relative to the vfs root (same as `index_file` |
| 87 |
/// if inline) |
| 88 |
data_file: PathBuf, |
| 89 |
/// Data config that applies to this revlog |
| 90 |
data_config: RevlogDataConfig, |
| 91 |
/// Delta config that applies to this revlog |
| 92 |
delta_config: RevlogDeltaConfig, |
| 93 |
/// Feature config that applies to this revlog |
| 94 |
feature_config: RevlogFeatureConfig, |
| 95 |
/// A view into this revlog's data file |
| 96 |
segment_file: RandomAccessFile, |
| 97 |
/// A cache of uncompressed chunks that have previously been restored. |
| 98 |
/// Its eviction policy is defined in [`Self::new`]. |
| 99 |
uncompressed_chunk_cache: Option<UncompressedChunkCache>, |
| 100 |
/// Used to keep track of the actual target during diverted writes |
| 101 |
/// for the changelog |
| 102 |
original_index_file: Option<PathBuf>, |
| 103 |
/// Write handles to the index and data files |
| 104 |
/// XXX why duplicate from `index` and `segment_file`? |
| 105 |
writing_handles: Option<WriteHandles>, |
| 106 |
/// See [`DelayedBuffer`]. |
| 107 |
delayed_buffer: Option<Arc<Mutex<DelayedBuffer>>>, |
| 108 |
/// Whether this revlog is inline. XXX why duplicate from `index`? |
| 109 |
pub inline: bool, |
| 110 |
/// A cache of the last revision, which is usually accessed multiple |
| 111 |
/// times. |
| 112 |
last_revision_cache: Mutex<Option<SingleRevisionCache>>, |
| 113 |
/// The [`Compressor`] that this revlog uses by default to compress data. |
| 114 |
/// This does not mean that this revlog uses this compressor for reading |
| 115 |
/// data, as different revisions may have different compression modes. |
| 116 |
compressor: Mutex<Box<dyn Compressor>>, |
| 117 |
revlog_type: RevlogType, |
| 118 |
/// The nodemap for this revlog, either lazy and in-memory or persistent |
| 119 |
nodemap: RevlogNodeMap, |
| 120 |
} |
| 121 |
|
| 122 |
impl InnerRevlog { |
| 123 |
#[allow(clippy::too_many_arguments)] |
| 124 |
pub fn new( |
| 125 |
vfs: Box<dyn Vfs>, |
| 126 |
index: Index, |
| 127 |
index_file: PathBuf, |
| 128 |
data_file: PathBuf, |
| 129 |
data_config: RevlogDataConfig, |
| 130 |
delta_config: RevlogDeltaConfig, |
| 131 |
feature_config: RevlogFeatureConfig, |
| 132 |
revlog_type: RevlogType, |
| 133 |
nodemap: Option<NodeTree>, |
| 134 |
) -> Self { |
| 135 |
assert!(index_file.is_relative()); |
| 136 |
assert!(data_file.is_relative()); |
| 137 |
let segment_file = RandomAccessFile::new( |
| 138 |
dyn_clone::clone_box(&*vfs), |
| 139 |
if index.is_inline() { |
| 140 |
index_file.to_owned() |
| 141 |
} else { |
| 142 |
data_file.to_owned() |
| 143 |
}, |
| 144 |
); |
| 145 |
|
| 146 |
let uncompressed_chunk_cache = |
| 147 |
data_config.uncompressed_cache_factor.map( |
| 148 |
// Arbitrary initial value |
| 149 |
// TODO check if using a hasher specific to integers is useful |
| 150 |
|_factor| { |
| 151 |
let resize_factor = data_config |
| 152 |
.uncompressed_cache_factor |
| 153 |
.expect("cache should not exist without factor"); |
| 154 |
RwLock::new(LruMap::new(ByTotalChunksSize::new( |
| 155 |
65536, |
| 156 |
resize_factor, |
| 157 |
))) |
| 158 |
}, |
| 159 |
); |
| 160 |
|
| 161 |
let inline = index.is_inline(); |
| 162 |
let nodemap = |
| 163 |
RevlogNodeMap::from_nodetree_option(nodemap, index_file.to_owned()); |
| 164 |
Self { |
| 165 |
index, |
| 166 |
vfs, |
| 167 |
index_file, |
| 168 |
data_file, |
| 169 |
data_config, |
| 170 |
delta_config, |
| 171 |
feature_config, |
| 172 |
segment_file, |
| 173 |
uncompressed_chunk_cache, |
| 174 |
original_index_file: None, |
| 175 |
writing_handles: None, |
| 176 |
delayed_buffer: None, |
| 177 |
inline, |
| 178 |
last_revision_cache: Mutex::new(None), |
| 179 |
compressor: Mutex::new(match feature_config.compression_engine { |
| 180 |
CompressionConfig::Zlib { level } => { |
| 181 |
Box::new(ZlibCompressor::new(level)) |
| 182 |
} |
| 183 |
CompressionConfig::Zstd { level, threads } => { |
| 184 |
Box::new(ZstdCompressor::new(level, threads)) |
| 185 |
} |
| 186 |
CompressionConfig::None => Box::new(NoneCompressor), |
| 187 |
}), |
| 188 |
revlog_type, |
| 189 |
nodemap, |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
/// Return number of entries of the revlog index |
| 194 |
pub fn len(&self) -> usize { |
| 195 |
self.index.len() |
| 196 |
} |
| 197 |
|
| 198 |
/// Return `true` if this revlog has no entries |
| 199 |
pub fn is_empty(&self) -> bool { |
| 200 |
self.len() == 0 |
| 201 |
} |
| 202 |
|
| 203 |
/// Return whether this revlog is inline (mixed index and data) |
| 204 |
pub fn is_inline(&self) -> bool { |
| 205 |
self.inline |
| 206 |
} |
| 207 |
|
| 208 |
/// Clear all caches from this revlog |
| 209 |
pub fn clear_cache(&mut self) { |
| 210 |
assert!(!self.is_delaying()); |
| 211 |
if let Some(cache) = self.uncompressed_chunk_cache.as_ref() { |
| 212 |
// We don't clear the allocation here because it's probably faster. |
| 213 |
// We could change our minds later if this ends up being a problem |
| 214 |
// with regards to memory consumption. |
| 215 |
cache.write().expect("lock is poisoned").clear(); |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
/// Set the "last revision cache" content |
| 220 |
pub fn set_rev_cache(&self, rev: Revision, data: ForeignBytes) { |
| 221 |
let mut last_revision_cache = |
| 222 |
self.last_revision_cache.lock().expect("propagate mutex panic"); |
| 223 |
let data = CachedBytes::Foreign(data); |
| 224 |
*last_revision_cache = Some(SingleRevisionCache { rev, data }); |
| 225 |
} |
| 226 |
|
| 227 |
/// Set the "last revision cache" content from a Rust native type |
| 228 |
pub fn set_rev_cache_native(&self, rev: Revision, data: &RawData) { |
| 229 |
let mut last_revision_cache = |
| 230 |
self.last_revision_cache.lock().expect("propagate mutex panic"); |
| 231 |
if let Some(cached) = &*last_revision_cache { |
| 232 |
// same a Arc clone when possible |
| 233 |
if cached.rev == rev { |
| 234 |
return; |
| 235 |
} |
| 236 |
} |
| 237 |
let data = CachedBytes::Native(data.clone()); |
| 238 |
*last_revision_cache = Some(SingleRevisionCache { rev, data }); |
| 239 |
} |
| 240 |
|
| 241 |
/// Clear the revision cache for the given revision (if any) |
| 242 |
pub fn clear_rev_cache(&self, rev: Revision) { |
| 243 |
let mut last_revision_cache = |
| 244 |
self.last_revision_cache.lock().expect("propagate mutex panic"); |
| 245 |
if let Some(cached) = &*last_revision_cache { |
| 246 |
if cached.rev == rev { |
| 247 |
last_revision_cache.take(); |
| 248 |
} |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
/// retrieve a owned copy of the cache |
| 253 |
/// |
| 254 |
/// The cache lock is only held for the duration of that function and the |
| 255 |
/// cache value can then be used lock free. |
| 256 |
pub fn get_rev_cache(&self) -> Option<SingleRevisionCache> { |
| 257 |
let mutex_guard = |
| 258 |
self.last_revision_cache.lock().expect("propagate mutex panic"); |
| 259 |
mutex_guard.as_ref().cloned() |
| 260 |
} |
| 261 |
|
| 262 |
/// Signal that we have seen a file this big |
| 263 |
/// |
| 264 |
/// This might update the limit of underlying cache. |
| 265 |
pub fn seen_file_size(&self, size: usize) { |
| 266 |
if let Some(Ok(mut cache)) = |
| 267 |
self.uncompressed_chunk_cache.as_ref().map(|c| c.try_write()) |
| 268 |
{ |
| 269 |
// Dynamically update the uncompressed_chunk_cache size to the |
| 270 |
// largest revision we've seen in this revlog. |
| 271 |
// Do it *before* restoration in case the current revision |
| 272 |
// is the largest. |
| 273 |
let limiter_mut = cache.limiter_mut(); |
| 274 |
let new_max = size; |
| 275 |
limiter_mut.maybe_grow_max(new_max); |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
/// Record the uncompressed raw chunk for rev |
| 280 |
/// |
| 281 |
/// This is a noop if the cache is disabled. |
| 282 |
pub fn record_uncompressed_chunk(&self, rev: Revision, data: RawData) { |
| 283 |
if let Some(Ok(mut cache)) = |
| 284 |
self.uncompressed_chunk_cache.as_ref().map(|c| c.try_write()) |
| 285 |
{ |
| 286 |
cache.insert(rev, data.clone()); |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
/// Return an entry for the null revision |
| 291 |
pub fn make_null_entry(&self) -> RevlogEntry { |
| 292 |
RevlogEntry { |
| 293 |
revlog: self, |
| 294 |
rev: NULL_REVISION, |
| 295 |
uncompressed_len: 0, |
| 296 |
p1: NULL_REVISION, |
| 297 |
p2: NULL_REVISION, |
| 298 |
flags: NULL_REVLOG_ENTRY_FLAGS, |
| 299 |
hash: NULL_NODE, |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
/// Return the [`RevlogEntry`] for a [`Revision`] that is known to exist |
| 304 |
pub fn get_entry(&self, rev: Revision) -> Result<RevlogEntry, RevlogError> { |
| 305 |
if rev == NULL_REVISION { |
| 306 |
return Ok(self.make_null_entry()); |
| 307 |
} |
| 308 |
let index_entry = self.index.get_entry(rev); |
| 309 |
let p1 = |
| 310 |
self.index.check_revision(index_entry.p1()).ok_or_else(|| { |
| 311 |
RevlogError::corrupted(format!("p1 for rev {} is invalid", rev)) |
| 312 |
})?; |
| 313 |
let p2 = |
| 314 |
self.index.check_revision(index_entry.p2()).ok_or_else(|| { |
| 315 |
RevlogError::corrupted(format!("p2 for rev {} is invalid", rev)) |
| 316 |
})?; |
| 317 |
let entry = RevlogEntry { |
| 318 |
revlog: self, |
| 319 |
rev, |
| 320 |
uncompressed_len: index_entry.uncompressed_len(), |
| 321 |
p1, |
| 322 |
p2, |
| 323 |
flags: index_entry.flags(), |
| 324 |
hash: *index_entry.hash(), |
| 325 |
}; |
| 326 |
Ok(entry) |
| 327 |
} |
| 328 |
|
| 329 |
/// Return the [`RevlogEntry`] for `rev`. If `rev` fails to check, this |
| 330 |
/// returns a [`RevlogError`]. |
| 331 |
pub fn get_entry_for_unchecked_rev( |
| 332 |
&self, |
| 333 |
rev: UncheckedRevision, |
| 334 |
) -> Result<RevlogEntry, RevlogError> { |
| 335 |
if rev == NULL_REVISION.into() { |
| 336 |
return Ok(self.make_null_entry()); |
| 337 |
} |
| 338 |
let rev = self.index.check_revision(rev).ok_or_else(|| { |
| 339 |
RevlogError::corrupted(format!("rev {} is invalid", rev)) |
| 340 |
})?; |
| 341 |
self.get_entry(rev) |
| 342 |
} |
| 343 |
|
| 344 |
/// Is the revlog currently delaying the visibility of written data? |
| 345 |
/// |
| 346 |
/// The delaying mechanism can be either in-memory or written on disk in a |
| 347 |
/// side-file. |
| 348 |
pub fn is_delaying(&self) -> bool { |
| 349 |
self.delayed_buffer.is_some() || self.original_index_file.is_some() |
| 350 |
} |
| 351 |
|
| 352 |
/// The offset of the data chunk for this revision |
| 353 |
#[inline(always)] |
| 354 |
pub fn data_start(&self, rev: Revision) -> usize { |
| 355 |
self.index.start(rev, &self.index.get_entry(rev)) |
| 356 |
} |
| 357 |
|
| 358 |
/// The length of the data chunk for this revision |
| 359 |
#[inline(always)] |
| 360 |
pub fn data_compressed_length(&self, rev: Revision) -> usize { |
| 361 |
self.index.get_entry(rev).compressed_len() as usize |
| 362 |
} |
| 363 |
|
| 364 |
/// The end of the data chunk for this revision |
| 365 |
#[inline(always)] |
| 366 |
pub fn data_end(&self, rev: Revision) -> usize { |
| 367 |
self.data_start(rev) + self.data_compressed_length(rev) |
| 368 |
} |
| 369 |
|
| 370 |
/// Return the delta parent of the given revision |
| 371 |
pub fn delta_parent(&self, rev: Revision) -> Revision { |
| 372 |
let base = |
| 373 |
self.index.get_entry(rev).base_revision_or_base_of_delta_chain(); |
| 374 |
if base.0 == rev.0 { |
| 375 |
NULL_REVISION |
| 376 |
} else if self.delta_config.general_delta { |
| 377 |
Revision(base.0) |
| 378 |
} else { |
| 379 |
Revision(rev.0 - 1) |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
/// Return whether `rev` points to a snapshot revision (i.e. does not have |
| 384 |
/// a delta base). |
| 385 |
pub fn is_snapshot(&self, rev: Revision) -> Result<bool, RevlogError> { |
| 386 |
if !self.delta_config.sparse_revlog { |
| 387 |
return Ok(self.delta_parent(rev) == NULL_REVISION); |
| 388 |
} |
| 389 |
self.index.is_snapshot_unchecked(rev) |
| 390 |
} |
| 391 |
|
| 392 |
/// Return the delta chain for `rev` according to this revlog's config. |
| 393 |
/// See [`Index::delta_chain`] for more information. |
| 394 |
pub fn delta_chain( |
| 395 |
&self, |
| 396 |
rev: Revision, |
| 397 |
stop_rev: Option<Revision>, |
| 398 |
) -> Result<(Vec<Revision>, bool), HgError> { |
| 399 |
self.index.delta_chain(rev, stop_rev) |
| 400 |
} |
| 401 |
|
| 402 |
/// Generate a possibly-compressed representation of data. |
| 403 |
/// Returns `None` if the data was not compressed. |
| 404 |
pub fn compress<'data>( |
| 405 |
&self, |
| 406 |
data: &'data [u8], |
| 407 |
) -> Result<Option<Cow<'data, [u8]>>, RevlogError> { |
| 408 |
if data.is_empty() { |
| 409 |
return Ok(Some(data.into())); |
| 410 |
} |
| 411 |
let res = self.compressor.lock().unwrap().compress(data)?; |
| 412 |
if let Some(compressed) = res { |
| 413 |
// The revlog compressor added the header in the returned data. |
| 414 |
return Ok(Some(compressed.into())); |
| 415 |
} |
| 416 |
|
| 417 |
if data[0] == b'\0' { |
| 418 |
return Ok(Some(data.into())); |
| 419 |
} |
| 420 |
Ok(None) |
| 421 |
} |
| 422 |
|
| 423 |
/// Decompress a revlog chunk. |
| 424 |
/// |
| 425 |
/// The chunk is expected to begin with a header identifying the |
| 426 |
/// format type so it can be routed to an appropriate decompressor. |
| 427 |
pub fn decompress<'a>( |
| 428 |
&'a self, |
| 429 |
data: &'a [u8], |
| 430 |
) -> Result<Cow<'a, [u8]>, RevlogError> { |
| 431 |
if data.is_empty() { |
| 432 |
return Ok(data.into()); |
| 433 |
} |
| 434 |
|
| 435 |
// Revlogs are read much more frequently than they are written and many |
| 436 |
// chunks only take microseconds to decompress, so performance is |
| 437 |
// important here. |
| 438 |
|
| 439 |
let header = data[0]; |
| 440 |
match header { |
| 441 |
// Settings don't matter as they only affect compression |
| 442 |
ZLIB_BYTE => Ok(ZlibCompressor::new(0).decompress(data)?.into()), |
| 443 |
// Settings don't matter as they only affect compression |
| 444 |
ZSTD_BYTE => Ok(ZstdCompressor::new(0, 0).decompress(data)?.into()), |
| 445 |
b'\0' => Ok(data.into()), |
| 446 |
b'u' => Ok((&data[1..]).into()), |
| 447 |
other => Err(HgError::unsupported(format!( |
| 448 |
"unknown compression header '{}'", |
| 449 |
other |
| 450 |
)) |
| 451 |
.into()), |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
/// Obtain a segment of raw data corresponding to a range of revisions. |
| 456 |
/// |
| 457 |
/// Requests for data may be satisfied by a cache. |
| 458 |
/// |
| 459 |
/// Returns a 2-tuple of (offset, data) for the requested range of |
| 460 |
/// revisions. Offset is the integer offset from the beginning of the |
| 461 |
/// revlog and data is a slice of the raw byte data. |
| 462 |
/// |
| 463 |
/// Callers will need to call `self.start(rev)` and `self.length(rev)` |
| 464 |
/// to determine where each revision's data begins and ends. |
| 465 |
pub fn get_segment_for_revs( |
| 466 |
&self, |
| 467 |
start_rev: Revision, |
| 468 |
end_rev: Revision, |
| 469 |
) -> Result<(usize, Vec<u8>), HgError> { |
| 470 |
let start = if start_rev == NULL_REVISION { |
| 471 |
0 |
| 472 |
} else { |
| 473 |
let start_entry = self.index.get_entry(start_rev); |
| 474 |
self.index.start(start_rev, &start_entry) |
| 475 |
}; |
| 476 |
let end_entry = self.index.get_entry(end_rev); |
| 477 |
let end = self.index.start(end_rev, &end_entry) |
| 478 |
+ self.data_compressed_length(end_rev); |
| 479 |
|
| 480 |
let length = end - start; |
| 481 |
|
| 482 |
// XXX should we use mmap instead of doing this for platforms that |
| 483 |
// support madvise/populate? |
| 484 |
Ok((start, self.segment_file.read_chunk(start, length)?)) |
| 485 |
} |
| 486 |
|
| 487 |
/// Return the uncompressed raw data for `rev` |
| 488 |
pub fn chunk_for_rev(&self, rev: Revision) -> Result<RawData, HgError> { |
| 489 |
if let Some(Ok(mut cache)) = |
| 490 |
self.uncompressed_chunk_cache.as_ref().map(|c| c.try_write()) |
| 491 |
{ |
| 492 |
if let Some(chunk) = cache.get(&rev) { |
| 493 |
return Ok(chunk.clone()); |
| 494 |
} |
| 495 |
} |
| 496 |
// TODO revlogv2 should check the compression mode |
| 497 |
let data = self.get_segment_for_revs(rev, rev)?.1; |
| 498 |
let uncompressed = self.decompress(&data).map_err(|e| { |
| 499 |
HgError::abort( |
| 500 |
format!("revlog decompression error: {}", e), |
| 501 |
exit_codes::ABORT, |
| 502 |
None, |
| 503 |
) |
| 504 |
})?; |
| 505 |
let uncompressed: RawData = RawData::from(uncompressed.into_owned()); |
| 506 |
self.record_uncompressed_chunk(rev, uncompressed.clone()); |
| 507 |
Ok(uncompressed) |
| 508 |
} |
| 509 |
|
| 510 |
/// Execute `func` within a read context for the data file, meaning that |
| 511 |
/// the read handle will be taken and discarded after the operation. |
| 512 |
pub fn with_read<R>( |
| 513 |
&self, |
| 514 |
func: impl FnOnce() -> Result<R, RevlogError>, |
| 515 |
) -> Result<R, RevlogError> { |
| 516 |
let exit_context = !self.is_open(); |
| 517 |
self.enter_reading_context()?; |
| 518 |
let res = func(); |
| 519 |
if exit_context { |
| 520 |
self.exit_reading_context(); |
| 521 |
} |
| 522 |
res |
| 523 |
} |
| 524 |
|
| 525 |
/// `pub` only for use in hg-pyo3 |
| 526 |
#[doc(hidden)] |
| 527 |
pub fn enter_reading_context(&self) -> Result<(), HgError> { |
| 528 |
if self.is_empty() { |
| 529 |
// Nothing to be read |
| 530 |
return Ok(()); |
| 531 |
} |
| 532 |
if self.delayed_buffer.is_some() && self.is_inline() { |
| 533 |
return Err(HgError::abort( |
| 534 |
"revlog with delayed write should not be inline", |
| 535 |
exit_codes::ABORT, |
| 536 |
None, |
| 537 |
)); |
| 538 |
} |
| 539 |
self.segment_file.get_read_handle()?; |
| 540 |
Ok(()) |
| 541 |
} |
| 542 |
|
| 543 |
/// `pub` only for use in hg-pyo3 |
| 544 |
#[doc(hidden)] |
| 545 |
pub fn exit_reading_context(&self) { |
| 546 |
self.segment_file.exit_reading_context() |
| 547 |
} |
| 548 |
|
| 549 |
/// Fill the buffer returned by `get_buffer` with the possibly un-validated |
| 550 |
/// raw text for a revision. It can be already validated if it comes |
| 551 |
/// from the cache. |
| 552 |
pub fn raw_text<G, T>( |
| 553 |
&self, |
| 554 |
rev: Revision, |
| 555 |
get_buffer: G, |
| 556 |
) -> Result<(), RevlogError> |
| 557 |
where |
| 558 |
G: FnOnce( |
| 559 |
usize, |
| 560 |
&mut dyn FnMut( |
| 561 |
&mut dyn RevisionBuffer<Target = T>, |
| 562 |
) -> Result<(), RevlogError>, |
| 563 |
) -> Result<(), RevlogError>, |
| 564 |
{ |
| 565 |
let entry = &self.get_entry(rev)?; |
| 566 |
let raw_size = entry.uncompressed_len(); |
| 567 |
let cached_rev = self.get_rev_cache(); |
| 568 |
let cache = cached_rev.as_ref().map(|c| c.as_delta_base()); |
| 569 |
if let Some(size) = raw_size { |
| 570 |
self.seen_file_size(u32_u(size)); |
| 571 |
} |
| 572 |
let stop_rev = cache.map(|(r, _)| r); |
| 573 |
let (deltas, stopped) = self.chunks_for_chain(rev, stop_rev)?; |
| 574 |
let (base_text, deltas) = if stopped { |
| 575 |
(cache.expect("last revision should be cached").1, &deltas[..]) |
| 576 |
} else { |
| 577 |
let (buf, deltas) = deltas.split_at(1); |
| 578 |
(buf[0].as_ref(), deltas) |
| 579 |
}; |
| 580 |
let size = entry |
| 581 |
.uncompressed_len() |
| 582 |
.map(|l| l as usize) |
| 583 |
.unwrap_or(base_text.len()); |
| 584 |
get_buffer(size, &mut |buf| { |
| 585 |
patch::build_data_from_deltas(buf, base_text, deltas)?; |
| 586 |
Ok(()) |
| 587 |
})?; |
| 588 |
Ok(()) |
| 589 |
} |
| 590 |
|
| 591 |
/// return a binary delta between two revisions + another delta |
| 592 |
/// |
| 593 |
/// The other delta is applied on rev_2. |
| 594 |
pub fn rev_delta_extra( |
| 595 |
&self, |
| 596 |
rev_1: Revision, |
| 597 |
rev_2: Revision, |
| 598 |
delta: &[u8], |
| 599 |
) -> Result<Vec<u8>, RevlogError> { |
| 600 |
let old_entry = self.get_entry(rev_1)?; |
| 601 |
let old_empty = old_entry.uncompressed_len().is_some_and(|s| s == 0); |
| 602 |
|
| 603 |
if rev_2 == NULL_REVISION || old_empty { |
| 604 |
// restore the full text from the patch |
| 605 |
let base_text = self.get_entry(rev_2)?.data_unchecked()?; |
| 606 |
let d = patch::Delta::new(delta)?; |
| 607 |
let target_size = u_i32(base_text.len()) + d.len_diff(); |
| 608 |
assert!(target_size > 0); |
| 609 |
let target_size = target_size as u32; |
| 610 |
let new_data = d.as_applied(&base_text, 0, target_size); |
| 611 |
|
| 612 |
Ok(if old_empty { |
| 613 |
// if the old version is empty, we can create a trivial "replace |
| 614 |
// all" delta |
| 615 |
let mut delta = vec![]; |
| 616 |
let patch = PlainDeltaPiece { |
| 617 |
start: 0, |
| 618 |
end: 0, |
| 619 |
data: new_data.as_ref(), |
| 620 |
}; |
| 621 |
patch.write(&mut delta); |
| 622 |
delta |
| 623 |
} else { |
| 624 |
// NULL_REVISION don't have a delta chain, this might confuse |
| 625 |
// [`Self::rev_delta_non_null`] So deal with the |
| 626 |
// diffing here. |
| 627 |
assert!(rev_2 == NULL_REVISION); |
| 628 |
let old_data = old_entry.data_unchecked()?; |
| 629 |
if self.revlog_type == RevlogType::Manifestlog { |
| 630 |
manifest::manifest_delta(&old_data, &new_data) |
| 631 |
} else { |
| 632 |
diff::text_delta(&old_data, &new_data) |
| 633 |
} |
| 634 |
}) |
| 635 |
} else { |
| 636 |
assert!( |
| 637 |
!delta.is_empty(), |
| 638 |
"empty delta passed to `rev_delta_extra`" |
| 639 |
); |
| 640 |
self.rev_delta_non_null(rev_1, rev_2, Some(delta)) |
| 641 |
} |
| 642 |
} |
| 643 |
|
| 644 |
/// return a binary delta between two revisions (and an optional extra |
| 645 |
/// delta) |
| 646 |
pub fn rev_delta( |
| 647 |
&self, |
| 648 |
rev_1: Revision, |
| 649 |
rev_2: Revision, |
| 650 |
) -> Result<Vec<u8>, RevlogError> { |
| 651 |
match (rev_1, rev_2) { |
| 652 |
(old, new) if old == new => Ok(vec![]), /* they are the same */ |
| 653 |
// picture |
| 654 |
(old_rev, empty) |
| 655 |
if (self |
| 656 |
.get_entry(empty)? |
| 657 |
.uncompressed_len() |
| 658 |
.is_some_and(|s| s == 0) |
| 659 |
&& self |
| 660 |
.get_entry(old_rev)? |
| 661 |
.uncompressed_len() |
| 662 |
.is_some()) => |
| 663 |
{ |
| 664 |
let mut delta = vec![]; |
| 665 |
let entry = &self.get_entry(old_rev)?; |
| 666 |
let deleted_size = |
| 667 |
entry.uncompressed_len().expect("checked above?"); |
| 668 |
let patch = |
| 669 |
PlainDeltaPiece { start: 0, end: deleted_size, data: &[] }; |
| 670 |
patch.write(&mut delta); |
| 671 |
Ok(delta) |
| 672 |
} |
| 673 |
(empty, new_rev) |
| 674 |
if self |
| 675 |
.get_entry(empty)? |
| 676 |
.uncompressed_len() |
| 677 |
.is_some_and(|s| s == 0) => |
| 678 |
{ |
| 679 |
let mut delta = vec![]; |
| 680 |
let entry = &self.get_entry(new_rev)?; |
| 681 |
let data = entry.data_unchecked()?; |
| 682 |
let patch = |
| 683 |
PlainDeltaPiece { start: 0, end: 0, data: data.as_ref() }; |
| 684 |
patch.write(&mut delta); |
| 685 |
Ok(delta) |
| 686 |
} |
| 687 |
(old, new) => self.rev_delta_non_null(old, new, None), |
| 688 |
} |
| 689 |
} |
| 690 |
|
| 691 |
/// inner part of `rev_delta` involving non null revision |
| 692 |
fn rev_delta_non_null( |
| 693 |
&self, |
| 694 |
rev_1: Revision, |
| 695 |
rev_2: Revision, |
| 696 |
extra_delta: Option<&[u8]>, |
| 697 |
) -> Result<Vec<u8>, RevlogError> { |
| 698 |
// Search for common part in the delta chain of the two revisions |
| 699 |
// |
| 700 |
// We also detect if an optionally cached revision is part of such |
| 701 |
// common part. |
| 702 |
let entry_1 = &self.get_entry(rev_1)?; |
| 703 |
let entry_2 = &self.get_entry(rev_2)?; |
| 704 |
|
| 705 |
let (delta_chain_1, _) = self.delta_chain(rev_1, None)?; |
| 706 |
let (delta_chain_2, _) = self.delta_chain(rev_2, None)?; |
| 707 |
|
| 708 |
let cached_entry = self.get_rev_cache(); |
| 709 |
let cached = cached_entry.as_ref().map(|c| c.as_delta_base()); |
| 710 |
|
| 711 |
let zipped = std::iter::zip(delta_chain_1.iter(), delta_chain_2.iter()); |
| 712 |
let (common_count, cached_idx) = match cached { |
| 713 |
None => (zipped.take_while(|(l, r)| l == r).count(), None), |
| 714 |
Some((cached_rev, _)) => { |
| 715 |
let mut count = 0; |
| 716 |
let mut cached_idx = None; |
| 717 |
for (old_rev, new_rev) in zipped { |
| 718 |
if old_rev != new_rev { |
| 719 |
break; |
| 720 |
} |
| 721 |
if cached_rev == *old_rev && count > 0 { |
| 722 |
cached_idx = Some(count); |
| 723 |
} |
| 724 |
count += 1; |
| 725 |
} |
| 726 |
(count, cached_idx) |
| 727 |
} |
| 728 |
}; |
| 729 |
|
| 730 |
// fast path the identical case |
| 731 |
// |
| 732 |
// This case might happen when the revision are different, the only |
| 733 |
// difference between them are empty delta (that got filtered |
| 734 |
// when building the delta chain. |
| 735 |
let delta = if common_count == delta_chain_1.len() |
| 736 |
&& common_count == delta_chain_2.len() |
| 737 |
{ |
| 738 |
match extra_delta { |
| 739 |
None => vec![], |
| 740 |
Some(delta) => delta.into(), |
| 741 |
} |
| 742 |
} else if common_count == 0 { |
| 743 |
let old_data = entry_1.data_unchecked()?; |
| 744 |
let new_data = if let Some(delta) = extra_delta { |
| 745 |
let base_text = entry_2.data_unchecked()?; |
| 746 |
let d = patch::Delta::new(delta)?; |
| 747 |
let target_size = u_i32(base_text.len()) + d.len_diff(); |
| 748 |
assert!(target_size > 0); |
| 749 |
let target_size = target_size as u32; |
| 750 |
d.as_applied(&base_text, 0, target_size).into() |
| 751 |
} else { |
| 752 |
entry_2.data_unchecked()? |
| 753 |
}; |
| 754 |
// Actually compute the delta we are looking for |
| 755 |
if self.revlog_type == RevlogType::Manifestlog { |
| 756 |
manifest::manifest_delta(&old_data, &new_data) |
| 757 |
} else { |
| 758 |
diff::text_delta(&old_data, &new_data) |
| 759 |
} |
| 760 |
} else if self.revlog_type == RevlogType::Manifestlog { |
| 761 |
let mut state = diff::RevDeltaState::new( |
| 762 |
self, |
| 763 |
cached_entry, |
| 764 |
common_count, |
| 765 |
cached_idx, |
| 766 |
delta_chain_1, |
| 767 |
delta_chain_2, |
| 768 |
extra_delta, |
| 769 |
)?; |
| 770 |
|
| 771 |
let p: diff::Prepared<'_, patch::RichDeltaPiece> = |
| 772 |
state.prepare()?; |
| 773 |
let common_2 = p.common_delta.clone(); |
| 774 |
let new_delta = common_2.combine(p.new_delta); |
| 775 |
let old_delta = p.common_delta.combine(p.old_delta); |
| 776 |
let iter_old = old_delta.into_iter_from_base(p.base_text); |
| 777 |
let iter_new = new_delta.into_iter_from_base(p.base_text); |
| 778 |
manifest::manifest_delta_from_patches(iter_old, iter_new) |
| 779 |
} else { |
| 780 |
let mut state = diff::RevDeltaState::new( |
| 781 |
self, |
| 782 |
cached_entry, |
| 783 |
common_count, |
| 784 |
cached_idx, |
| 785 |
delta_chain_1, |
| 786 |
delta_chain_2, |
| 787 |
extra_delta, |
| 788 |
)?; |
| 789 |
|
| 790 |
let p: diff::Prepared<'_, PlainDeltaPiece> = state.prepare()?; |
| 791 |
|
| 792 |
let common_buff; |
| 793 |
let old_buff; |
| 794 |
let new_buff; |
| 795 |
|
| 796 |
// find the commonly affected part |
| 797 |
let Some((start, end)) = affected_range(&p.old_delta, &p.new_delta) |
| 798 |
else { |
| 799 |
return Ok(vec![]); |
| 800 |
}; |
| 801 |
|
| 802 |
let skipped_size = p.common_size - (end - start); |
| 803 |
|
| 804 |
// build the common part (if ≠from base |
| 805 |
let common_radix: &[u8] = if p.common_delta.is_empty() { |
| 806 |
&p.base_text[u32_u(start)..u32_u(end)] |
| 807 |
} else { |
| 808 |
// TODO: We could only restore the affected windows in the |
| 809 |
// common text. |
| 810 |
// |
| 811 |
// However it means we can no longer cache the result which has |
| 812 |
// a negative effect of some benchmark. |
| 813 |
// Restoring only the windows can have positive effect on |
| 814 |
// benchmark, so it is a worthy pursuit, but it need to be done |
| 815 |
// carefully while considering benchmark for |
| 816 |
// high level operation. |
| 817 |
common_buff = RawData::from(p.common_delta.as_applied( |
| 818 |
p.base_text, |
| 819 |
0, |
| 820 |
p.common_size, |
| 821 |
)); |
| 822 |
self.set_rev_cache_native(p.common_rev, &common_buff); |
| 823 |
&common_buff[u32_u(start)..u32_u(end)] |
| 824 |
}; |
| 825 |
|
| 826 |
// build the old text (if ≠common) |
| 827 |
let old_data = if p.old_delta.is_empty() { |
| 828 |
common_radix |
| 829 |
} else { |
| 830 |
old_buff = p.old_delta.as_applied( |
| 831 |
common_radix, |
| 832 |
start, |
| 833 |
p.old_size - skipped_size, |
| 834 |
); |
| 835 |
&old_buff |
| 836 |
}; |
| 837 |
// build the new text (if ≠common) |
| 838 |
let new_data = if p.new_delta.is_empty() { |
| 839 |
common_radix |
| 840 |
} else { |
| 841 |
new_buff = p.new_delta.as_applied( |
| 842 |
common_radix, |
| 843 |
start, |
| 844 |
p.new_size - skipped_size, |
| 845 |
); |
| 846 |
&new_buff |
| 847 |
}; |
| 848 |
text_delta_with_offset(start, old_data, new_data) |
| 849 |
}; |
| 850 |
Ok(delta) |
| 851 |
} |
| 852 |
|
| 853 |
/// Only `pub` for `hg-pyo3`. |
| 854 |
/// Obtain decompressed raw data for the specified revisions that are |
| 855 |
/// assumed to be in ascending order. |
| 856 |
/// |
| 857 |
/// Returns a list with decompressed data for each requested revision. |
| 858 |
#[doc(hidden)] |
| 859 |
pub fn chunks( |
| 860 |
&self, |
| 861 |
revs: &[Revision], |
| 862 |
target_size: Option<u64>, |
| 863 |
) -> Result<Vec<RawData>, RevlogError> { |
| 864 |
if revs.is_empty() { |
| 865 |
return Ok(vec![]); |
| 866 |
} |
| 867 |
let mut fetched_revs_vec = vec![]; |
| 868 |
let mut chunks = Vec::with_capacity(revs.len()); |
| 869 |
|
| 870 |
let fetched_revs = match self.uncompressed_chunk_cache.as_ref() { |
| 871 |
Some(cache) => { |
| 872 |
if let Ok(mut cache) = cache.try_write() { |
| 873 |
for rev in revs.iter() { |
| 874 |
match cache.get(rev) { |
| 875 |
Some(hit) => chunks.push((*rev, hit.clone())), |
| 876 |
None => fetched_revs_vec.push(*rev), |
| 877 |
} |
| 878 |
} |
| 879 |
&fetched_revs_vec |
| 880 |
} else { |
| 881 |
revs |
| 882 |
} |
| 883 |
} |
| 884 |
None => revs, |
| 885 |
}; |
| 886 |
|
| 887 |
let already_cached = chunks.len(); |
| 888 |
|
| 889 |
let sliced_chunks = if fetched_revs.is_empty() { |
| 890 |
vec![] |
| 891 |
} else if !self.data_config.with_sparse_read || self.is_inline() { |
| 892 |
vec![fetched_revs] |
| 893 |
} else { |
| 894 |
self.slice_chunk(fetched_revs, target_size)? |
| 895 |
}; |
| 896 |
if !sliced_chunks.is_empty() { |
| 897 |
self.with_read(|| { |
| 898 |
for revs_chunk in sliced_chunks { |
| 899 |
let first_rev = revs_chunk[0]; |
| 900 |
// Skip trailing revisions with empty diff |
| 901 |
let last_rev_idx = revs_chunk |
| 902 |
.iter() |
| 903 |
.rposition(|r| self.data_compressed_length(*r) != 0) |
| 904 |
.unwrap_or(revs_chunk.len() - 1); |
| 905 |
|
| 906 |
let last_rev = revs_chunk[last_rev_idx]; |
| 907 |
|
| 908 |
let (offset, data) = |
| 909 |
self.get_segment_for_revs(first_rev, last_rev)?; |
| 910 |
|
| 911 |
let revs_chunk = &revs_chunk[..=last_rev_idx]; |
| 912 |
|
| 913 |
for rev in revs_chunk { |
| 914 |
let chunk_start = self.data_start(*rev); |
| 915 |
let chunk_length = self.data_compressed_length(*rev); |
| 916 |
// TODO revlogv2 should check the compression mode |
| 917 |
let bytes = |
| 918 |
&data[chunk_start - offset..][..chunk_length]; |
| 919 |
let chunk = if !bytes.is_empty() |
| 920 |
&& bytes[0] == ZSTD_BYTE |
| 921 |
{ |
| 922 |
// If we're using `zstd`, we want to try a more |
| 923 |
// specialized decompression |
| 924 |
let entry = self.index.get_entry(*rev); |
| 925 |
let is_delta = entry |
| 926 |
.base_revision_or_base_of_delta_chain() |
| 927 |
!= (*rev).into(); |
| 928 |
let uncompressed = uncompressed_zstd_data( |
| 929 |
bytes, |
| 930 |
is_delta, |
| 931 |
entry.uncompressed_len(), |
| 932 |
)?; |
| 933 |
RawData::from(uncompressed) |
| 934 |
} else { |
| 935 |
// Otherwise just fallback to generic decompression. |
| 936 |
RawData::from(self.decompress(bytes)?) |
| 937 |
}; |
| 938 |
|
| 939 |
chunks.push((*rev, chunk)); |
| 940 |
} |
| 941 |
} |
| 942 |
Ok(()) |
| 943 |
})?; |
| 944 |
|
| 945 |
if let Some(Ok(mut cache)) = |
| 946 |
self.uncompressed_chunk_cache.as_ref().map(|c| c.try_write()) |
| 947 |
{ |
| 948 |
for (rev, chunk) in chunks.iter().skip(already_cached) { |
| 949 |
cache.insert(*rev, chunk.clone()); |
| 950 |
} |
| 951 |
} |
| 952 |
// Use stable sort here since it's *mostly* sorted |
| 953 |
chunks.sort_by(|a, b| a.0.cmp(&b.0)); |
| 954 |
} |
| 955 |
Ok(chunks.into_iter().map(|(_r, chunk)| chunk).collect()) |
| 956 |
} |
| 957 |
|
| 958 |
/// Return the chunks of the delta-chain of a revision |
| 959 |
/// |
| 960 |
/// Only return the chunk for the chain above `cached_rev` if possible. |
| 961 |
/// |
| 962 |
/// return the chunks and a boolean stating if the cached_rev was reached. |
| 963 |
pub(super) fn chunks_for_chain( |
| 964 |
&self, |
| 965 |
rev: Revision, |
| 966 |
cached_rev: Option<Revision>, |
| 967 |
) -> Result<(Vec<RawData>, bool), RevlogError> { |
| 968 |
let (delta_chain, stopped) = self.delta_chain(rev, cached_rev)?; |
| 969 |
// TODO: adjust the target size depending of `stopped` |
| 970 |
let target_size = self |
| 971 |
.get_entry(rev)? |
| 972 |
.uncompressed_len() |
| 973 |
.map(|raw_size| 4 * raw_size as u64); |
| 974 |
let deltas = self.chunks(&delta_chain, target_size)?; |
| 975 |
Ok((deltas, stopped)) |
| 976 |
} |
| 977 |
|
| 978 |
/// Slice revs to reduce the amount of unrelated data to be read from disk. |
| 979 |
/// |
| 980 |
/// ``revs`` is sliced into groups that should be read in one time. |
| 981 |
/// Assume that revs are sorted. |
| 982 |
/// |
| 983 |
/// The initial chunk is sliced until the overall density |
| 984 |
/// (payload/chunks-span ratio) is above |
| 985 |
/// `revlog.data_config.sr_density_threshold`. |
| 986 |
/// No gap smaller than `revlog.data_config.sr_min_gap_size` is skipped. |
| 987 |
/// |
| 988 |
/// If `target_size` is set, no chunk larger than `target_size` |
| 989 |
/// will be returned. |
| 990 |
/// For consistency with other slicing choices, this limit won't go lower |
| 991 |
/// than `revlog.data_config.sr_min_gap_size`. |
| 992 |
/// |
| 993 |
/// If individual revision chunks are larger than this limit, they will |
| 994 |
/// still be raised individually. |
| 995 |
pub fn slice_chunk<'a>( |
| 996 |
&'a self, |
| 997 |
revs: &'a [Revision], |
| 998 |
target_size: Option<u64>, |
| 999 |
) -> Result<Vec<&'a [Revision]>, RevlogError> { |
| 1000 |
let target_size = |
| 1001 |
target_size.map(|size| size.max(self.data_config.sr_min_gap_size)); |
| 1002 |
|
| 1003 |
let target_density = self.data_config.sr_density_threshold; |
| 1004 |
let min_gap_size = self.data_config.sr_min_gap_size as usize; |
| 1005 |
let to_density = self.index.slice_chunk_to_density( |
| 1006 |
revs, |
| 1007 |
target_density, |
| 1008 |
min_gap_size, |
| 1009 |
); |
| 1010 |
|
| 1011 |
let mut sliced = vec![]; |
| 1012 |
|
| 1013 |
for chunk in to_density { |
| 1014 |
sliced.extend( |
| 1015 |
self.slice_chunk_to_size(chunk, target_size)?.into_iter(), |
| 1016 |
); |
| 1017 |
} |
| 1018 |
|
| 1019 |
Ok(sliced) |
| 1020 |
} |
| 1021 |
|
| 1022 |
/// Slice revs to match the target size |
| 1023 |
/// |
| 1024 |
/// This is intended to be used on chunks that density slicing selected, |
| 1025 |
/// but that are still too large compared to the read guarantee of revlogs. |
| 1026 |
/// This might happen when the "minimal gap size" interrupted the slicing |
| 1027 |
/// or when chains are built in a way that create large blocks next to |
| 1028 |
/// each other. |
| 1029 |
fn slice_chunk_to_size<'a>( |
| 1030 |
&self, |
| 1031 |
revs: &'a [Revision], |
| 1032 |
target_size: Option<u64>, |
| 1033 |
) -> Result<Vec<&'a [Revision]>, RevlogError> { |
| 1034 |
let mut start_data = self.data_start(revs[0]); |
| 1035 |
let end_data = self.data_end(revs[revs.len() - 1]); |
| 1036 |
let full_span = end_data - start_data; |
| 1037 |
|
| 1038 |
let nothing_to_do = |
| 1039 |
target_size.map(|size| full_span <= size as usize).unwrap_or(true); |
| 1040 |
|
| 1041 |
if nothing_to_do { |
| 1042 |
return Ok(vec![revs]); |
| 1043 |
} |
| 1044 |
let target_size = target_size.expect("target_size is set") as usize; |
| 1045 |
|
| 1046 |
let mut start_rev_idx = 0; |
| 1047 |
let mut end_rev_idx = 1; |
| 1048 |
let mut chunks = vec![]; |
| 1049 |
|
| 1050 |
for (idx, rev) in revs.iter().enumerate().skip(1) { |
| 1051 |
let span = self.data_end(*rev) - start_data; |
| 1052 |
let is_snapshot = self.is_snapshot(*rev)?; |
| 1053 |
if span <= target_size && is_snapshot { |
| 1054 |
end_rev_idx = idx + 1; |
| 1055 |
} else { |
| 1056 |
let chunk = |
| 1057 |
self.trim_chunk(revs, start_rev_idx, Some(end_rev_idx)); |
| 1058 |
if !chunk.is_empty() { |
| 1059 |
chunks.push(chunk); |
| 1060 |
} |
| 1061 |
start_rev_idx = idx; |
| 1062 |
start_data = self.data_start(*rev); |
| 1063 |
end_rev_idx = idx + 1; |
| 1064 |
} |
| 1065 |
if !is_snapshot { |
| 1066 |
break; |
| 1067 |
} |
| 1068 |
} |
| 1069 |
|
| 1070 |
// For the others, we use binary slicing to quickly converge towards |
| 1071 |
// valid chunks (otherwise, we might end up looking for the start/end |
| 1072 |
// of many revisions). This logic is not looking for the perfect |
| 1073 |
// slicing point, it quickly converges towards valid chunks. |
| 1074 |
let number_of_items = revs.len(); |
| 1075 |
|
| 1076 |
while (end_data - start_data) > target_size { |
| 1077 |
end_rev_idx = number_of_items; |
| 1078 |
if number_of_items - start_rev_idx <= 1 { |
| 1079 |
// Protect against individual chunks larger than the limit |
| 1080 |
break; |
| 1081 |
} |
| 1082 |
let mut local_end_data = self.data_end(revs[end_rev_idx - 1]); |
| 1083 |
let mut span = local_end_data - start_data; |
| 1084 |
while span > target_size { |
| 1085 |
if end_rev_idx - start_rev_idx <= 1 { |
| 1086 |
// Protect against individual chunks larger than the limit |
| 1087 |
break; |
| 1088 |
} |
| 1089 |
end_rev_idx -= (end_rev_idx - start_rev_idx) / 2; |
| 1090 |
local_end_data = self.data_end(revs[end_rev_idx - 1]); |
| 1091 |
span = local_end_data - start_data; |
| 1092 |
} |
| 1093 |
let chunk = self.trim_chunk(revs, start_rev_idx, Some(end_rev_idx)); |
| 1094 |
if !chunk.is_empty() { |
| 1095 |
chunks.push(chunk); |
| 1096 |
} |
| 1097 |
start_rev_idx = end_rev_idx; |
| 1098 |
start_data = self.data_start(revs[start_rev_idx]); |
| 1099 |
} |
| 1100 |
|
| 1101 |
let chunk = self.trim_chunk(revs, start_rev_idx, None); |
| 1102 |
if !chunk.is_empty() { |
| 1103 |
chunks.push(chunk); |
| 1104 |
} |
| 1105 |
|
| 1106 |
Ok(chunks) |
| 1107 |
} |
| 1108 |
|
| 1109 |
/// Returns `revs[startidx..endidx]` without empty trailing revs |
| 1110 |
fn trim_chunk<'a>( |
| 1111 |
&self, |
| 1112 |
revs: &'a [Revision], |
| 1113 |
start_rev_idx: usize, |
| 1114 |
end_rev_idx: Option<usize>, |
| 1115 |
) -> &'a [Revision] { |
| 1116 |
let mut end_rev_idx = end_rev_idx.unwrap_or(revs.len()); |
| 1117 |
|
| 1118 |
// If we have a non-empty delta candidate, there is nothing to trim |
| 1119 |
if revs[end_rev_idx - 1].0 < self.len() as BaseRevision { |
| 1120 |
// Trim empty revs at the end, except the very first rev of a chain |
| 1121 |
while end_rev_idx > 1 |
| 1122 |
&& end_rev_idx > start_rev_idx |
| 1123 |
&& self.data_compressed_length(revs[end_rev_idx - 1]) == 0 |
| 1124 |
{ |
| 1125 |
end_rev_idx -= 1 |
| 1126 |
} |
| 1127 |
} |
| 1128 |
|
| 1129 |
&revs[start_rev_idx..end_rev_idx] |
| 1130 |
} |
| 1131 |
|
| 1132 |
/// Check the hash of some given data against the recorded hash. |
| 1133 |
pub fn check_hash( |
| 1134 |
&self, |
| 1135 |
p1: Revision, |
| 1136 |
p2: Revision, |
| 1137 |
expected: &[u8], |
| 1138 |
data: &[u8], |
| 1139 |
) -> bool { |
| 1140 |
let h1 = self.index.get_entry(p1).hash(); |
| 1141 |
let h2 = self.index.get_entry(p2).hash(); |
| 1142 |
|
| 1143 |
hash(data, h1.as_bytes(), h2.as_bytes()) == expected |
| 1144 |
} |
| 1145 |
|
| 1146 |
/// Returns whether we are currently in a [`Self::with_write`] context |
| 1147 |
pub fn is_writing(&self) -> bool { |
| 1148 |
self.writing_handles.is_some() |
| 1149 |
} |
| 1150 |
|
| 1151 |
/// Open the revlog files for writing |
| 1152 |
/// |
| 1153 |
/// Adding content to a revlog should be done within this context. |
| 1154 |
/// TODO try using `BufRead` and `BufWrite` and see if performance improves |
| 1155 |
pub fn with_write<R>( |
| 1156 |
&mut self, |
| 1157 |
transaction: &mut impl Transaction, |
| 1158 |
data_end: Option<usize>, |
| 1159 |
func: impl FnOnce() -> R, |
| 1160 |
) -> Result<R, HgError> { |
| 1161 |
if self.is_writing() { |
| 1162 |
return Ok(func()); |
| 1163 |
} |
| 1164 |
self.enter_writing_context(data_end, transaction).inspect_err( |
| 1165 |
|_| { |
| 1166 |
self.exit_writing_context(); |
| 1167 |
}, |
| 1168 |
)?; |
| 1169 |
let res = func(); |
| 1170 |
self.exit_writing_context(); |
| 1171 |
Ok(res) |
| 1172 |
} |
| 1173 |
|
| 1174 |
/// `pub` only for use in hg-pyo3 |
| 1175 |
#[doc(hidden)] |
| 1176 |
pub fn exit_writing_context(&mut self) { |
| 1177 |
self.writing_handles.take(); |
| 1178 |
self.segment_file.writing_handle.get().map(|h| h.take()); |
| 1179 |
self.segment_file.reading_handle.get().map(|h| h.take()); |
| 1180 |
} |
| 1181 |
|
| 1182 |
/// `pub` only for use in hg-pyo3 |
| 1183 |
#[doc(hidden)] |
| 1184 |
pub fn python_writing_handles(&self) -> Option<&WriteHandles> { |
| 1185 |
self.writing_handles.as_ref() |
| 1186 |
} |
| 1187 |
|
| 1188 |
/// `pub` only for use in hg-pyo3 |
| 1189 |
#[doc(hidden)] |
| 1190 |
pub fn enter_writing_context( |
| 1191 |
&mut self, |
| 1192 |
data_end: Option<usize>, |
| 1193 |
transaction: &mut impl Transaction, |
| 1194 |
) -> Result<(), HgError> { |
| 1195 |
let data_size = if self.is_empty() { |
| 1196 |
0 |
| 1197 |
} else { |
| 1198 |
self.data_end(Revision((self.len() - 1) as BaseRevision)) |
| 1199 |
}; |
| 1200 |
let mut data_handle = if !self.is_inline() { |
| 1201 |
let data_handle = match self.vfs.open_write(&self.data_file) { |
| 1202 |
Ok(mut f) => { |
| 1203 |
if let Some(end) = data_end { |
| 1204 |
f.seek(SeekFrom::Start(end as u64)) |
| 1205 |
.when_reading_file(&self.data_file)?; |
| 1206 |
} else { |
| 1207 |
f.seek(SeekFrom::End(0)) |
| 1208 |
.when_reading_file(&self.data_file)?; |
| 1209 |
} |
| 1210 |
f |
| 1211 |
} |
| 1212 |
Err(e) => match e { |
| 1213 |
HgError::IoError { error, context, backtrace } => { |
| 1214 |
if error.kind() != ErrorKind::NotFound { |
| 1215 |
return Err(HgError::IoError { |
| 1216 |
error, |
| 1217 |
context, |
| 1218 |
backtrace, |
| 1219 |
}); |
| 1220 |
} |
| 1221 |
self.vfs.create(&self.data_file, true)? |
| 1222 |
} |
| 1223 |
e => return Err(e), |
| 1224 |
}, |
| 1225 |
}; |
| 1226 |
transaction.add(&self.data_file, data_size); |
| 1227 |
Some(FileHandle::from_file( |
| 1228 |
data_handle, |
| 1229 |
dyn_clone::clone_box(&*self.vfs), |
| 1230 |
&self.data_file, |
| 1231 |
)) |
| 1232 |
} else { |
| 1233 |
None |
| 1234 |
}; |
| 1235 |
let index_size = self.len() * INDEX_ENTRY_SIZE; |
| 1236 |
let index_handle = self.index_write_handle()?; |
| 1237 |
if self.is_inline() { |
| 1238 |
transaction.add(&self.index_file, data_size); |
| 1239 |
} else { |
| 1240 |
transaction.add(&self.index_file, index_size); |
| 1241 |
} |
| 1242 |
self.writing_handles = Some(WriteHandles { |
| 1243 |
index_handle: index_handle.try_clone()?, |
| 1244 |
data_handle: if let Some(d) = data_handle.as_mut() { |
| 1245 |
Some(d.try_clone()?) |
| 1246 |
} else { |
| 1247 |
None |
| 1248 |
}, |
| 1249 |
}); |
| 1250 |
*self.segment_file.reading_handle.get_or_default().borrow_mut() = |
| 1251 |
if self.is_inline() { |
| 1252 |
Some(index_handle) |
| 1253 |
} else { |
| 1254 |
data_handle |
| 1255 |
}; |
| 1256 |
Ok(()) |
| 1257 |
} |
| 1258 |
|
| 1259 |
/// Get a write handle to the index, sought to the end of its data. |
| 1260 |
fn index_write_handle(&self) -> Result<FileHandle, HgError> { |
| 1261 |
let res = if self.delayed_buffer.is_none() { |
| 1262 |
if self.data_config.check_ambig { |
| 1263 |
self.vfs.open_check_ambig(&self.index_file) |
| 1264 |
} else { |
| 1265 |
self.vfs.open_write(&self.index_file) |
| 1266 |
} |
| 1267 |
} else { |
| 1268 |
self.vfs.open_write(&self.index_file) |
| 1269 |
}; |
| 1270 |
match res { |
| 1271 |
Ok(mut handle) => { |
| 1272 |
handle |
| 1273 |
.seek(SeekFrom::End(0)) |
| 1274 |
.when_reading_file(&self.index_file)?; |
| 1275 |
Ok(if let Some(delayed_buffer) = self.delayed_buffer.as_ref() { |
| 1276 |
FileHandle::from_file_delayed( |
| 1277 |
handle, |
| 1278 |
dyn_clone::clone_box(&*self.vfs), |
| 1279 |
&self.index_file, |
| 1280 |
delayed_buffer.clone(), |
| 1281 |
)? |
| 1282 |
} else { |
| 1283 |
FileHandle::from_file( |
| 1284 |
handle, |
| 1285 |
dyn_clone::clone_box(&*self.vfs), |
| 1286 |
&self.index_file, |
| 1287 |
) |
| 1288 |
}) |
| 1289 |
} |
| 1290 |
Err(e) => match e { |
| 1291 |
HgError::IoError { error, context, backtrace } => { |
| 1292 |
if error.kind() != ErrorKind::NotFound { |
| 1293 |
return Err(HgError::IoError { |
| 1294 |
error, |
| 1295 |
context, |
| 1296 |
backtrace, |
| 1297 |
}); |
| 1298 |
}; |
| 1299 |
if let Some(delayed_buffer) = self.delayed_buffer.as_ref() { |
| 1300 |
FileHandle::new_delayed( |
| 1301 |
dyn_clone::clone_box(&*self.vfs), |
| 1302 |
&self.index_file, |
| 1303 |
true, |
| 1304 |
delayed_buffer.clone(), |
| 1305 |
) |
| 1306 |
} else { |
| 1307 |
FileHandle::new( |
| 1308 |
dyn_clone::clone_box(&*self.vfs), |
| 1309 |
&self.index_file, |
| 1310 |
true, |
| 1311 |
true, |
| 1312 |
) |
| 1313 |
} |
| 1314 |
} |
| 1315 |
e => Err(e), |
| 1316 |
}, |
| 1317 |
} |
| 1318 |
} |
| 1319 |
|
| 1320 |
/// Split the data of an inline revlog into an index and a data file |
| 1321 |
pub fn split_inline( |
| 1322 |
&mut self, |
| 1323 |
header: IndexHeader, |
| 1324 |
new_index_file_path: Option<PathBuf>, |
| 1325 |
) -> Result<PathBuf, RevlogError> { |
| 1326 |
assert!(self.delayed_buffer.is_none()); |
| 1327 |
let existing_handles = self.writing_handles.is_some(); |
| 1328 |
if let Some(handles) = &mut self.writing_handles { |
| 1329 |
handles.index_handle.flush()?; |
| 1330 |
self.writing_handles.take(); |
| 1331 |
self.segment_file.writing_handle.get().map(|h| h.take()); |
| 1332 |
} |
| 1333 |
let mut new_data_file_handle = |
| 1334 |
self.vfs.create(&self.data_file, true)?; |
| 1335 |
// Drop any potential data, possibly redundant with the VFS impl. |
| 1336 |
new_data_file_handle.set_len(0).when_writing_file(&self.data_file)?; |
| 1337 |
|
| 1338 |
self.with_read(|| -> Result<(), RevlogError> { |
| 1339 |
for r in 0..self.index.len() { |
| 1340 |
let rev = Revision(r as BaseRevision); |
| 1341 |
let rev_segment = self.get_segment_for_revs(rev, rev)?.1; |
| 1342 |
new_data_file_handle |
| 1343 |
.write_all(&rev_segment) |
| 1344 |
.when_writing_file(&self.data_file)?; |
| 1345 |
} |
| 1346 |
new_data_file_handle.flush().when_writing_file(&self.data_file)?; |
| 1347 |
Ok(()) |
| 1348 |
})?; |
| 1349 |
|
| 1350 |
if let Some(index_path) = new_index_file_path { |
| 1351 |
self.index_file = index_path |
| 1352 |
} |
| 1353 |
|
| 1354 |
let mut new_index_handle = self.vfs.create(&self.index_file, true)?; |
| 1355 |
let mut new_data = Vec::with_capacity(self.len() * INDEX_ENTRY_SIZE); |
| 1356 |
for r in 0..self.len() { |
| 1357 |
let rev = Revision(r as BaseRevision); |
| 1358 |
let entry = self.index.entry_binary(rev); |
| 1359 |
if r == 0 { |
| 1360 |
new_data.extend(header.header_bytes); |
| 1361 |
} |
| 1362 |
new_data.extend(entry); |
| 1363 |
} |
| 1364 |
new_index_handle |
| 1365 |
.write_all(&new_data) |
| 1366 |
.when_writing_file(&self.index_file)?; |
| 1367 |
// Replace the index with a new one because the buffer contains inline |
| 1368 |
// data |
| 1369 |
self.index = Index::new(DynBytes::new(Box::new(new_data)), header)?; |
| 1370 |
self.inline = false; |
| 1371 |
|
| 1372 |
self.segment_file = RandomAccessFile::new( |
| 1373 |
dyn_clone::clone_box(&*self.vfs), |
| 1374 |
self.data_file.to_owned(), |
| 1375 |
); |
| 1376 |
if existing_handles { |
| 1377 |
// Switched from inline to conventional, reopen the index |
| 1378 |
let mut new_data_handle = Some(FileHandle::from_file( |
| 1379 |
new_data_file_handle, |
| 1380 |
dyn_clone::clone_box(&*self.vfs), |
| 1381 |
&self.data_file, |
| 1382 |
)); |
| 1383 |
self.writing_handles = Some(WriteHandles { |
| 1384 |
index_handle: self.index_write_handle()?, |
| 1385 |
data_handle: if let Some(d) = new_data_handle.as_mut() { |
| 1386 |
Some(d.try_clone()?) |
| 1387 |
} else { |
| 1388 |
None |
| 1389 |
}, |
| 1390 |
}); |
| 1391 |
*self.segment_file.writing_handle.get_or_default().borrow_mut() = |
| 1392 |
new_data_handle; |
| 1393 |
} |
| 1394 |
|
| 1395 |
Ok(self.index_file.to_owned()) |
| 1396 |
} |
| 1397 |
|
| 1398 |
/// Write a new entry to this revlog. |
| 1399 |
/// - `entry` is the index bytes |
| 1400 |
/// - `header_and_data` is the compression header and the revision data |
| 1401 |
/// - `offset` is the position in the data file to write to |
| 1402 |
/// - `index_end` is the overwritten position in the index in revlog-v2, |
| 1403 |
/// since the format may allow a rewrite of garbage data at the end. |
| 1404 |
/// - `data_end` is the overwritten position in the data-file in revlog-v2, |
| 1405 |
/// since the format may allow a rewrite of garbage data at the end. |
| 1406 |
/// |
| 1407 |
/// XXX Why do we have `data_end` *and* `offset`? Same question in Python |
| 1408 |
pub fn write_entry( |
| 1409 |
&mut self, |
| 1410 |
mut transaction: impl Transaction, |
| 1411 |
entry: &[u8], |
| 1412 |
header_and_data: (&[u8], &[u8]), |
| 1413 |
mut offset: usize, |
| 1414 |
index_end: Option<u64>, |
| 1415 |
data_end: Option<u64>, |
| 1416 |
) -> Result<(u64, Option<u64>), HgError> { |
| 1417 |
let current_revision = self.len() - 1; |
| 1418 |
let canonical_index_file = self.canonical_index_file(); |
| 1419 |
|
| 1420 |
let is_inline = self.is_inline(); |
| 1421 |
let handles = match &mut self.writing_handles { |
| 1422 |
None => { |
| 1423 |
return Err(HgError::abort( |
| 1424 |
"adding revision outside of the `with_write` context", |
| 1425 |
exit_codes::ABORT, |
| 1426 |
None, |
| 1427 |
)); |
| 1428 |
} |
| 1429 |
Some(handles) => handles, |
| 1430 |
}; |
| 1431 |
let index_handle = &mut handles.index_handle; |
| 1432 |
let data_handle = &mut handles.data_handle; |
| 1433 |
if let Some(end) = index_end { |
| 1434 |
index_handle |
| 1435 |
.seek(SeekFrom::Start(end)) |
| 1436 |
.when_reading_file(&self.index_file)?; |
| 1437 |
} else { |
| 1438 |
index_handle |
| 1439 |
.seek(SeekFrom::End(0)) |
| 1440 |
.when_reading_file(&self.index_file)?; |
| 1441 |
} |
| 1442 |
if let Some(data_handle) = data_handle { |
| 1443 |
if let Some(end) = data_end { |
| 1444 |
data_handle |
| 1445 |
.seek(SeekFrom::Start(end)) |
| 1446 |
.when_reading_file(&self.data_file)?; |
| 1447 |
} else { |
| 1448 |
data_handle |
| 1449 |
.seek(SeekFrom::End(0)) |
| 1450 |
.when_reading_file(&self.data_file)?; |
| 1451 |
} |
| 1452 |
} |
| 1453 |
let (header, data) = header_and_data; |
| 1454 |
|
| 1455 |
if !is_inline { |
| 1456 |
transaction.add(&self.data_file, offset); |
| 1457 |
transaction |
| 1458 |
.add(&canonical_index_file, current_revision * entry.len()); |
| 1459 |
let data_handle = data_handle |
| 1460 |
.as_mut() |
| 1461 |
.expect("data handle should exist when not inline"); |
| 1462 |
if !header.is_empty() { |
| 1463 |
data_handle.write_all(header)?; |
| 1464 |
} |
| 1465 |
data_handle.write_all(data)?; |
| 1466 |
match &mut self.delayed_buffer { |
| 1467 |
Some(buf) => { |
| 1468 |
buf.lock() |
| 1469 |
.expect("propagate the panic") |
| 1470 |
.buffer |
| 1471 |
.write_all(entry) |
| 1472 |
.expect("write to delay buffer should succeed"); |
| 1473 |
} |
| 1474 |
None => index_handle.write_all(entry)?, |
| 1475 |
} |
| 1476 |
} else if self.delayed_buffer.is_some() { |
| 1477 |
return Err(HgError::abort( |
| 1478 |
"invalid delayed write on inline revlog", |
| 1479 |
exit_codes::ABORT, |
| 1480 |
None, |
| 1481 |
)); |
| 1482 |
} else { |
| 1483 |
offset += current_revision * entry.len(); |
| 1484 |
transaction.add(&canonical_index_file, offset); |
| 1485 |
index_handle.write_all(entry)?; |
| 1486 |
index_handle.write_all(header)?; |
| 1487 |
index_handle.write_all(data)?; |
| 1488 |
} |
| 1489 |
let data_position = match data_handle { |
| 1490 |
Some(h) => Some(h.position()?), |
| 1491 |
None => None, |
| 1492 |
}; |
| 1493 |
Ok((index_handle.position()?, data_position)) |
| 1494 |
} |
| 1495 |
|
| 1496 |
/// Return the real target index file and not the temporary when diverting |
| 1497 |
pub fn canonical_index_file(&self) -> PathBuf { |
| 1498 |
self.original_index_file |
| 1499 |
.as_ref() |
| 1500 |
.map(ToOwned::to_owned) |
| 1501 |
.unwrap_or_else(|| self.index_file.to_owned()) |
| 1502 |
} |
| 1503 |
|
| 1504 |
/// Return the path to the diverted index |
| 1505 |
fn diverted_index(&self) -> PathBuf { |
| 1506 |
self.index_file.with_extension("i.a") |
| 1507 |
} |
| 1508 |
|
| 1509 |
/// True if we're in a [`Self::with_write`] or [`Self::with_read`] context |
| 1510 |
pub fn is_open(&self) -> bool { |
| 1511 |
self.segment_file.is_open() |
| 1512 |
} |
| 1513 |
|
| 1514 |
/// Set this revlog to delay its writes to a buffer |
| 1515 |
pub fn delay(&mut self) -> Result<Option<PathBuf>, HgError> { |
| 1516 |
assert!(!self.is_open()); |
| 1517 |
if self.is_inline() { |
| 1518 |
return Err(HgError::abort( |
| 1519 |
"revlog with delayed write should not be inline", |
| 1520 |
exit_codes::ABORT, |
| 1521 |
None, |
| 1522 |
)); |
| 1523 |
} |
| 1524 |
if self.delayed_buffer.is_some() || self.original_index_file.is_some() { |
| 1525 |
// Delay or divert already happening |
| 1526 |
return Ok(None); |
| 1527 |
} |
| 1528 |
if self.is_empty() { |
| 1529 |
self.original_index_file = Some(self.index_file.to_owned()); |
| 1530 |
self.index_file = self.diverted_index(); |
| 1531 |
if self.vfs.exists(&self.index_file) { |
| 1532 |
self.vfs.unlink(&self.index_file)?; |
| 1533 |
} |
| 1534 |
Ok(Some(self.index_file.to_owned())) |
| 1535 |
} else { |
| 1536 |
self.delayed_buffer = |
| 1537 |
Some(Arc::new(Mutex::new(DelayedBuffer::default()))); |
| 1538 |
Ok(None) |
| 1539 |
} |
| 1540 |
} |
| 1541 |
|
| 1542 |
/// Write the pending data (in memory) if any to the diverted index file |
| 1543 |
/// (on disk temporary file) |
| 1544 |
pub fn write_pending( |
| 1545 |
&mut self, |
| 1546 |
) -> Result<(Option<PathBuf>, bool), HgError> { |
| 1547 |
assert!(!self.is_open()); |
| 1548 |
if self.is_inline() { |
| 1549 |
return Err(HgError::abort( |
| 1550 |
"revlog with delayed write should not be inline", |
| 1551 |
exit_codes::ABORT, |
| 1552 |
None, |
| 1553 |
)); |
| 1554 |
} |
| 1555 |
if self.original_index_file.is_some() { |
| 1556 |
return Ok((None, true)); |
| 1557 |
} |
| 1558 |
let mut any_pending = false; |
| 1559 |
let pending_index_file = self.diverted_index(); |
| 1560 |
if self.vfs.exists(&pending_index_file) { |
| 1561 |
self.vfs.unlink(&pending_index_file)?; |
| 1562 |
} |
| 1563 |
self.vfs.copy(&self.index_file, &pending_index_file)?; |
| 1564 |
if let Some(delayed_buffer) = self.delayed_buffer.take() { |
| 1565 |
let mut index_file_handle = |
| 1566 |
self.vfs.open_write(&pending_index_file)?; |
| 1567 |
index_file_handle |
| 1568 |
.seek(SeekFrom::End(0)) |
| 1569 |
.when_writing_file(&pending_index_file)?; |
| 1570 |
let delayed_data = |
| 1571 |
&delayed_buffer.lock().expect("propagate the panic").buffer; |
| 1572 |
index_file_handle |
| 1573 |
.write_all(delayed_data) |
| 1574 |
.when_writing_file(&pending_index_file)?; |
| 1575 |
any_pending = true; |
| 1576 |
} |
| 1577 |
self.original_index_file = Some(self.index_file.to_owned()); |
| 1578 |
self.index_file = pending_index_file; |
| 1579 |
Ok((Some(self.index_file.to_owned()), any_pending)) |
| 1580 |
} |
| 1581 |
|
| 1582 |
/// Overwrite the canonical file with the diverted file, or write out the |
| 1583 |
/// delayed buffer. |
| 1584 |
/// Returns an error if the revlog is neither diverted nor delayed. |
| 1585 |
pub fn finalize_pending(&mut self) -> Result<PathBuf, HgError> { |
| 1586 |
assert!(!self.is_open()); |
| 1587 |
if self.is_inline() { |
| 1588 |
return Err(HgError::abort( |
| 1589 |
"revlog with delayed write should not be inline", |
| 1590 |
exit_codes::ABORT, |
| 1591 |
None, |
| 1592 |
)); |
| 1593 |
} |
| 1594 |
match (self.delayed_buffer.as_ref(), self.original_index_file.as_ref()) |
| 1595 |
{ |
| 1596 |
(None, None) => { |
| 1597 |
return Err(HgError::abort( |
| 1598 |
"neither delay nor divert found on this revlog", |
| 1599 |
exit_codes::ABORT, |
| 1600 |
None, |
| 1601 |
)); |
| 1602 |
} |
| 1603 |
(Some(delay), None) => { |
| 1604 |
let mut index_file_handle = |
| 1605 |
self.vfs.open_write(&self.index_file)?; |
| 1606 |
index_file_handle |
| 1607 |
.seek(SeekFrom::End(0)) |
| 1608 |
.when_writing_file(&self.index_file)?; |
| 1609 |
index_file_handle |
| 1610 |
.write_all( |
| 1611 |
&delay.lock().expect("propagate the panic").buffer, |
| 1612 |
) |
| 1613 |
.when_writing_file(&self.index_file)?; |
| 1614 |
self.delayed_buffer = None; |
| 1615 |
} |
| 1616 |
(None, Some(divert)) => { |
| 1617 |
if self.vfs.exists(&self.index_file) { |
| 1618 |
self.vfs.rename(&self.index_file, divert, true)?; |
| 1619 |
} |
| 1620 |
divert.clone_into(&mut self.index_file); |
| 1621 |
self.original_index_file = None; |
| 1622 |
} |
| 1623 |
(Some(_), Some(_)) => unreachable!( |
| 1624 |
"{} is in an inconsistent state of both delay and divert", |
| 1625 |
self.canonical_index_file().display(), |
| 1626 |
), |
| 1627 |
} |
| 1628 |
Ok(self.canonical_index_file()) |
| 1629 |
} |
| 1630 |
|
| 1631 |
/// `pub` only for `hg-pyo3`. This is made a different method than |
| 1632 |
/// [`Revlog::index`] in case there is a different invariant that pops up |
| 1633 |
/// later. |
| 1634 |
#[doc(hidden)] |
| 1635 |
pub fn shared_index(&self) -> &Index { |
| 1636 |
&self.index |
| 1637 |
} |
| 1638 |
|
| 1639 |
/// Whether we can ignore censored revisions **in filelogs only** |
| 1640 |
/// |
| 1641 |
/// # Panics |
| 1642 |
/// |
| 1643 |
/// Panics if [`Self::revlog_type`] != [`RevlogType::Filelog`] |
| 1644 |
pub fn ignore_filelog_censored_revisions(&self) -> bool { |
| 1645 |
assert!(self.revlog_type == RevlogType::Filelog); |
| 1646 |
self.feature_config.ignore_filelog_censored_revisions |
| 1647 |
} |
| 1648 |
|
| 1649 |
/// Finds the unique [`Revision`] whose [`Node`] starts with the given |
| 1650 |
/// binary prefix. |
| 1651 |
/// If no [`Revision`] matches the given prefix, Ok(None) is returned. |
| 1652 |
pub fn rev_from_node_prefix( |
| 1653 |
&self, |
| 1654 |
node_prefix: NodePrefix, |
| 1655 |
) -> Result<Option<Revision>, RevlogError> { |
| 1656 |
self.nodemap |
| 1657 |
.rev_from_node_prefix(&self.index, node_prefix) |
| 1658 |
.map_err(|err| nodemap_error_to_revlog_error(err, node_prefix)) |
| 1659 |
} |
| 1660 |
|
| 1661 |
/// Returns the shortest length in bytes to uniquely identify this [`Node`]. |
| 1662 |
/// If no [`Revision`] matches the given node, `Ok(None)`` is returned. |
| 1663 |
pub fn unique_prefix_len_node( |
| 1664 |
&self, |
| 1665 |
node: super::Node, |
| 1666 |
) -> Result<Option<usize>, RevlogError> { |
| 1667 |
self.nodemap |
| 1668 |
.unique_prefix_len_node(&self.index, &node) |
| 1669 |
.map_err(|err| nodemap_error_to_revlog_error(err, node.into())) |
| 1670 |
} |
| 1671 |
|
| 1672 |
/// `pub` only for `hg-pyo3` |
| 1673 |
/// If `node_tree_opt` is `None`, this creates an empty in-memory nodemap. |
| 1674 |
/// If it's `Some`, it creates a persistent nodemap. |
| 1675 |
#[doc(hidden)] |
| 1676 |
pub fn nodemap_set( |
| 1677 |
&mut self, |
| 1678 |
node_tree_opt: Option<NodeTree>, |
| 1679 |
index_file: PathBuf, |
| 1680 |
) { |
| 1681 |
self.nodemap = |
| 1682 |
RevlogNodeMap::from_nodetree_option(node_tree_opt, index_file) |
| 1683 |
} |
| 1684 |
|
| 1685 |
/// `pub` only for `hg-pyo3` |
| 1686 |
#[doc(hidden)] |
| 1687 |
pub fn nodemap_invalidate(&mut self) -> Result<(), NodeMapError> { |
| 1688 |
self.nodemap.invalidate(&self.index) |
| 1689 |
} |
| 1690 |
|
| 1691 |
/// `pub` only for `hg-pyo3` |
| 1692 |
#[doc(hidden)] |
| 1693 |
pub fn nodemap_incremental_data(&mut self) -> (usize, Vec<u8>) { |
| 1694 |
self.nodemap.incremental_data() |
| 1695 |
} |
| 1696 |
|
| 1697 |
/// `pub` only for `hg-pyo3` |
| 1698 |
/// Appends this new node to the in-memory index and its nodemap. This is |
| 1699 |
/// still needed because some places directly call the index instead of |
| 1700 |
/// going through the [`InnerRevlog`], and that would need a separate |
| 1701 |
/// cleanup. |
| 1702 |
#[doc(hidden)] |
| 1703 |
pub fn index_append( |
| 1704 |
&mut self, |
| 1705 |
params: RevisionDataParams, |
| 1706 |
) -> Result<(), RevlogError> { |
| 1707 |
let node = Node::from(params.node_id); |
| 1708 |
let rev = |
| 1709 |
Revision(self.index.len().try_into().expect("revision too large")); |
| 1710 |
self.index.append(params)?; |
| 1711 |
self.nodemap |
| 1712 |
.insert(&self.index, &node, rev) |
| 1713 |
.map_err(|err| nodemap_error_to_revlog_error(err, node.into())) |
| 1714 |
} |
| 1715 |
} |
| 1716 |
|
| 1717 |
fn nodemap_error_to_revlog_error( |
| 1718 |
err: NodeMapError, |
| 1719 |
node_prefix: NodePrefix, |
| 1720 |
) -> RevlogError { |
| 1721 |
// Pretty awful but no worse than what we had before. This |
| 1722 |
// is being cleaned up in a separate effort for all errors, so we keep it |
| 1723 |
// in a self-contained function |
| 1724 |
match err { |
| 1725 |
NodeMapError::MultipleResults => { |
| 1726 |
RevlogError::AmbiguousPrefix(format!("{:x}", node_prefix)) |
| 1727 |
} |
| 1728 |
NodeMapError::RevisionNotInIndex(rev) => { |
| 1729 |
RevlogError::InvalidRevision(rev.to_string()) |
| 1730 |
} |
| 1731 |
} |
| 1732 |
} |
| 1733 |
|
| 1734 |
/// Encapsulates the state of a revlog's nodemap |
| 1735 |
enum RevlogNodeMapState { |
| 1736 |
/// Non-persistent nodemap, lazily constructed in-memory |
| 1737 |
InMemory { |
| 1738 |
/// How many lookups have failed |
| 1739 |
misses: AtomicUsize, |
| 1740 |
/// The in-memory tree |
| 1741 |
tree: NodeTree, |
| 1742 |
/// The smallest revision number from the index we've cached. This is |
| 1743 |
/// useful because (after a few misses) we lazily fill the nodemap from |
| 1744 |
/// the end, so every subsequent query would start over from the tip if |
| 1745 |
/// we didn't remember this. |
| 1746 |
smallest_cached_rev: Option<Revision>, |
| 1747 |
}, |
| 1748 |
/// Nodemap stored on disk in an append-mostly format |
| 1749 |
Persistent(NodeTree), |
| 1750 |
} |
| 1751 |
|
| 1752 |
/// The nodemap for a given revlog index. It only makes sense to use in the |
| 1753 |
/// context of a single [`InnerRevlog`]. |
| 1754 |
struct RevlogNodeMap { |
| 1755 |
/// Holds the state of the nodemap in a thread-safe manner. Most access |
| 1756 |
/// patterns are reads, so we optimize for it. |
| 1757 |
state: RwLock<RevlogNodeMapState>, |
| 1758 |
/// The canonical index file for the target revlog, for debugging. |
| 1759 |
index_file: PathBuf, |
| 1760 |
} |
| 1761 |
|
| 1762 |
impl std::fmt::Debug for RevlogNodeMap { |
| 1763 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1764 |
f.debug_struct("RevlogNodeMap") |
| 1765 |
.field("index_file", &self.index_file.display()) |
| 1766 |
.finish() |
| 1767 |
} |
| 1768 |
} |
| 1769 |
|
| 1770 |
impl RevlogNodeMap { |
| 1771 |
/// Main insertion method, see [`NodeTree::insert`]. |
| 1772 |
pub fn insert( |
| 1773 |
&self, |
| 1774 |
idx: &impl RevlogIndex, |
| 1775 |
node: &Node, |
| 1776 |
rev: Revision, |
| 1777 |
) -> Result<(), NodeMapError> { |
| 1778 |
let mut state = self.state.write().expect("propagate the panic"); |
| 1779 |
let tree = match state.deref_mut() { |
| 1780 |
RevlogNodeMapState::InMemory { |
| 1781 |
tree, |
| 1782 |
// No need to adjust either of those |
| 1783 |
misses: _, |
| 1784 |
smallest_cached_rev: _, |
| 1785 |
} => tree, |
| 1786 |
RevlogNodeMapState::Persistent(tree) => tree, |
| 1787 |
}; |
| 1788 |
tree.insert(idx, node, rev) |
| 1789 |
} |
| 1790 |
|
| 1791 |
/// Find the unique [`Revision`] whose [`Node`] starts with the given |
| 1792 |
/// binary prefix. The `idx` must be the same one for all invocations |
| 1793 |
/// If no [`Revision`] matches the given prefix, Ok(None) is returned. |
| 1794 |
fn rev_from_node_prefix( |
| 1795 |
&self, |
| 1796 |
idx: &impl RevlogIndex, |
| 1797 |
node_prefix: NodePrefix, |
| 1798 |
) -> Result<Option<Revision>, NodeMapError> { |
| 1799 |
if node_prefix == NULL_NODE { |
| 1800 |
// This ensures we don't count this trivial case as a query |
| 1801 |
return Ok(Some(NULL_REVISION)); |
| 1802 |
} |
| 1803 |
|
| 1804 |
// First check if we have it in cache |
| 1805 |
let (prev_misses, partial_lookup) = |
| 1806 |
match &*self.state.read().expect("propagate the panic") { |
| 1807 |
RevlogNodeMapState::Persistent(node_tree) => { |
| 1808 |
return node_tree.find_bin(idx, node_prefix); |
| 1809 |
} |
| 1810 |
RevlogNodeMapState::InMemory { |
| 1811 |
misses, |
| 1812 |
tree, |
| 1813 |
smallest_cached_rev: _, |
| 1814 |
} => { |
| 1815 |
let partial_lookup = tree.find_bin(idx, node_prefix)?; |
| 1816 |
if node_prefix.nybbles_len() == NULL_NODE.nybbles_len() { |
| 1817 |
if let Some(rev) = partial_lookup { |
| 1818 |
// In-memory cache hit of a full node |
| 1819 |
return Ok(Some(rev)); |
| 1820 |
} |
| 1821 |
} |
| 1822 |
// In-memory cache miss, update the counter. |
| 1823 |
let prev_misses = misses.fetch_add(1, Ordering::Relaxed); |
| 1824 |
// The nodemap is not fully populated, so we can't give |
| 1825 |
// back a prefix answer without scanning the full index. |
| 1826 |
(prev_misses, partial_lookup) |
| 1827 |
} |
| 1828 |
}; |
| 1829 |
|
| 1830 |
// Cache miss: the tree is lazily built for performance reason, so look |
| 1831 |
// for a match in the index |
| 1832 |
if prev_misses <= 3 { |
| 1833 |
// Don't cache revisions we visit yet |
| 1834 |
let noop_visit = |_, _| {}; |
| 1835 |
|
| 1836 |
let opt = |
| 1837 |
idx.rev_from_prefix(node_prefix, noop_visit, None, None)?; |
| 1838 |
if let Some((node, rev)) = opt { |
| 1839 |
// Only cache the exact revision we've asked for |
| 1840 |
self.insert(idx, &node, rev)?; |
| 1841 |
} |
| 1842 |
return Ok(opt.map(|(_, rev)| rev)); |
| 1843 |
} |
| 1844 |
|
| 1845 |
// This revlog is getting queried often: cache every rev we visit |
| 1846 |
let mut state = self.state.write().expect("propagate the panic"); |
| 1847 |
match state.deref_mut() { |
| 1848 |
RevlogNodeMapState::Persistent(_) => { |
| 1849 |
unreachable!("in a partial state") |
| 1850 |
} |
| 1851 |
RevlogNodeMapState::InMemory { |
| 1852 |
misses: _, |
| 1853 |
tree, |
| 1854 |
smallest_cached_rev, |
| 1855 |
} => { |
| 1856 |
let start_rev = *smallest_cached_rev; |
| 1857 |
let visit = |node, rev| { |
| 1858 |
tree.insert(idx, &node, rev).expect("rev must be valid"); |
| 1859 |
// remember where we stopped to not insert top-most |
| 1860 |
// revisions again |
| 1861 |
*smallest_cached_rev = Some(rev); |
| 1862 |
}; |
| 1863 |
let node_rev_pair = idx.rev_from_prefix( |
| 1864 |
node_prefix, |
| 1865 |
visit, |
| 1866 |
start_rev, |
| 1867 |
partial_lookup, |
| 1868 |
)?; |
| 1869 |
match node_rev_pair { |
| 1870 |
Some((_node, revision)) => Ok(Some(revision)), |
| 1871 |
None => Ok(None), |
| 1872 |
} |
| 1873 |
} |
| 1874 |
} |
| 1875 |
} |
| 1876 |
|
| 1877 |
/// Empty the nodemap and return a pair of (`changed`, `new_data`), where |
| 1878 |
/// `changed` is the number of bytes from the readonly part that have been |
| 1879 |
/// masked by the new data (i.e. data added after what was on disk at load |
| 1880 |
/// time). |
| 1881 |
pub fn incremental_data(&self) -> (usize, Vec<u8>) { |
| 1882 |
let mut state = self.state.write().expect("propagate the panic"); |
| 1883 |
let tree = match state.deref_mut() { |
| 1884 |
RevlogNodeMapState::InMemory { |
| 1885 |
misses, |
| 1886 |
tree, |
| 1887 |
smallest_cached_rev, |
| 1888 |
} => { |
| 1889 |
*misses = 0.into(); |
| 1890 |
*smallest_cached_rev = None; |
| 1891 |
tree |
| 1892 |
} |
| 1893 |
RevlogNodeMapState::Persistent(tree) => tree, |
| 1894 |
}; |
| 1895 |
let tree = std::mem::take(tree); |
| 1896 |
let masked_blocks = tree.masked_readonly_blocks(); |
| 1897 |
let (_, data) = tree.into_readonly_and_added_bytes(); |
| 1898 |
let changed = |
| 1899 |
masked_blocks * std::mem::size_of::<super::nodemap::Block>(); |
| 1900 |
(changed, data) |
| 1901 |
} |
| 1902 |
|
| 1903 |
/// Empty the nodemap and if it's persistent, reload it from scratch. |
| 1904 |
pub fn invalidate( |
| 1905 |
&self, |
| 1906 |
idx: &impl RevlogIndex, |
| 1907 |
) -> Result<(), NodeMapError> { |
| 1908 |
let mut state = self.state.write().expect("propagate the panic"); |
| 1909 |
match state.deref_mut() { |
| 1910 |
RevlogNodeMapState::InMemory { |
| 1911 |
misses, |
| 1912 |
tree, |
| 1913 |
smallest_cached_rev, |
| 1914 |
} => { |
| 1915 |
*misses = 0.into(); |
| 1916 |
*smallest_cached_rev = None; |
| 1917 |
// Don't reload if it's in-memory, we don't know future access |
| 1918 |
// patterns. |
| 1919 |
tree.invalidate_all(); |
| 1920 |
Ok(()) |
| 1921 |
} |
| 1922 |
RevlogNodeMapState::Persistent(tree) => { |
| 1923 |
tree.invalidate_all(); |
| 1924 |
tree.catch_up_to_index(idx, NULL_REVISION) |
| 1925 |
} |
| 1926 |
} |
| 1927 |
} |
| 1928 |
|
| 1929 |
/// Internal constructor. |
| 1930 |
/// |
| 1931 |
/// The [`NodeTree`] must be fully populated, or there will be false |
| 1932 |
/// negatives. |
| 1933 |
fn from_nodetree_option( |
| 1934 |
node_tree_opt: Option<NodeTree>, |
| 1935 |
index_file: PathBuf, |
| 1936 |
) -> Self { |
| 1937 |
let state = match node_tree_opt { |
| 1938 |
Some(node_tree) => RevlogNodeMapState::Persistent(node_tree), |
| 1939 |
None => RevlogNodeMapState::InMemory { |
| 1940 |
misses: 0.into(), |
| 1941 |
tree: Default::default(), |
| 1942 |
smallest_cached_rev: None, |
| 1943 |
}, |
| 1944 |
}; |
| 1945 |
Self { index_file, state: RwLock::new(state) } |
| 1946 |
} |
| 1947 |
} |
| 1948 |
|
| 1949 |
impl NodeMap for RevlogNodeMap { |
| 1950 |
fn find_bin( |
| 1951 |
&self, |
| 1952 |
idx: &impl RevlogIndex, |
| 1953 |
prefix: NodePrefix, |
| 1954 |
) -> Result<Option<Revision>, NodeMapError> { |
| 1955 |
self.rev_from_node_prefix(idx, prefix) |
| 1956 |
} |
| 1957 |
|
| 1958 |
fn unique_prefix_len_bin( |
| 1959 |
&self, |
| 1960 |
idx: &impl RevlogIndex, |
| 1961 |
node_prefix: NodePrefix, |
| 1962 |
) -> Result<Option<usize>, NodeMapError> { |
| 1963 |
let mut state = self.state.write().expect("propagate the panic"); |
| 1964 |
let state = state.deref_mut(); |
| 1965 |
match state { |
| 1966 |
RevlogNodeMapState::InMemory { |
| 1967 |
misses: _, |
| 1968 |
tree, |
| 1969 |
smallest_cached_rev, |
| 1970 |
} => { |
| 1971 |
// We need to fully populate the tree to answer this question |
| 1972 |
tree.catch_up_to_index(idx, NULL_REVISION)?; |
| 1973 |
*smallest_cached_rev = Some(NULL_REVISION); |
| 1974 |
tree.unique_prefix_len_bin(idx, node_prefix) |
| 1975 |
} |
| 1976 |
RevlogNodeMapState::Persistent(tree) => { |
| 1977 |
// The persistent nodemap should have been kept up to date |
| 1978 |
tree.unique_prefix_len_bin(idx, node_prefix) |
| 1979 |
} |
| 1980 |
} |
| 1981 |
} |
| 1982 |
} |
| 1983 |
|
| 1984 |
/// Given two delta targeting the same base, find the affected window |
| 1985 |
/// |
| 1986 |
/// This return the start and end offset of section in "base" affected by a |
| 1987 |
/// change in any of the two deltas. Assume that at least one of the delta is |
| 1988 |
/// non-empty. |
| 1989 |
pub(super) fn affected_range<'a, P>( |
| 1990 |
left: &super::patch::Delta<'a, P>, |
| 1991 |
right: &super::patch::Delta<'a, P>, |
| 1992 |
) -> Option<(u32, u32)> |
| 1993 |
where |
| 1994 |
P: DeltaPiece<'a>, |
| 1995 |
{ |
| 1996 |
match (&left.chunks[..], &right.chunks[..]) { |
| 1997 |
([], []) => None, // both delta chain cancelled themself out eventually |
| 1998 |
([], chain) => Some((chain[0].start(), chain[chain.len() - 1].end())), |
| 1999 |
(chain, []) => Some((chain[0].start(), chain[chain.len() - 1].end())), |
| 2000 |
(old_chain, new_chain) => { |
| 2001 |
let start = old_chain[0].start().min(new_chain[0].start()); |
| 2002 |
let end = old_chain[old_chain.len() - 1] |
| 2003 |
.end() |
| 2004 |
.max(new_chain[new_chain.len() - 1].end()); |
| 2005 |
Some((start, end)) |
| 2006 |
} |
| 2007 |
} |
| 2008 |
} |
| 2009 |
|
| 2010 |
type UncompressedChunkCache = |
| 2011 |
RwLock<LruMap<Revision, RawData, ByTotalChunksSize>>; |
| 2012 |
|
| 2013 |
type ForeignBytes = Arc<dyn Deref<Target = [u8]> + Send + Sync>; |
| 2014 |
|
| 2015 |
#[derive(Clone)] |
| 2016 |
enum CachedBytes { |
| 2017 |
Foreign(ForeignBytes), |
| 2018 |
Native(RawData), |
| 2019 |
} |
| 2020 |
|
| 2021 |
impl std::ops::Deref for CachedBytes { |
| 2022 |
type Target = [u8]; |
| 2023 |
|
| 2024 |
fn deref(&self) -> &Self::Target { |
| 2025 |
match self { |
| 2026 |
Self::Foreign(data) => data, |
| 2027 |
Self::Native(data) => data, |
| 2028 |
} |
| 2029 |
} |
| 2030 |
} |
| 2031 |
|
| 2032 |
/// The revision and data for the last revision we've seen. Speeds up |
| 2033 |
/// a lot of sequential operations of the revlog. |
| 2034 |
/// |
| 2035 |
/// The data is not just bytes since it can come from Python and we want to |
| 2036 |
/// avoid copies if possible. |
| 2037 |
#[derive(Clone)] |
| 2038 |
pub struct SingleRevisionCache { |
| 2039 |
pub rev: Revision, |
| 2040 |
data: CachedBytes, |
| 2041 |
} |
| 2042 |
|
| 2043 |
impl SingleRevisionCache { |
| 2044 |
pub(super) fn as_delta_base(&self) -> (Revision, &[u8]) { |
| 2045 |
match &self.data { |
| 2046 |
CachedBytes::Foreign(data) => (self.rev, data.as_ref()), |
| 2047 |
CachedBytes::Native(data) => (self.rev, data.as_ref()), |
| 2048 |
} |
| 2049 |
} |
| 2050 |
|
| 2051 |
/// return a RawData if available |
| 2052 |
pub(super) fn as_data(&self) -> RawData { |
| 2053 |
match &self.data { |
| 2054 |
CachedBytes::Foreign(data) => { |
| 2055 |
let data: &[u8] = data; |
| 2056 |
RawData::from(data) |
| 2057 |
} |
| 2058 |
CachedBytes::Native(data) => data.clone(), |
| 2059 |
} |
| 2060 |
} |
| 2061 |
} |
| 2062 |
|
| 2063 |
impl std::ops::Deref for SingleRevisionCache { |
| 2064 |
type Target = [u8]; |
| 2065 |
|
| 2066 |
fn deref(&self) -> &Self::Target { |
| 2067 |
&self.data |
| 2068 |
} |
| 2069 |
} |
| 2070 |
|
| 2071 |
/// A way of progressively filling a buffer with revision data, then return |
| 2072 |
/// that buffer. Used to abstract away Python-allocated code to reduce copying |
| 2073 |
/// for performance reasons. |
| 2074 |
pub trait RevisionBuffer { |
| 2075 |
/// The owned buffer type to return |
| 2076 |
type Target; |
| 2077 |
/// Copies the slice into the buffer |
| 2078 |
fn extend_from_slice(&mut self, slice: &[u8]); |
| 2079 |
/// Returns the now finished owned buffer |
| 2080 |
fn finish(self) -> Self::Target; |
| 2081 |
} |
| 2082 |
|
| 2083 |
/// A simple vec-based buffer. This is uselessly complicated for the pure Rust |
| 2084 |
/// case, but it's the price to pay for Python compatibility. |
| 2085 |
#[derive(Debug)] |
| 2086 |
pub(super) struct CoreRevisionBuffer { |
| 2087 |
buf: Vec<u8>, |
| 2088 |
} |
| 2089 |
|
| 2090 |
impl CoreRevisionBuffer { |
| 2091 |
pub fn new() -> Self { |
| 2092 |
Self { buf: vec![] } |
| 2093 |
} |
| 2094 |
|
| 2095 |
#[inline] |
| 2096 |
pub fn resize(&mut self, size: usize) { |
| 2097 |
self.buf.reserve_exact(size - self.buf.capacity()); |
| 2098 |
} |
| 2099 |
} |
| 2100 |
|
| 2101 |
impl RevisionBuffer for CoreRevisionBuffer { |
| 2102 |
type Target = Vec<u8>; |
| 2103 |
|
| 2104 |
#[inline] |
| 2105 |
fn extend_from_slice(&mut self, slice: &[u8]) { |
| 2106 |
self.buf.extend_from_slice(slice); |
| 2107 |
} |
| 2108 |
|
| 2109 |
#[inline] |
| 2110 |
fn finish(self) -> Self::Target { |
| 2111 |
self.buf |
| 2112 |
} |
| 2113 |
} |
| 2114 |
|
| 2115 |
/// Calculate the hash of a revision given its data and its parents. |
| 2116 |
pub fn hash( |
| 2117 |
data: &[u8], |
| 2118 |
p1_hash: &[u8], |
| 2119 |
p2_hash: &[u8], |
| 2120 |
) -> [u8; NODE_BYTES_LENGTH] { |
| 2121 |
let mut hasher = Sha1::new(); |
| 2122 |
let (a, b) = (p1_hash, p2_hash); |
| 2123 |
if a > b { |
| 2124 |
hasher.update(b); |
| 2125 |
hasher.update(a); |
| 2126 |
} else { |
| 2127 |
hasher.update(a); |
| 2128 |
hasher.update(b); |
| 2129 |
} |
| 2130 |
hasher.update(data); |
| 2131 |
*hasher.finalize().as_ref() |
| 2132 |
} |
| 2133 |
|
| 2134 |
#[cfg(test)] |
| 2135 |
mod tests { |
| 2136 |
use super::*; |
| 2137 |
|
| 2138 |
const NODE_0: &[u8; 40] = b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"; |
| 2139 |
// different here ^^ |
| 2140 |
const NODE_1: &[u8; 40] = b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabee"; |
| 2141 |
|
| 2142 |
struct FakeIndex([Node; 2]); |
| 2143 |
|
| 2144 |
impl FakeIndex { |
| 2145 |
fn new() -> Self { |
| 2146 |
Self([ |
| 2147 |
Node::from_hex(NODE_0).unwrap(), |
| 2148 |
Node::from_hex(NODE_1).unwrap(), |
| 2149 |
]) |
| 2150 |
} |
| 2151 |
} |
| 2152 |
|
| 2153 |
impl RevlogIndex for FakeIndex { |
| 2154 |
fn len(&self) -> usize { |
| 2155 |
2 |
| 2156 |
} |
| 2157 |
|
| 2158 |
fn node(&self, rev: Revision) -> &Node { |
| 2159 |
&self.0[rev.0 as usize] |
| 2160 |
} |
| 2161 |
} |
| 2162 |
|
| 2163 |
/// Tests that the [`RevlogNodeMap`] behaves correctly when partially built |
| 2164 |
/// in-memory |
| 2165 |
#[test] |
| 2166 |
fn test_revlog_nodemap_basic() { |
| 2167 |
let idx = FakeIndex::new(); |
| 2168 |
let nodemap = RevlogNodeMap::from_nodetree_option(None, PathBuf::new()); |
| 2169 |
// Test exact match first, to populate the nodemap and make sure... |
| 2170 |
assert_eq!( |
| 2171 |
nodemap.rev_from_node_prefix( |
| 2172 |
&idx, |
| 2173 |
NodePrefix::from_hex(NODE_0).unwrap() |
| 2174 |
), |
| 2175 |
Ok(Some(Revision(0))) |
| 2176 |
); |
| 2177 |
// ... no partial match from an in-memory index without scanning the |
| 2178 |
// whole thing. |
| 2179 |
assert_eq!( |
| 2180 |
nodemap.rev_from_node_prefix( |
| 2181 |
&idx, |
| 2182 |
NodePrefix::from_hex(b"abcd").unwrap() |
| 2183 |
), |
| 2184 |
Err(NodeMapError::MultipleResults) |
| 2185 |
); |
| 2186 |
assert_eq!( |
| 2187 |
nodemap.rev_from_node_prefix( |
| 2188 |
&idx, |
| 2189 |
NodePrefix::from_hex( |
| 2190 |
// unambiguous prefix (removed the last byte) |
| 2191 |
b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabc" |
| 2192 |
) |
| 2193 |
.unwrap() |
| 2194 |
), |
| 2195 |
Ok(Some(Revision(0))) |
| 2196 |
); |
| 2197 |
assert_eq!( |
| 2198 |
nodemap.rev_from_node_prefix( |
| 2199 |
&idx, |
| 2200 |
NodePrefix::from_hex(b"abcde").unwrap() |
| 2201 |
), |
| 2202 |
Ok(None) |
| 2203 |
); |
| 2204 |
// Test other exact match |
| 2205 |
assert_eq!( |
| 2206 |
nodemap.rev_from_node_prefix( |
| 2207 |
&idx, |
| 2208 |
NodePrefix::from_hex(NODE_1).unwrap() |
| 2209 |
), |
| 2210 |
Ok(Some(Revision(1))) |
| 2211 |
); |
| 2212 |
// Test full node not matching |
| 2213 |
assert_eq!( |
| 2214 |
nodemap.rev_from_node_prefix( |
| 2215 |
&idx, |
| 2216 |
NodePrefix::from_hex( |
| 2217 |
b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabaa" |
| 2218 |
) |
| 2219 |
.unwrap() |
| 2220 |
), |
| 2221 |
Ok(None) |
| 2222 |
); |
| 2223 |
} |
| 2224 |
|
| 2225 |
/// Test that we don't confuse previous full matches with an unambiguous |
| 2226 |
/// prefix |
| 2227 |
#[test] |
| 2228 |
fn test_revlog_nodemap_prefix() { |
| 2229 |
let idx = FakeIndex::new(); |
| 2230 |
let nodemap = RevlogNodeMap::from_nodetree_option(None, PathBuf::new()); |
| 2231 |
assert_eq!( |
| 2232 |
nodemap.rev_from_node_prefix( |
| 2233 |
&idx, |
| 2234 |
NodePrefix::from_hex(NODE_0).unwrap() |
| 2235 |
), |
| 2236 |
Ok(Some(Revision(0))) |
| 2237 |
); |
| 2238 |
assert_eq!( |
| 2239 |
nodemap.rev_from_node_prefix( |
| 2240 |
&idx, |
| 2241 |
NodePrefix::from_hex( |
| 2242 |
// Missing the last character, but still unambiguous |
| 2243 |
b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabe" |
| 2244 |
) |
| 2245 |
.unwrap() |
| 2246 |
), |
| 2247 |
Ok(Some(Revision(1))) |
| 2248 |
); |
| 2249 |
} |
| 2250 |
} |