From eec1c5360b410b5474c9645b07bc273bb3034625 Mon Sep 17 00:00:00 2001 From: Daniel Schadt Date: Tue, 28 Apr 2020 13:17:13 +0200 Subject: restructure how agents are constructed The old function turned a bit into a mess, so the functionality is now split up. --- src/raw/mod.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'src/raw/mod.rs') diff --git a/src/raw/mod.rs b/src/raw/mod.rs index 7451b5a..50ad9b4 100644 --- a/src/raw/mod.rs +++ b/src/raw/mod.rs @@ -18,6 +18,7 @@ pub mod parser; pub use self::parser::{parse_file, Evtc, ParseError, ParseResult}; use std::io::{Read, Seek, BufReader}; +use std::ffi::CStr; /// Parse a complete log that was compressed as a zip file. pub fn parse_zip(input: &mut T) -> ParseResult { @@ -25,3 +26,44 @@ pub fn parse_zip(input: &mut T) -> ParseResult { let mut file = BufReader::new(archive.by_index(0)?); parse_file(&mut file) } + +/// Return a [`CStr`][CStr] up to the first nul byte. +/// +/// This is different to [`CStr::from_bytes_with_nul`][CStr::from_bytes_with_nul] in that it stops +/// at the first nul byte instead of raising an error. +/// +/// If the slice does not end with a nul byte, this function returns `None`. +pub fn cstr_up_to_nul(bytes: &[u8]) -> Option<&CStr> { + let index = bytes.iter().position(|c| *c == 0)?; + CStr::from_bytes_with_nul(&bytes[..index + 1]).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_cstr_up_to_nul_terminated() { + let bytes = b"foo\0"; + let cstr = cstr_up_to_nul(bytes).unwrap(); + assert_eq!(cstr.to_bytes(), b"foo"); + } + + #[test] + fn test_cstr_up_to_nul_multiple() { + let bytes = b"foo\0\0\0"; + let cstr = cstr_up_to_nul(bytes).unwrap(); + assert_eq!(cstr.to_bytes(), b"foo"); + + let bytes = b"foo\0bar\0\0"; + let cstr = cstr_up_to_nul(bytes).unwrap(); + assert_eq!(cstr.to_bytes(), b"foo"); + } + + #[test] + fn test_cstr_up_to_nul_unterminated() { + let bytes = b"foo"; + let cstr = cstr_up_to_nul(bytes); + assert!(cstr.is_none()); + } +} -- cgit v1.2.3