added container_type

This commit is contained in:
Sven Vogel 2023-05-16 15:53:32 +02:00
parent 53dcfcb30b
commit 76eaee60a7
2 changed files with 108 additions and 0 deletions

View File

@ -0,0 +1,8 @@
[package]
name = "container_type"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

100
container_type/src/main.rs Normal file
View File

@ -0,0 +1,100 @@
/**
* _ _ _ _
* __ ___ __(_) |_| |_ ___ _ __ | |__ _ _
* \ \ /\ / / '__| | __| __/ _ \ '_ \ | '_ \| | | |
* \ V V /| | | | |_| || __/ | | | | |_) | |_| |
* \_/\_/ |_| |_|\__|\__\___|_| |_| |_.__/ \__, |
* |___/
* ____ __ __ _
* / ___|_ _____ _ __ \ \ / /__ __ _ ___| |
* \___ \ \ / / _ \ '_ \ \ \ / / _ \ / _` |/ _ \ |
* ___) \ V / __/ | | | \ V / (_) | (_| | __/ |
* |____/ \_/ \___|_| |_| \_/ \___/ \__, |\___|_|
* |___/
* Licensed under the GPLv2 License, Version 2.0 (the "License");
* Copyright (c) Sven Vogel
*/
use std::ops::{Index, IndexMut};
pub struct WeddingCouplePile<A, B> {
couples: Vec<(A, B)>
}
impl<A, B> WeddingCouplePile<A, B> where A: PartialEq {
pub fn new() -> Self {
Self {
couples: Vec::new(),
}
}
pub fn get(&self, key: A) -> Option<&B> {
return if let Some((_, v)) = self.couples.iter().filter(|(k,_)|*k==key).nth(0) {
Some(v)
} else {
None
}
}
pub fn get_mut(&mut self, key: A) -> Option<&mut B> {
return if let Some((_, v)) = self.couples.iter_mut().filter(|(k, _)|*k==key).nth(0) {
Some(v)
} else {
None
}
}
pub fn insert(&mut self, key: A, value: B) {
if let Some((idx, _)) = self.couples.iter().enumerate().filter(|(_, (a, _))| *a == key).nth(0) {
self.couples.insert(idx, (key, value))
} else {
self.couples.push((key, value))
}
}
pub fn remove(&mut self, key: A) -> Option<B> {
return if let Some((idx, _)) = self.couples.iter().enumerate().filter(|(_, (a, _))| *a == key).nth(0) {
Some(self.couples.remove(idx).1)
} else {
None
}
}
}
impl<A, B> Index<A> for WeddingCouplePile<A, B> where A: PartialEq {
type Output=B;
fn index(&self, index: A) -> &Self::Output {
self.get(index).unwrap()
}
}
impl<A, B> IndexMut<A> for WeddingCouplePile<A, B> where A: PartialEq {
fn index_mut(&mut self, index: A) -> &mut Self::Output {
self.get_mut(index).unwrap()
}
}
impl<A, B> IntoIterator for WeddingCouplePile<A, B> {
type Item = (A, B);
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.couples.into_iter()
}
}
fn main() {
let mut couples = WeddingCouplePile::<&str, u64>::new();
couples.insert("Klaus", 0xCafeBabe);
couples.insert("Peter", 0xDeadbeef);
couples["Klaus"] = 0xBadF00d;
for (a, b) in couples.into_iter() {
println!("({a}, {:x})", b);
}
}