mirror of
https://github.com/132nd-vWing/tacview-splitter.git
synced 2026-08-26 11:58:36 +02:00
introduce anyhow, test
This commit is contained in:
+93
-48
@@ -1,24 +1,24 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::Display;
|
||||
use std::hash::Hash;
|
||||
use anyhow::{bail, Context, Result};
|
||||
|
||||
use crate::tacview::{Coalition, CoalitionIDs};
|
||||
|
||||
const COMMENT: char = '#';
|
||||
const MINUS: char = '-';
|
||||
const ZERO: char = '0';
|
||||
const UTF8_BOM: char = '\u{FEFF}'; // byte order mark. a String can begin with that, in which case
|
||||
// we need to discard it.
|
||||
|
||||
pub fn split_into_header_and_body<S>(mut lines: Vec<S>) -> Result<(Vec<S>, Vec<S>), ProcessingError>
|
||||
pub fn split_into_header_and_body<S>(mut lines: Vec<S>) -> Result<(Vec<S>, Vec<S>)>
|
||||
where
|
||||
S: AsRef<str>,
|
||||
S: AsRef<str> + From<String>,
|
||||
{
|
||||
let mut split_idx = 0;
|
||||
for line in &lines {
|
||||
for line in lines.iter() {
|
||||
if line
|
||||
.as_ref()
|
||||
.chars()
|
||||
.next()
|
||||
.ok_or(ProcessingError::CannotSplitIntoHeaderAndBody)?
|
||||
.find(|c| *c != UTF8_BOM)
|
||||
.with_context(|| "found an empty line")?
|
||||
== COMMENT
|
||||
{
|
||||
break;
|
||||
@@ -29,9 +29,9 @@ where
|
||||
Ok((lines, body))
|
||||
}
|
||||
|
||||
pub fn divide_body_by_coalition<S>(body: &[S]) -> Result<Vec<Coalition>, Box<dyn Error>>
|
||||
pub fn divide_body_by_coalition<S>(body: &[S]) -> Result<Vec<Coalition>>
|
||||
where
|
||||
S: AsRef<str> + Hash + Eq,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
let mut result = vec![];
|
||||
let mut coalition_ids: CoalitionIDs = CoalitionIDs::new();
|
||||
@@ -43,9 +43,18 @@ where
|
||||
result.push(processed.coalition.clone());
|
||||
old_line = processed;
|
||||
}
|
||||
sanity_check(&result, body);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn sanity_check<S, T>(v1: &[S], v2: &[T]) {
|
||||
if v1.len() != v2.len() {
|
||||
println!("Warning: data is inconsistent");
|
||||
println!("{}", v1.len());
|
||||
println!("{}", v2.len());
|
||||
}
|
||||
}
|
||||
|
||||
struct Line {
|
||||
line_type: LineType,
|
||||
continued: bool,
|
||||
@@ -57,10 +66,11 @@ impl Line {
|
||||
old_line: Line,
|
||||
current_line: &'a S,
|
||||
coalition_ids: &mut CoalitionIDs<'a>,
|
||||
) -> Result<Self, ProcessingError> {
|
||||
) -> Result<Self> {
|
||||
let line_type = match old_line.continued {
|
||||
true => old_line.line_type,
|
||||
false => LineType::find_type(current_line)?,
|
||||
false => LineType::find_type(current_line)
|
||||
.with_context(|| "could not get line type for this line: {current_line}")?,
|
||||
};
|
||||
|
||||
match line_type {
|
||||
@@ -69,12 +79,17 @@ impl Line {
|
||||
Self::will_line_continue(current_line),
|
||||
Coalition::All,
|
||||
)),
|
||||
LineType::Telemetry => Ok(Line::from_content(line_type, current_line, coalition_ids)?),
|
||||
LineType::Telemetry => Ok(Line::from_content(line_type, current_line, coalition_ids)
|
||||
.with_context(|| "could not parse telemetry line")?),
|
||||
LineType::Timestamp => Ok(Line::new(line_type, false, Coalition::All)),
|
||||
LineType::Destruction => {
|
||||
Ok(Line::from_content(line_type, current_line, coalition_ids)?)
|
||||
}
|
||||
LineType::Unknown => Err(ProcessingError::UnknownLineType),
|
||||
LineType::Destruction => Ok(Line::from_content(line_type, current_line, coalition_ids)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"could not parse this destruction line: {}",
|
||||
current_line.as_ref()
|
||||
)
|
||||
})?),
|
||||
LineType::Unknown => bail!("unknown line type"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +97,7 @@ impl Line {
|
||||
line_type: LineType,
|
||||
current_line: &'a S,
|
||||
coalition_ids: &mut CoalitionIDs<'a>,
|
||||
) -> Result<Self, ProcessingError> {
|
||||
) -> Result<Self> {
|
||||
let id = Self::get_id_from_line(current_line, &line_type)?;
|
||||
let continued = Self::will_line_continue(current_line);
|
||||
let coalition = Self::assign_id_to_coalitions(coalition_ids, current_line, id)
|
||||
@@ -109,21 +124,23 @@ impl Line {
|
||||
current_line.as_ref().ends_with('\\')
|
||||
}
|
||||
|
||||
fn get_id_from_line<'a, S>(
|
||||
line: &'a S,
|
||||
line_type: &LineType,
|
||||
) -> Result<&'a str, ProcessingError>
|
||||
fn get_id_from_line<'a, S>(line: &'a S, line_type: &LineType) -> Result<&'a str>
|
||||
where
|
||||
S: AsRef<str>,
|
||||
{
|
||||
let local_line = line.as_ref();
|
||||
if line_type == &LineType::Destruction {
|
||||
Ok(&local_line[1..local_line.len()])
|
||||
let result = if line_type == &LineType::Destruction {
|
||||
&local_line[1..local_line.len()]
|
||||
} else {
|
||||
Ok(local_line
|
||||
local_line
|
||||
.split_once(',')
|
||||
.ok_or_else(|| ProcessingError::CannotGetIDFromLine(local_line.to_owned()))?
|
||||
.0)
|
||||
.with_context(|| format!("cannot get ID from line {local_line}"))?
|
||||
.0
|
||||
};
|
||||
if result.is_empty() {
|
||||
bail!("cannot get ID from this line\n{local_line}")
|
||||
} else {
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +159,7 @@ impl Default for Line {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone)]
|
||||
#[derive(PartialEq, Clone, Debug)]
|
||||
enum LineType {
|
||||
Unknown,
|
||||
Timestamp,
|
||||
@@ -152,43 +169,71 @@ enum LineType {
|
||||
}
|
||||
|
||||
impl LineType {
|
||||
fn find_type<S: AsRef<str>>(line: &S) -> Result<Self, ProcessingError> {
|
||||
fn find_type<S: AsRef<str>>(line: &S) -> Result<Self> {
|
||||
let first_char = line
|
||||
.as_ref()
|
||||
.chars()
|
||||
.next()
|
||||
.ok_or(ProcessingError::LineIsEmptyError)?;
|
||||
.find(|c| *c != UTF8_BOM)
|
||||
.with_context(|| "line in tacview file is empty")?;
|
||||
let mut buffer: [u8; 4] = [0; 4];
|
||||
first_char.encode_utf8(&mut buffer);
|
||||
if first_char == COMMENT {
|
||||
Ok(Self::Timestamp)
|
||||
} else if first_char == MINUS {
|
||||
Ok(Self::Destruction)
|
||||
} else if first_char == ZERO {
|
||||
Ok(LineType::ArbitraryData)
|
||||
} else if first_char.is_whitespace() {
|
||||
bail!("found line beginning with whitespace")
|
||||
} else {
|
||||
Ok(LineType::Telemetry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ProcessingError {
|
||||
LineIsEmptyError,
|
||||
UnknownLineType,
|
||||
CannotSplitIntoHeaderAndBody,
|
||||
CannotGetIDFromLine(String),
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::{Line, LineType};
|
||||
|
||||
impl Error for ProcessingError {}
|
||||
#[test]
|
||||
fn test_find_type() {
|
||||
assert_eq!(LineType::find_type(&"#0").unwrap(), LineType::Timestamp);
|
||||
assert_eq!(
|
||||
LineType::find_type(&"102,T=5.0785362|6.203").unwrap(),
|
||||
LineType::Telemetry
|
||||
);
|
||||
assert_eq!(LineType::find_type(&"-102").unwrap(), LineType::Destruction);
|
||||
assert_eq!(
|
||||
LineType::find_type(&"0,Authentication").unwrap(),
|
||||
LineType::ArbitraryData
|
||||
);
|
||||
}
|
||||
|
||||
impl Display for ProcessingError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::LineIsEmptyError => write!(f, "line in tacview file is empty"),
|
||||
Self::UnknownLineType => write!(f, "unknown line type in tacview file"),
|
||||
Self::CannotSplitIntoHeaderAndBody => {
|
||||
write!(f, "cannot split the file into header and body")
|
||||
}
|
||||
Self::CannotGetIDFromLine(l) => write!(f, "cannot get unit ID from line: \n{l}"),
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_find_type_for_space() {
|
||||
LineType::find_type(&" ").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_id_from_line() {
|
||||
let lines = vec![
|
||||
("102,T=5.0785362|6.203", "102"),
|
||||
("2d02,T=", "2d02"),
|
||||
("248b02,T=6.70283", "248b02"),
|
||||
];
|
||||
for l in lines {
|
||||
assert_eq!(
|
||||
&Line::get_id_from_line(&l.0, &LineType::Telemetry).unwrap(),
|
||||
&l.1
|
||||
)
|
||||
}
|
||||
let lines = vec![("-102", "102"), ("-2d02", "2d02"), ("-248b02", "248b02")];
|
||||
for l in lines {
|
||||
assert_eq!(
|
||||
&Line::get_id_from_line(&l.0, &LineType::Destruction).unwrap(),
|
||||
&l.1
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user