Skip to main content

patchlib/
lib.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5use crate::pattern::PatchLine;
6
7pub mod diff;
8pub mod pattern;
9
10#[derive(Debug, Clone)]
11pub struct DiffHunk {
12    pub old_start: usize,
13    pub old_count: usize,
14    pub new_start: usize,
15    pub new_count: usize,
16    pub lines: Vec<DiffLine>,
17}
18
19#[derive(Debug, Clone, Deserialize, Serialize)]
20pub enum DiffLine {
21    Context(Vec<u8>),
22    Deletion(Vec<u8>),
23    Addition(Vec<u8>),
24}
25
26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
27pub struct HunkHead {
28    old_start: usize,
29    old_count: Option<usize>,
30    new_start: usize,
31    new_count: Option<usize>,
32}
33
34impl fmt::Display for HunkHead {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(f, "@@ -{}", self.old_start)?;
37        if let Some(count) = self.old_count {
38            write!(f, ",{count}")?;
39        }
40        write!(f, " +{}", self.new_start)?;
41        if let Some(count) = self.new_count {
42            write!(f, ",{count}")?;
43        }
44        write!(f, " @@")?;
45        Ok(())
46    }
47}
48
49pub fn parse_data<'a>(data: &'a [u8]) -> Result<Vec<PatchLine<'a>>, String> {
50    let mut lines = Vec::new();
51    for line in data.split(|c| *c == b'\n') {
52        lines.push(pattern::parse_patch_line(line));
53    }
54    Ok(lines)
55}