clap/src/mkeymap.rs

464 lines
12 KiB
Rust
Raw Normal View History

2018-07-19 14:27:25 +00:00
use build::Arg;
2018-07-19 12:50:47 +00:00
use std::collections::hash_map;
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
2018-07-29 18:20:17 +00:00
use std::ffi::OsString;
2018-07-19 12:50:47 +00:00
use std::hash::{Hash, Hasher};
use std::slice;
// ! rustdoc
2018-07-26 15:15:47 +00:00
#[derive(Default, PartialEq, Debug, Clone)]
pub struct MKeyMap<T> {
2018-07-29 18:20:17 +00:00
keys: HashMap<KeyType, usize>,
value_index: Vec<T>,
2018-07-19 12:50:47 +00:00
values: HashMap<u64, HashSet<usize>>,
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
2018-07-29 18:20:17 +00:00
pub enum KeyType {
2018-07-19 12:50:47 +00:00
Short(char),
2018-07-29 18:20:17 +00:00
Long(OsString),
2018-08-01 15:33:55 +00:00
Position(u64),
2018-07-19 12:50:47 +00:00
}
2018-08-21 00:23:52 +00:00
impl KeyType {
pub(crate) fn is_position(&self) -> bool {
match *self {
KeyType::Position(_) => true,
_ => false,
}
}
pub(crate) fn is_short(&self) -> bool {
match *self {
KeyType::Short(_) => true,
_ => false,
}
}
pub(crate) fn is_long(&self) -> bool {
match *self {
KeyType::Long(_) => true,
_ => false,
}
}
}
impl<T> MKeyMap<T>
where
T: Sized + Hash + PartialEq + Default + Eq,
2018-07-29 18:20:17 +00:00
{
2018-07-19 14:27:25 +00:00
pub fn new() -> Self { MKeyMap::default() }
2018-07-19 12:50:47 +00:00
//TODO ::from(x), ::with_capacity(n) etc
//? set theory ops?
2018-07-29 18:20:17 +00:00
pub fn insert(&mut self, key: KeyType, value: T) -> usize {
2018-07-19 12:50:47 +00:00
let index = self.push(value);
self.keys.insert(key, index);
index
}
2018-07-29 18:20:17 +00:00
pub fn push(&mut self, value: T) -> usize {
2018-07-19 12:50:47 +00:00
let index;
let mut hasher = DefaultHasher::new();
value.hash(&mut hasher);
let hash = hasher.finish();
if let Some((idx, _)) = self.values.get(&hash).and_then(|ids| {
ids.iter()
.map(|&x| (x, &self.value_index[x]))
.find(|(_i, x)| x == &&value)
}) {
2018-08-11 18:32:06 +00:00
debug_assert!(false, "Non-unique value found");
2018-07-19 12:50:47 +00:00
index = idx;
} else {
self.value_index.push(value);
index = self.value_index.len() - 1;
self.values
.entry(hash)
.and_modify(|x| {
x.insert(index);
2018-08-21 00:23:52 +00:00
}).or_insert({
2018-07-19 12:50:47 +00:00
let mut set = HashSet::new();
set.insert(index);
set
});
}
2018-07-24 16:48:24 +00:00
2018-07-19 14:27:25 +00:00
index
2018-07-19 12:50:47 +00:00
}
//TODO ::push_many([x, y])
2018-07-29 18:20:17 +00:00
pub fn insert_key(&mut self, key: KeyType, index: usize) {
2018-07-19 12:50:47 +00:00
if index >= self.values.len() {
panic!("Index out of bounds");
}
self.keys.insert(key, index);
}
//TODO ::insert_keyset([Long, Key2])
2018-07-24 16:48:24 +00:00
// ! Arg mutation functionality
2018-07-29 18:20:17 +00:00
pub fn get(&self, key: KeyType) -> Option<&T> {
2018-07-19 12:50:47 +00:00
self.keys
.get(&key)
.and_then(|&idx| self.value_index.get(idx))
}
//TODO ::get_first([KeyA, KeyB])
2018-07-29 18:20:17 +00:00
pub fn get_mut(&mut self, key: KeyType) -> Option<&mut T> {
2018-07-24 16:48:24 +00:00
if let Some(&idx) = self.keys.get(&key) {
self.value_index.get_mut(idx)
} else {
None
}
2018-07-19 12:50:47 +00:00
}
2018-07-19 14:27:25 +00:00
pub fn is_empty(&self) -> bool { self.keys.is_empty() && self.values.is_empty() }
2018-07-19 12:50:47 +00:00
2018-08-11 17:34:40 +00:00
pub fn remove_by_name(&mut self, _name: &str) -> Option<T> { unimplemented!() }
2018-07-29 18:20:17 +00:00
2018-08-11 17:34:40 +00:00
pub fn remove(&mut self, _key: KeyType) -> Option<T> { unimplemented!() }
2018-07-19 12:50:47 +00:00
//TODO ::remove_many([KeyA, KeyB])
//? probably shouldn't add a possibility for removal?
//? or remove by replacement by some dummy object, so the order is preserved
2018-08-01 15:33:55 +00:00
pub fn remove_key(&mut self, key: KeyType) { self.keys.remove(&key); }
2018-07-19 12:50:47 +00:00
//TODO ::remove_keys([KeyA, KeyB])
2018-07-29 18:20:17 +00:00
pub fn keys(&self) -> Keys<usize> {
2018-07-19 12:50:47 +00:00
Keys {
iter: self.keys.keys(),
}
}
pub fn values(&self) -> Values<T> {
2018-07-19 12:50:47 +00:00
Values {
iter: self.value_index.iter(),
}
}
pub fn values_mut(&mut self) -> ValuesMut<T> {
2018-07-19 12:50:47 +00:00
ValuesMut {
iter: self.value_index.iter_mut(),
}
}
2018-07-19 14:27:25 +00:00
2018-07-29 18:20:17 +00:00
pub fn iter(&self) -> Iter<T> {
2018-07-19 14:27:25 +00:00
Iter {
map: self,
keys: self.keys(),
}
}
2018-07-19 12:50:47 +00:00
}
2018-08-01 15:33:55 +00:00
impl<'a, 'b> MKeyMap<Arg<'a, 'b>> {
pub fn insert_key_by_name(&mut self, key: KeyType, name: &str) {
let index = self.find_by_name(name);
self.keys.insert(key, index);
}
pub fn make_entries(&mut self, arg: Arg<'a, 'b>) -> usize {
let short = arg.short.map(|c| KeyType::Short(c));
let positional = arg.index.map(|n| KeyType::Position(n));
let mut longs = arg
.aliases
.clone()
.map(|v| {
v.iter()
.map(|(n, _)| KeyType::Long(OsString::from(n)))
.collect()
2018-08-21 00:23:52 +00:00
}).unwrap_or(Vec::new());
2018-08-01 15:33:55 +00:00
longs.extend(arg.long.map(|l| KeyType::Long(OsString::from(l))));
let index = self.push(arg);
short.map(|s| self.insert_key(s, index));
positional.map(|p| self.insert_key(p, index));
longs.into_iter().map(|l| self.insert_key(l, index)).count();
index
}
pub fn make_entries_by_index(&mut self, index: usize) {
let short;
let positional;
let mut longs;
{
let arg = &self.value_index[index];
short = arg.short.map(|c| KeyType::Short(c));
positional = arg.index.map(|n| KeyType::Position(n));
longs = arg
.aliases
.clone()
.map(|v| {
v.iter()
.map(|(n, _)| KeyType::Long(OsString::from(n)))
.collect()
2018-08-21 00:23:52 +00:00
}).unwrap_or(Vec::new());
2018-08-01 15:33:55 +00:00
longs.extend(arg.long.map(|l| KeyType::Long(OsString::from(l))));
}
short.map(|s| self.insert_key(s, index));
positional.map(|p| self.insert_key(p, index));
longs.into_iter().map(|l| self.insert_key(l, index)).count();
}
pub fn mut_arg<F>(&mut self, name: &str, f: F)
where
F: FnOnce(Arg<'a, 'b>) -> Arg<'a, 'b>,
{
let index = self.find_by_name(name);
let new_arg = f(self.value_index[index].clone());
let value_key = self
.values
.iter()
.filter(|(_, v)| v.contains(&index))
.map(|(k, _)| k)
.next()
.map(|&x| x);
value_key.map(|k| {
self.values.entry(k).and_modify(|v| {
v.remove(&index);
})
});
let mut hasher = DefaultHasher::new();
new_arg.hash(&mut hasher);
let hash = hasher.finish();
self.values
.entry(hash)
.and_modify(|x| {
x.insert(index);
2018-08-21 00:23:52 +00:00
}).or_insert({
2018-08-01 15:33:55 +00:00
let mut set = HashSet::new();
set.insert(index);
set
});
self.value_index.push(new_arg);
self.value_index.swap_remove(index);
self.make_entries_by_index(index);
}
pub fn find_by_name(&mut self, name: &str) -> usize {
self.value_index
.iter()
.position(|x| x.name == name)
.expect("No such name found")
}
}
#[derive(Debug)]
2018-07-19 12:50:47 +00:00
pub struct Keys<'a, V: 'a> {
2018-07-29 18:20:17 +00:00
iter: hash_map::Keys<'a, KeyType, V>,
2018-07-19 12:50:47 +00:00
}
impl<'a, V> Iterator for Keys<'a, V> {
2018-07-29 18:20:17 +00:00
type Item = &'a KeyType;
2018-07-19 12:50:47 +00:00
2018-07-19 14:27:25 +00:00
fn next(&mut self) -> Option<Self::Item> { self.iter.next() }
2018-07-19 12:50:47 +00:00
}
#[derive(Debug)]
2018-07-19 12:50:47 +00:00
pub struct Values<'a, V: 'a> {
iter: slice::Iter<'a, V>,
}
impl<'a, V> Iterator for Values<'a, V> {
type Item = &'a V;
2018-07-19 14:27:25 +00:00
fn next(&mut self) -> Option<Self::Item> { self.iter.next() }
2018-07-19 12:50:47 +00:00
}
#[derive(Debug)]
2018-07-19 12:50:47 +00:00
pub struct ValuesMut<'a, V: 'a> {
iter: slice::IterMut<'a, V>,
}
impl<'a, V> Iterator for ValuesMut<'a, V> {
2018-07-19 14:27:25 +00:00
type Item = &'a mut V;
fn next(&mut self) -> Option<Self::Item> { self.iter.next() }
}
#[derive(Debug)]
2018-07-29 18:20:17 +00:00
pub struct Iter<'c, T>
where
T: 'c,
2018-07-24 16:48:24 +00:00
{
2018-07-29 18:20:17 +00:00
map: &'c MKeyMap<T>,
2018-07-19 14:27:25 +00:00
keys: Keys<'c, usize>,
}
2018-07-29 18:20:17 +00:00
impl<'c, T> Iterator for Iter<'c, T>
where
T: 'c + Sized + Hash + PartialEq + Default + Eq,
2018-07-19 14:27:25 +00:00
{
2018-07-29 18:20:17 +00:00
type Item = (&'c KeyType, &'c T);
2018-07-19 12:50:47 +00:00
fn next(&mut self) -> Option<Self::Item> {
2018-07-19 14:27:25 +00:00
if let Some(key) = self.keys.next() {
Some((key, self.map.get(key.clone()).unwrap()))
} else {
None
}
2018-07-19 12:50:47 +00:00
}
}
#[cfg(test)]
mod tests {
2018-07-19 14:27:25 +00:00
use self::KeyType::*;
2018-07-19 12:50:47 +00:00
use super::*;
#[test]
fn get_some_value() {
2018-07-29 18:20:17 +00:00
let mut map: MKeyMap<Arg> = MKeyMap::new();
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
map.insert(Long(OsString::from("One")), Arg::with_name("Value1"));
2018-07-19 12:50:47 +00:00
2018-07-24 16:48:24 +00:00
assert_eq!(
2018-07-29 18:20:17 +00:00
map.get(Long(OsString::from("One"))),
2018-07-24 16:48:24 +00:00
Some(&Arg::with_name("Value1"))
);
2018-07-19 12:50:47 +00:00
}
#[test]
fn get_none_value() {
2018-07-29 18:20:17 +00:00
let mut map: MKeyMap<Arg> = MKeyMap::new();
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
map.insert(Long(OsString::from("One")), Arg::with_name("Value1"));
map.get(Long(OsString::from("Two")));
2018-07-24 16:48:24 +00:00
2018-07-29 18:20:17 +00:00
assert_eq!(map.get(Long(OsString::from("Two"))), None);
2018-07-19 12:50:47 +00:00
}
// #[test]
// fn insert_delete_value() {
// let mut map = MKeyMap::new();
// map.insert("One", clap::Arg::with_name("Value1"));
// assert_eq!(map.remove("One"), Some(clap::Arg::with_name("Value1")));
// assert!(map.is_empty());
// }
#[test]
fn insert_duplicate_key() {
2018-07-29 18:20:17 +00:00
let mut map: MKeyMap<Arg> = MKeyMap::new();
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
map.insert(Long(OsString::from("One")), Arg::with_name("Value1"));
2018-07-19 12:50:47 +00:00
assert_eq!(
2018-07-29 18:20:17 +00:00
map.insert(Long(OsString::from("One")), Arg::with_name("Value2")),
2018-07-19 12:50:47 +00:00
1
);
}
#[test]
2018-08-21 00:28:51 +00:00
#[should_panic]
2018-07-19 12:50:47 +00:00
fn insert_duplicate_value() {
2018-07-29 18:20:17 +00:00
let mut map: MKeyMap<Arg> = MKeyMap::new();
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
map.insert(Long(OsString::from("One")), Arg::with_name("Value1"));
2018-07-19 12:50:47 +00:00
let orig_len = map.values.len();
2018-07-29 18:20:17 +00:00
map.insert(Long(OsString::from("Two")), Arg::with_name("Value1"));
2018-07-19 12:50:47 +00:00
assert_eq!(map.values.len(), orig_len);
assert_eq!(
2018-07-29 18:20:17 +00:00
map.get(Long(OsString::from("One"))),
map.get(Long(OsString::from("Two")))
2018-07-19 12:50:47 +00:00
);
}
// #[test]
// fn insert_delete_none() {
// let mut map = MKeyMap::new();
// map.insert("One", clap::Arg::with_name("Value1"));
// assert_eq!(map.remove("Two"), None);
// assert!(!map.is_empty());
// assert_eq!(map.get("One"), Some(clap::Arg::with_name("Value1")));
// }
#[test]
fn insert_multiple_keys() {
2018-07-29 18:20:17 +00:00
let mut map: MKeyMap<Arg> = MKeyMap::new();
let index = map.insert(Long(OsString::from("One")), Arg::with_name("Value1"));
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
map.insert_key(Long(OsString::from("Two")), index);
2018-07-19 12:50:47 +00:00
assert_eq!(
2018-07-29 18:20:17 +00:00
map.get(Long(OsString::from("One"))),
map.get(Long(OsString::from("Two")))
2018-07-19 12:50:47 +00:00
);
assert_eq!(map.values.len(), 1);
}
2018-07-19 14:27:25 +00:00
2018-07-29 18:20:17 +00:00
// #[test]
// fn insert_by_name() {
// let mut map: MKeyMap<Arg> = MKeyMap::new();
// let index = map.insert(Long(OsString::from("One")), Arg::with_name("Value1"));
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
// map.insert_key_by_name(Long(OsString::from("Two")), "Value1");
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
// assert_eq!(
// map.get(Long(OsString::from("One"))),
// map.get(Long(OsString::from("Two")))
// );
// assert_eq!(map.values.len(), 1);
// }
2018-07-19 12:50:47 +00:00
#[test]
2018-07-19 14:27:25 +00:00
fn get_mutable() {
2018-07-29 18:20:17 +00:00
let mut map: MKeyMap<Arg> = MKeyMap::new();
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
map.insert(Long(OsString::from("One")), Arg::with_name("Value1"));
2018-07-19 12:50:47 +00:00
assert_eq!(
2018-07-29 18:20:17 +00:00
map.get_mut(Long(OsString::from("One"))),
2018-07-24 16:48:24 +00:00
Some(&mut Arg::with_name("Value1"))
2018-07-19 14:27:25 +00:00
);
2018-07-19 12:50:47 +00:00
}
#[test]
fn remove_key() {
2018-07-29 18:20:17 +00:00
let mut map: MKeyMap<Arg> = MKeyMap::new();
let index = map.insert(Long(OsString::from("One")), Arg::with_name("Value1"));
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
map.insert_key(Long(OsString::from("Two")), index);
map.remove_key(Long(OsString::from("One")));
2018-07-19 12:50:47 +00:00
assert_eq!(map.keys.len(), 1);
assert_eq!(map.values.len(), 1);
}
#[test]
fn iter_keys() {
2018-07-29 18:20:17 +00:00
let mut map: MKeyMap<Arg> = MKeyMap::new();
2018-07-19 12:50:47 +00:00
2018-07-29 18:20:17 +00:00
map.insert(Long(OsString::from("One")), Arg::with_name("Value1"));
map.insert(Long(OsString::from("Two")), Arg::with_name("Value2"));
2018-08-21 00:28:51 +00:00
map.insert(Position(1), Arg::with_name("Value3"));
2018-07-19 12:50:47 +00:00
let iter = map.keys().cloned();
let mut ground_truth = HashSet::new();
2018-07-29 18:20:17 +00:00
ground_truth.insert(Long(OsString::from("One")));
ground_truth.insert(Long(OsString::from("Two")));
2018-07-19 12:50:47 +00:00
ground_truth.insert(Position(1));
assert_eq!(
ground_truth.symmetric_difference(&iter.collect()).count(),
0
);
}
}