Use proper iterators

This commit is contained in:
ItsDrike 2024-04-18 21:49:14 +02:00
parent e1d70f424e
commit 567da290dd
Signed by: ItsDrike
GPG key ID: FA2745890B7048C0

View file

@ -4,15 +4,30 @@ mod rentry;
const PASTE_NAME: &str = "Hyprland-controversy";
pub struct EditCodeGenerator {
codes: Vec<String>,
index: usize,
pub struct EditCodeGenerator<I>
where
I: Iterator<Item = String>,
{
inner: I,
last_item: Option<String>,
retry: bool,
}
impl EditCodeGenerator {
impl<I> EditCodeGenerator<I>
where
I: Iterator<Item = String>,
{
pub fn new(inner: I) -> Self {
EditCodeGenerator {
inner,
last_item: None,
retry: false,
}
}
pub fn retry_last(&mut self) -> Option<()> {
if self.index > 0 {
self.index -= 1;
if let Some(ref _item) = self.last_item {
self.retry = true;
Some(())
} else {
None
@ -20,29 +35,33 @@ impl EditCodeGenerator {
}
}
impl Default for EditCodeGenerator {
impl<I> Iterator for EditCodeGenerator<I>
where
I: Iterator<Item = String>,
{
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
if self.retry {
self.retry = false;
return self.last_item.clone();
}
let next_item = self.inner.next();
self.last_item = next_item.clone();
next_item
}
}
impl Default for EditCodeGenerator<std::vec::IntoIter<String>> {
fn default() -> Self {
let codes = (b'a'..=b'z')
.map(|c| (c as char).to_string())
.chain((b'A'..=b'Z').map(|c| (c as char).to_string()))
.chain((b'0'..=b'9').map(|c| (c as char).to_string()))
.collect();
.collect::<Vec<_>>();
EditCodeGenerator { codes, index: 0 }
}
}
impl Iterator for EditCodeGenerator {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.codes.len() {
let code = self.codes[self.index].clone();
self.index += 1;
Some(code)
} else {
None
}
EditCodeGenerator::new(codes.into_iter())
}
}