summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLars Wirzenius <liw@sequoia-pgp.org>2022-05-01 15:08:46 +0300
committerLars Wirzenius <liw@sequoia-pgp.org>2022-05-01 15:22:56 +0300
commit741ab78ea5e9572614a6dbe4984616bd3451ae74 (patch)
tree1c1405444356418950b6aac166984dfd4c71e9cb
parentb402f3f12e6e94bf3f5efa271ec5ee2137f37c57 (diff)
downloaditer-741ab78ea5e9572614a6dbe4984616bd3451ae74.tar.gz
add container, with placeholder iterator
Sponsored-by: author separate iterator for container items Sponsored-by: author implement iterator Sponsored-by: author Sponsored-by: NLnet Foundation; NGI Assure Sponsored-by: pep.foundation
-rw-r--r--src/main.rs52
1 files changed, 51 insertions, 1 deletions
diff --git a/src/main.rs b/src/main.rs
index e7a11a9..6f9a675 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,53 @@
fn main() {
- println!("Hello, world!");
+ let mut cont: Container<usize> = Container::new();
+ cont.push(42);
+ for v in cont.iter() {
+ println!("{}", v);
+ }
+}
+
+struct Container<T> {
+ items: Vec<T>,
+}
+
+impl<T> Container<T> {
+ fn new() -> Self {
+ Self { items: vec![] }
+ }
+
+ fn push(&mut self, item: T) {
+ self.items.push(item);
+ }
+
+ fn iter<'a>(&'a self) -> ContainerItems<'a, T> {
+ ContainerItems::new(self)
+ }
+}
+
+struct ContainerItems<'a, T> {
+ cont: &'a Container<T>,
+ next: Option<usize>,
+}
+
+impl<'a, T> ContainerItems<'a, T> {
+ fn new(cont: &'a Container<T>) -> Self {
+ Self { cont, next: Some(0) }
+ }
+}
+
+impl<'a, T> Iterator for ContainerItems<'a, T> {
+ type Item = &'a T;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if let Some(i) = self.next {
+ if i < self.cont.items.len() {
+ self.next = Some(i + 1);
+ Some(&self.cont.items[i])
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ }
}