| 1 |
//! Safe bindings to bdiff.c. |
| 2 |
|
| 3 |
use std::marker::PhantomData; |
| 4 |
|
| 5 |
use crate::errors::HgError; |
| 6 |
|
| 7 |
/// A file split into lines, ready for diffing. |
| 8 |
pub struct Lines<'a> { |
| 9 |
/// The array of lines, allocated by bdiff.c. |
| 10 |
/// Must never be mutated by Rust code apart from freeing it in `Drop`. |
| 11 |
array: *mut ffi::bdiff_line, |
| 12 |
/// Length of the array. |
| 13 |
len: u32, |
| 14 |
/// Lifetime of the source buffer, since array items store pointers. |
| 15 |
_lifetime: PhantomData<&'a [u8]>, |
| 16 |
} |
| 17 |
|
| 18 |
/// Splits `source` into lines that can be diffed. |
| 19 |
pub fn split_lines(source: &[u8]) -> Result<Lines, HgError> { |
| 20 |
let mut array = std::ptr::null_mut(); |
| 21 |
// Safety: The pointer and length are valid since they both come from |
| 22 |
// `source`, and the out pointer is non-null. |
| 23 |
let result = unsafe { |
| 24 |
ffi::bdiff_splitlines( |
| 25 |
source.as_ptr() as *const std::ffi::c_char, |
| 26 |
source.len() as isize, |
| 27 |
&mut array, |
| 28 |
) |
| 29 |
}; |
| 30 |
match u32::try_from(result) { |
| 31 |
Ok(len) => { |
| 32 |
assert!(!array.is_null()); |
| 33 |
Ok(Lines { array, len, _lifetime: PhantomData }) |
| 34 |
} |
| 35 |
Err(_) => { |
| 36 |
Err(HgError::abort_simple("bdiff_splitlines failed to allocate")) |
| 37 |
} |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
impl<'a> Lines<'a> { |
| 42 |
/// Returns the number of lines. |
| 43 |
pub fn len(&self) -> usize { |
| 44 |
self.len as usize |
| 45 |
} |
| 46 |
|
| 47 |
/// Returns an iterator over the lines. |
| 48 |
pub fn iter(&self) -> LinesIter<'_, 'a> { |
| 49 |
LinesIter { lines: self, index: 0 } |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
impl Drop for Lines<'_> { |
| 54 |
fn drop(&mut self) { |
| 55 |
// Safety: This is the only place that frees the array (no |
| 56 |
// double-free), and it's in a `Drop` impl (no use-after-free). |
| 57 |
unsafe { |
| 58 |
libc::free(self.array as *mut std::ffi::c_void); |
| 59 |
} |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
// Safety: It is safe to send `Lines` to a different thread because |
| 64 |
// `self.array` is never copied so only one thread will free it. |
| 65 |
unsafe impl Send for Lines<'_> {} |
| 66 |
|
| 67 |
// It is *not* safe to share `&Lines` between threads because `ffi::bdiff_diff` |
| 68 |
// mutates lines by storing bookkeeping information in `n` and `e`. |
| 69 |
static_assertions_next::assert_impl!(Lines<'_>: !Sync); |
| 70 |
|
| 71 |
#[derive(Clone)] |
| 72 |
pub struct LinesIter<'a, 'b> { |
| 73 |
lines: &'a Lines<'b>, |
| 74 |
index: usize, |
| 75 |
} |
| 76 |
|
| 77 |
impl<'b> Iterator for LinesIter<'_, 'b> { |
| 78 |
type Item = &'b [u8]; |
| 79 |
|
| 80 |
fn next(&mut self) -> Option<Self::Item> { |
| 81 |
if self.index == self.lines.len() { |
| 82 |
return None; |
| 83 |
} |
| 84 |
// Safety: We just checked that the index has not reached the length. |
| 85 |
let line = unsafe { *self.lines.array.add(self.index) }; |
| 86 |
self.index += 1; |
| 87 |
// Safety: We assume bdiff.c sets `l` and `len` correctly. |
| 88 |
Some(unsafe { |
| 89 |
std::slice::from_raw_parts(line.l as *const u8, line.len as usize) |
| 90 |
}) |
| 91 |
} |
| 92 |
|
| 93 |
fn size_hint(&self) -> (usize, Option<usize>) { |
| 94 |
let len = self.lines.len() - self.index; |
| 95 |
(len, Some(len)) |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
impl ExactSizeIterator for LinesIter<'_, '_> {} |
| 100 |
|
| 101 |
/// A diff hunk comparing lines [a1,a2) in file A with lines [b1,b2) in file B. |
| 102 |
#[derive(Copy, Clone, Debug, PartialEq, Eq)] |
| 103 |
pub struct Hunk { |
| 104 |
/// Start line index in file A (inclusive). |
| 105 |
pub a1: u32, |
| 106 |
/// End line index in file A (exclusive). |
| 107 |
pub a2: u32, |
| 108 |
/// Start line index in file B (inclusive). |
| 109 |
pub b1: u32, |
| 110 |
/// End line index in file B (exclusive). |
| 111 |
pub b2: u32, |
| 112 |
} |
| 113 |
|
| 114 |
/// A list of matching hunks. |
| 115 |
pub struct HunkList { |
| 116 |
/// The head of the linked list, allocated by bdiff.c. |
| 117 |
head: *mut ffi::bdiff_hunk, |
| 118 |
/// Length of the list. |
| 119 |
len: u32, |
| 120 |
} |
| 121 |
|
| 122 |
/// Returns a list of hunks that match in `a` and `b`. |
| 123 |
pub fn diff(a: &Lines, b: &Lines) -> Result<HunkList, HgError> { |
| 124 |
let mut out = ffi::bdiff_hunk { |
| 125 |
a1: 0, |
| 126 |
a2: 0, |
| 127 |
b1: 0, |
| 128 |
b2: 0, |
| 129 |
next: std::ptr::null_mut(), |
| 130 |
}; |
| 131 |
// Safety: We assume bdiff.c sets `array` and `len` correctly; and the |
| 132 |
// out pointer is non-null. |
| 133 |
let result = unsafe { |
| 134 |
ffi::bdiff_diff(a.array, a.len as i32, b.array, b.len as i32, &mut out) |
| 135 |
}; |
| 136 |
match u32::try_from(result) { |
| 137 |
Ok(len) => Ok(HunkList { |
| 138 |
// Start with out.next because the first hunk is not meaningful and |
| 139 |
// is not included in len. This matches mercurial/cffi/bdiff.py. |
| 140 |
head: out.next, |
| 141 |
len, |
| 142 |
}), |
| 143 |
Err(_) => Err(HgError::abort_simple("bdiff_diff failed to allocate")), |
| 144 |
} |
| 145 |
} |
| 146 |
|
| 147 |
impl HunkList { |
| 148 |
/// Returns the number of hunks. |
| 149 |
pub fn len(&self) -> usize { |
| 150 |
self.len as usize |
| 151 |
} |
| 152 |
|
| 153 |
/// Returns an iterator over the hunks. |
| 154 |
pub fn iter(&self) -> HunkListIter { |
| 155 |
HunkListIter { |
| 156 |
// Safety: If `self.head` is null, this is safe. If non-null, then: |
| 157 |
// - We assume bdiff.c made it properly aligned. |
| 158 |
// - It's dereferenceable (any bit pattern is ok for `bdiff_hunk`). |
| 159 |
// - It won't be mutated because `HunkListIter` is tied to `&self`. |
| 160 |
next: unsafe { self.head.as_ref() }, |
| 161 |
remaining: self.len(), |
| 162 |
} |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
impl Drop for HunkList { |
| 167 |
fn drop(&mut self) { |
| 168 |
// Safety: This is the only place that frees `self.head` (no |
| 169 |
// double-free), and it's in a `Drop` impl (no use-after-free). |
| 170 |
unsafe { |
| 171 |
ffi::bdiff_freehunks(self.head); |
| 172 |
} |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
pub struct HunkListIter<'a> { |
| 177 |
next: Option<&'a ffi::bdiff_hunk>, |
| 178 |
remaining: usize, |
| 179 |
} |
| 180 |
|
| 181 |
impl Iterator for HunkListIter<'_> { |
| 182 |
type Item = Hunk; |
| 183 |
|
| 184 |
fn next(&mut self) -> Option<Self::Item> { |
| 185 |
match self.next { |
| 186 |
Some(hunk) => { |
| 187 |
// Safety: Same reasoning as in `HunkList::iter`. |
| 188 |
self.next = unsafe { hunk.next.as_ref() }; |
| 189 |
self.remaining -= 1; |
| 190 |
debug_assert_eq!(hunk.a2 - hunk.a1, hunk.b2 - hunk.b1); |
| 191 |
Some(Hunk { |
| 192 |
a1: hunk.a1 as u32, |
| 193 |
a2: hunk.a2 as u32, |
| 194 |
b1: hunk.b1 as u32, |
| 195 |
b2: hunk.b2 as u32, |
| 196 |
}) |
| 197 |
} |
| 198 |
None => { |
| 199 |
assert_eq!(self.remaining, 0); |
| 200 |
None |
| 201 |
} |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
fn size_hint(&self) -> (usize, Option<usize>) { |
| 206 |
(self.remaining, Some(self.remaining)) |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
impl ExactSizeIterator for HunkListIter<'_> {} |
| 211 |
|
| 212 |
mod ffi { |
| 213 |
#![allow(non_camel_case_types)] |
| 214 |
|
| 215 |
use std::ffi::c_char; |
| 216 |
use std::ffi::c_int; |
| 217 |
|
| 218 |
#[repr(C)] |
| 219 |
#[derive(Debug, Copy, Clone)] |
| 220 |
pub struct bdiff_line { |
| 221 |
pub hash: c_int, |
| 222 |
pub n: c_int, |
| 223 |
pub e: c_int, |
| 224 |
pub len: isize, |
| 225 |
pub l: *const c_char, |
| 226 |
} |
| 227 |
|
| 228 |
#[repr(C)] |
| 229 |
#[derive(Debug, Copy, Clone)] |
| 230 |
pub struct bdiff_hunk { |
| 231 |
pub a1: c_int, |
| 232 |
pub a2: c_int, |
| 233 |
pub b1: c_int, |
| 234 |
pub b2: c_int, |
| 235 |
pub next: *mut bdiff_hunk, |
| 236 |
} |
| 237 |
|
| 238 |
#[link(name = "bdiff", kind = "static")] |
| 239 |
unsafe extern "C" { |
| 240 |
/// Splits `a` into lines. On success, stores a pointer to an array of |
| 241 |
/// lines in `*lr` and returns its length. On failure, returns |
| 242 |
/// -1. The caller is responsible for freeing the array. |
| 243 |
/// |
| 244 |
/// # Safety |
| 245 |
/// |
| 246 |
/// - `a` must point to an array of `len` chars. |
| 247 |
/// - `lr` must be non-null (but `*lr` can be null). |
| 248 |
pub fn bdiff_splitlines( |
| 249 |
a: *const c_char, |
| 250 |
len: isize, |
| 251 |
lr: *mut *mut bdiff_line, |
| 252 |
) -> c_int; |
| 253 |
|
| 254 |
/// Diffs `a` and `b`. On success, stores the head of a linked list of |
| 255 |
/// hunks in `base->next` and returns its length. On failure, returns |
| 256 |
/// -1. The caller is responsible for `bdiff_freehunks(base->next)`. |
| 257 |
/// |
| 258 |
/// # Safety |
| 259 |
/// |
| 260 |
/// - `a` must point to an array of `an` lines. |
| 261 |
/// - `b` must point to an array of `bn` lines. |
| 262 |
/// - `base` must be non-null. |
| 263 |
pub fn bdiff_diff( |
| 264 |
a: *mut bdiff_line, |
| 265 |
an: c_int, |
| 266 |
b: *mut bdiff_line, |
| 267 |
bn: c_int, |
| 268 |
base: *mut bdiff_hunk, |
| 269 |
) -> c_int; |
| 270 |
|
| 271 |
/// Frees the linked list of hunks `l`. |
| 272 |
/// |
| 273 |
/// # Safety |
| 274 |
/// |
| 275 |
/// - `l` must be non-null, not already freed, and not used after this. |
| 276 |
pub fn bdiff_freehunks(l: *mut bdiff_hunk); |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
#[cfg(test)] |
| 281 |
mod tests { |
| 282 |
fn split(a: &[u8]) -> Vec<&[u8]> { |
| 283 |
super::split_lines(a).unwrap().iter().collect() |
| 284 |
} |
| 285 |
|
| 286 |
fn diff(a: &[u8], b: &[u8]) -> Vec<(u32, u32, u32, u32)> { |
| 287 |
let la = super::split_lines(a).unwrap(); |
| 288 |
let lb = super::split_lines(b).unwrap(); |
| 289 |
let hunks = super::diff(&la, &lb).unwrap(); |
| 290 |
hunks.iter().map(|h| (h.a1, h.a2, h.b1, h.b2)).collect() |
| 291 |
} |
| 292 |
|
| 293 |
#[test] |
| 294 |
fn test_split_lines() { |
| 295 |
assert_eq!(split(b""), [] as [&[u8]; 0]); |
| 296 |
assert_eq!(split(b"\n"), [b"\n"]); |
| 297 |
assert_eq!(split(b"\r\n"), [b"\r\n"]); |
| 298 |
assert_eq!(split(b"X\nY"), [b"X\n" as &[u8], b"Y"]); |
| 299 |
assert_eq!(split(b"X\nY\n"), [b"X\n" as &[u8], b"Y\n"]); |
| 300 |
assert_eq!(split(b"X\r\nY\r\n"), [b"X\r\n" as &[u8], b"Y\r\n"]); |
| 301 |
} |
| 302 |
|
| 303 |
#[test] |
| 304 |
fn test_diff_single_line() { |
| 305 |
assert_eq!(diff(b"", b""), &[(0, 0, 0, 0)]); |
| 306 |
assert_eq!(diff(b"x", b"x"), &[(0, 1, 0, 1), (1, 1, 1, 1)]); |
| 307 |
assert_eq!(diff(b"x", b"y"), &[(1, 1, 1, 1)]); |
| 308 |
} |
| 309 |
|
| 310 |
#[test] |
| 311 |
fn test_diff_multiple_lines() { |
| 312 |
assert_eq!( |
| 313 |
diff( |
| 314 |
b" line1 \n line2 \n line3 \n line4 \n REMOVED \n", |
| 315 |
b" ADDED \n line1 \n lined2_CHANGED \n line3 \n line4 \n" |
| 316 |
), |
| 317 |
&[(0, 1, 1, 2), (2, 4, 3, 5), (5, 5, 5, 5)] |
| 318 |
); |
| 319 |
} |
| 320 |
} |