From 21a6b0ae5bd279d2372dba90cbeb976d8b5358ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jelmer=20Vernoo=C4=B3?= Date: Sun, 7 Jul 2024 12:24:55 +0100 Subject: [PATCH] Add tests for .as_bytes --- src/patch.rs | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/src/patch.rs b/src/patch.rs index d819e98..c25b029 100644 --- a/src/patch.rs +++ b/src/patch.rs @@ -214,7 +214,7 @@ pub enum HunkLine { } impl HunkLine { - pub fn get_str(&self, leadchar: u8) -> Vec { + fn get_str(&self, leadchar: u8) -> Vec { match self { Self::ContextLine(contents) | Self::InsertLine(contents) @@ -244,12 +244,12 @@ impl HunkLine { pub fn parse_line(line: &[u8]) -> Result { if line.starts_with(b"\n") { Ok(Self::ContextLine(line.to_vec())) - } else if line.starts_with(b" ") { - Ok(Self::ContextLine(line[1..].to_vec())) - } else if line.starts_with(b"+") { - Ok(Self::InsertLine(line[1..].to_vec())) - } else if line.starts_with(b"-") { - Ok(Self::RemoveLine(line[1..].to_vec())) + } else if let Some(line) = line.strip_prefix(b" ") { + Ok(Self::ContextLine(line.to_vec())) + } else if let Some(line) = line.strip_prefix(b"+") { + Ok(Self::InsertLine(line.to_vec())) + } else if let Some(line) = line.strip_prefix(b"-") { + Ok(Self::RemoveLine(line.to_vec())) } else { Err(MalformedLine(line.to_vec())) } @@ -295,6 +295,30 @@ mod hunkline_tests { MalformedLine(b"aaaaa\n".to_vec()) ); } + + #[test] + fn as_bytes() { + assert_eq!( + HunkLine::ContextLine(b"foo\n".to_vec()).as_bytes(), + b" foo\n" + ); + assert_eq!( + HunkLine::InsertLine(b"foo\n".to_vec()).as_bytes(), + b"+foo\n" + ); + assert_eq!( + HunkLine::RemoveLine(b"foo\n".to_vec()).as_bytes(), + b"-foo\n" + ); + } + + #[test] + fn as_bytes_no_nl() { + assert_eq!( + HunkLine::ContextLine(b"foo".to_vec()).as_bytes(), + b" foo\n\\ No newline at end of file\n" + ); + } } #[derive(Clone, Debug, PartialEq, Eq)] @@ -521,4 +545,3 @@ mod parse_range_tests { parse_range("foo").unwrap_err(); } } -