try/check ID functions

This commit is contained in:
Max Bradbury 2020-06-24 18:36:28 +01:00
parent 401bfe4695
commit cbbbcb7196
1 changed files with 32 additions and 1 deletions

View File

@ -145,6 +145,23 @@ fn segments_from_string(string: String) -> Vec<String> {
output
}
/// tries to use an existing ID - if it is already in use, generate a new one
/// then return the ID (either original or new)
/// todo refactor (unnecessary clones etc.)
fn try_id(ids: Vec<String>, id: String) -> String {
let id = id.clone();
let ids = ids.clone();
if is_id_available(&ids, &id) {
id
} else {
new_unique_id(ids)
}
}
fn is_id_available(ids: &Vec<String>, id: &String) -> bool {
! ids.contains(id)
}
/// e.g. pass all tile IDs into this to get a new non-conflicting tile ID
#[inline]
fn new_unique_id(mut ids: Vec<String>) -> String {
@ -188,7 +205,7 @@ impl Unquote for String {
#[cfg(test)]
mod test {
use crate::{from_base36, ToBase36, optional_data_line, mock, segments_from_string, Quote, Unquote, new_unique_id};
use crate::{from_base36, ToBase36, optional_data_line, mock, segments_from_string, Quote, Unquote, new_unique_id, try_id};
#[test]
fn test_from_base36() {
@ -238,6 +255,20 @@ mod test {
assert_eq!(output, expected);
}
#[test]
fn test_try_id() {
// does a conflict generate a new ID?
assert_eq!(
try_id(vec!["0".to_string(), "1".to_string()], "1".to_string()),
"2".to_string()
);
// with no conflict, does the ID remain the same?
assert_eq!(
try_id(vec!["0".to_string(), "1".to_string()], "3".to_string()),
"3".to_string()
);
}
#[test]
fn test_new_unique_id() {
// start