werewolves/werewolves-macros/src/hashlist.rs

51 lines
1.7 KiB
Rust
Raw Normal View History

// Copyright (C) 2025-2026 Emilis Bliūdžius
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::collections::HashMap;
use std::hash::Hash;
pub struct HashList<K: Eq + Hash, V>(HashMap<K, Vec<V>>);
impl<K: Eq + Hash + core::fmt::Debug, V: core::fmt::Debug> core::fmt::Debug for HashList<K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("HashList").field(&self.0).finish()
}
}
impl<K: Eq + Hash + Clone, V: Clone> Clone for HashList<K, V> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<K: Eq + Hash, V> HashList<K, V> {
pub fn new() -> Self {
Self(HashMap::new())
}
pub fn add(&mut self, key: K, value: V) {
match self.0.get_mut(&key) {
Some(values) => values.push(value),
None => {
self.0.insert(key, vec![value]);
}
}
}
pub fn decompose(&mut self) -> Box<[(K, Vec<V>)]> {
let mut body = HashMap::new();
core::mem::swap(&mut self.0, &mut body);
body.into_iter().collect()
}
}