Skip to content

Instantly share code, notes, and snippets.

@saivert
Created May 2, 2024 17:11
Show Gist options
  • Save saivert/4585823aad303b9bdadf7ef665bd3a69 to your computer and use it in GitHub Desktop.
Save saivert/4585823aad303b9bdadf7ef665bd3a69 to your computer and use it in GitHub Desktop.
struct IndexGetter {
current_serial: u32,
tags: Vec<Tag>,
}
#[derive(Clone)]
struct Tag {
pub serial: u32,
pub tag: String,
}
impl IndexGetter {
pub fn new(tags: &[Tag]) -> Self {
Self {
current_serial: 0,
tags: tags.to_vec(),
}
}
pub fn next_serial(&mut self, new_tag: &str) -> u32 {
// Check if new tag matches an old tag, then use its serial
if let Some(old_tag) = self.tags.iter().find(|x| x.tag == new_tag) {
return old_tag.serial;
}
// Skip over other used serials
let mut new_serial = self.current_serial + 1;
for a in &self.tags {
if new_serial == a.serial {
new_serial += 1;
}
}
self.current_serial = new_serial;
self.current_serial
}
}
fn main() {
let tags = vec![
Tag {
serial: 2,
tag: "TAG_A".to_string(),
},
Tag {
serial: 4,
tag: "TAG_B".to_string(),
},
];
let mut getter = IndexGetter::new(&tags);
let new_tags = vec!["TAG_A", "TAG_C", "TAG_B", "TAG_D"];
for new_tag in new_tags {
println!("{}", getter.next_serial(new_tag));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment