From cbbbcb7196c3b5323f7c519b630c8eaac769b44d Mon Sep 17 00:00:00 2001 From: Max Bradbury Date: Wed, 24 Jun 2020 18:36:28 +0100 Subject: [PATCH] try/check ID functions --- src/lib.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 7fd89ab..3964ef7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -145,6 +145,23 @@ fn segments_from_string(string: String) -> Vec { 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, 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, 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 { @@ -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