Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rust: rewrite & address #12 #13

Merged
merged 2 commits into from
Jan 17, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 101 additions & 57 deletions rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,6 @@ impl SortingType {
}
}

fn split_once_rest<'a>(s: &'a str, numeric: bool) -> Option<(&str, &str)> {
let loc = s.find(if numeric {
|c: char| c.is_ascii_digit()
} else {
|c: char| !c.is_ascii_digit()
});
if let Some(index) = loc {
Some(s.split_at(index))
} else {
Some((s, ""))
}
}

fn is_semver_prerelease(s: &str) -> bool {
s.len() > 1 && s.starts_with('-')
}
Expand All @@ -46,33 +33,73 @@ fn decompose(str_in: &str) -> VecDeque<SortingType> {
return VecDeque::new();
}

let mut last_numeric = str_in.starts_with(|c: char| c.is_ascii_digit());
let mut s = str_in.to_owned();
let s = if let Some((left, _)) = str_in.split_once('+') {
left
} else {
str_in
};

let mut out: VecDeque<SortingType> = VecDeque::new();
let mut current = String::new();

let mut currently_numeric = s.starts_with(|c: char| c.is_ascii_digit());
let mut skip = s.starts_with('-');

fn handle_split(
current: &str,
c: Option<&char>,
currently_numeric: bool,
) -> Option<SortingType> {
let numeric = if let Some(c) = c {
c.is_ascii_digit()
} else {
false
};

if let Some((left, _)) = s.split_once('+') {
s = left.to_owned();
};
use SortingType::*;

while !s.is_empty() {
if last_numeric {
if let Some((left, right)) = split_once_rest(&s, false) {
out.push_back(SortingType::Numerical(
left.parse::<i64>().unwrap(),
left.to_owned(),
if currently_numeric {
if numeric {
return None;
} else {
return Some(Numerical(
current.parse::<i64>().unwrap(),
current.to_owned(),
));
s = right.to_owned();
last_numeric = false;
}
} else if let Some((left, right)) = split_once_rest(&s, true) {
out.push_back(if is_semver_prerelease(left) {
SortingType::SemverPrerelease(left.to_string())
}

if !(numeric || c == Some(&'-') || c.is_none()) {
return None;
}

if is_semver_prerelease(current) {
if c == Some(&'-') {
// Pre-releases can have multiple dashes
None
} else {
Some(SemverPrerelease(current.to_owned()))
}
} else {
Some(Lexical(current.to_owned()))
}
}

for c in s.chars() {
if let Some(part) = handle_split(&current, Some(&c), currently_numeric) {
if skip {
skip = false;
} else {
SortingType::Lexical(left.to_string())
});
s = right.to_owned();
last_numeric = true;
out.push_back(part);
current.clear();
currently_numeric = c.is_ascii_digit();
}
}
current.push(c);
}

if let Some(part) = handle_split(&current, None, currently_numeric) {
out.push_back(part);
}

out
Expand Down Expand Up @@ -161,19 +188,25 @@ impl Ord for FlexVer<'_> {

#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::fs;
use std::path::PathBuf;

use super::*;

const ENABLED_TESTS: &'static [&str] = &[ "test_vectors.txt" ];
const ENABLED_TESTS: &'static [&str] = &["test_vectors.txt"];

fn test(left: &str, right: &str, expected: Ordering) -> Result<(), String> {
if compare(left, right) != expected {
return Err(format!("Expected {:?} but found {:?}", expected, compare(left, right)));
return Err(format!(
"Expected {:?} but found {:?} ({:?} | {:?})",
expected,
compare(left, right),
decompose(left),
decompose(right)
));
}

// Assert commutativity, if right > left than left < right and vice versa
// Assert commutativity, if right > left than left < right and vice versa
let inverse = match expected {
Less => Greater,
Greater => Less,
Expand All @@ -189,30 +222,41 @@ mod tests {
#[test]
fn standardized_tests() {
let test_folder = PathBuf::from("../test");
let errors = ENABLED_TESTS.iter().flat_map(|test_file_name| {
let test_file = test_folder.join(test_file_name);
fs::read_to_string(test_file).unwrap()
.lines()
.enumerate()
.filter(|(_, line)| !line.starts_with("#"))
.filter(|(_, line)| !line.is_empty())
.map(|(num, line)| {
let split: Vec<&str> = line.split(" ").collect();
if split.len() != 3 { panic!("{}:{} Line formatted incorrectly, expected 2 spaces: {}", test_file_name, num, line) }
let ord = match split[1] {
"<" => Less,
"=" => Equal,
">" => Greater,
_ => panic!("{} is not a valid ordering", split[1])
};
test(split[0], split[2], ord).map_err(|message| (line.to_owned(), message))
}).collect::<Vec<_>>()
let errors = ENABLED_TESTS
.iter()
.flat_map(|test_file_name| {
let test_file = test_folder.join(test_file_name);
fs::read_to_string(test_file)
.unwrap()
.lines()
.enumerate()
.filter(|(_, line)| !line.starts_with("#"))
.filter(|(_, line)| !line.is_empty())
.map(|(num, line)| {
let split: Vec<&str> = line.split(" ").collect();
if split.len() != 3 {
panic!(
"{}:{} Line formatted incorrectly, expected 2 spaces: {}",
test_file_name, num, line
)
}
let ord = match split[1] {
"<" => Less,
"=" => Equal,
">" => Greater,
_ => panic!("{} is not a valid ordering", split[1]),
};
test(split[0], split[2], ord).map_err(|message| (line.to_owned(), message))
})
.collect::<Vec<_>>()
})
.filter_map(|res| res.err())
.collect::<Vec<_>>();

if !errors.is_empty() {
errors.iter().for_each(|(line, message)| println!("{}: {}", line, message));
errors
.iter()
.for_each(|(line, message)| println!("{}: {}", line, message));
panic!()
}
}
Expand Down