From 72a9631b038d1a60e4e4a78e92cd69e6f8ce4316 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Thu, 5 Dec 2019 19:48:37 +0100 Subject: =?UTF-8?q?Move=20arg=20parser=20into=20`FuncArgs`=20and=20create?= =?UTF-8?q?=20(incomplete)=20consistent=20map=20=F0=9F=A7=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/func/map.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/func/map.rs (limited to 'src/func/map.rs') diff --git a/src/func/map.rs b/src/func/map.rs new file mode 100644 index 00000000..880fe3e6 --- /dev/null +++ b/src/func/map.rs @@ -0,0 +1,59 @@ +//! A deduplicating map. + +use std::collections::HashMap; +use std::hash::Hash; + +use crate::syntax::{Spanned, ParseResult}; + +/// A deduplicating map type useful for storing possibly redundant arguments. +#[derive(Debug, Clone, PartialEq)] +pub struct ConsistentMap where K: Hash + Eq { + map: HashMap, +} + +impl ConsistentMap where K: Hash + Eq { + pub fn new() -> ConsistentMap { + ConsistentMap { map: HashMap::new() } + } + + /// Add a key-value pair. + pub fn add(&mut self, key: K, value: V) -> ParseResult<()> { + self.map.insert(key, value); + // TODO + Ok(()) + } + + /// Add a key-value pair if the value is not `None`. + pub fn add_opt(&mut self, key: K, value: Option) -> ParseResult<()> { + Ok(if let Some(value) = value { + self.add(key, value)?; + }) + } + + /// Add a key-spanned-value pair the value is not `None`. + pub fn add_opt_span(&mut self, key: K, value: Option>) -> ParseResult<()> { + Ok(if let Some(spanned) = value { + self.add(key, spanned.v)?; + }) + } + + /// Call a function with the value if the key is present. + pub fn with(&self, key: K, callback: F) where F: FnOnce(&V) { + if let Some(value) = self.map.get(&key) { + callback(value); + } + } + + /// Create a new consistent map where keys and values are mapped to new + /// keys and values. Returns an error if a new key is duplicate. + pub fn dedup(&self, _f: F) -> ParseResult> + where F: FnOnce(K, V) -> ParseResult<(K2, V2)>, K2: Hash + Eq { + // TODO + Ok(ConsistentMap::new()) + } + + /// Iterate over the (key, value) pairs. + pub fn iter(&self) -> std::collections::hash_map::Iter<'_, K, V> { + self.map.iter() + } +} -- cgit v1.2.3