| 1 |
// Copyright 2019-2020 Georges Racinet <[email protected]> |
| 2 |
// |
| 3 |
// This software may be used and distributed according to the terms of the |
| 4 |
// GNU General Public License version 2 or any later version. |
| 5 |
|
| 6 |
//! Minimal `RevlogIndex`, readable from standard Mercurial file format |
| 7 |
use std::fs::File; |
| 8 |
use std::ops::Deref; |
| 9 |
use std::path::Path; |
| 10 |
use std::slice; |
| 11 |
|
| 12 |
use hg::revlog::node::NULL_NODE; |
| 13 |
use hg::revlog::RevlogIndex; |
| 14 |
use hg::*; |
| 15 |
use memmap2::*; |
| 16 |
|
| 17 |
pub struct Index { |
| 18 |
data: Box<dyn Deref<Target = [IndexEntry]> + Send>, |
| 19 |
} |
| 20 |
|
| 21 |
/// A fixed sized index entry. All numbers are big endian |
| 22 |
#[repr(C)] |
| 23 |
pub struct IndexEntry { |
| 24 |
not_used_yet: [u8; 24], |
| 25 |
p1: Revision, |
| 26 |
p2: Revision, |
| 27 |
node: Node, |
| 28 |
unused_node: [u8; 12], |
| 29 |
} |
| 30 |
|
| 31 |
pub const INDEX_ENTRY_SIZE: usize = 64; |
| 32 |
|
| 33 |
impl IndexEntry { |
| 34 |
fn parents(&self) -> [Revision; 2] { |
| 35 |
[self.p1, self.p2] |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
impl RevlogIndex for Index { |
| 40 |
fn len(&self) -> usize { |
| 41 |
self.data.len() |
| 42 |
} |
| 43 |
|
| 44 |
fn node(&self, rev: Revision) -> &Node { |
| 45 |
if rev == NULL_REVISION { |
| 46 |
return &NULL_NODE; |
| 47 |
} |
| 48 |
&self.data[rev.0 as usize].node |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
impl Graph for &Index { |
| 53 |
fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> { |
| 54 |
let [p1, p2] = self.data[rev.0 as usize].parents(); |
| 55 |
let len = (*self).len(); |
| 56 |
if p1 < NULL_REVISION |
| 57 |
|| p2 < NULL_REVISION |
| 58 |
|| p1.0 as usize >= len |
| 59 |
|| p2.0 as usize >= len |
| 60 |
{ |
| 61 |
return Err(GraphError::ParentOutOfRange(rev)); |
| 62 |
} |
| 63 |
Ok([p1, p2]) |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
struct IndexMmap(Mmap); |
| 68 |
|
| 69 |
impl Deref for IndexMmap { |
| 70 |
type Target = [IndexEntry]; |
| 71 |
|
| 72 |
fn deref(&self) -> &[IndexEntry] { |
| 73 |
let ptr = self.0.as_ptr() as *const IndexEntry; |
| 74 |
// Any misaligned data will be ignored. |
| 75 |
debug_assert_eq!( |
| 76 |
self.0.len() % std::mem::align_of::<IndexEntry>(), |
| 77 |
0, |
| 78 |
"Misaligned data in mmap" |
| 79 |
); |
| 80 |
unsafe { slice::from_raw_parts(ptr, self.0.len() / INDEX_ENTRY_SIZE) } |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
impl Index { |
| 85 |
pub fn load_mmap(path: impl AsRef<Path>) -> Self { |
| 86 |
let file = File::open(path).unwrap(); |
| 87 |
let msg = "Index file is missing, or missing permission"; |
| 88 |
let mmap = unsafe { MmapOptions::new().map(&file) }.expect(msg); |
| 89 |
Self { data: Box::new(IndexMmap(mmap)) } |
| 90 |
} |
| 91 |
} |