From b2f23b8a672af52c55ba17e45319d8a7463eb5d4 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Tue, 29 Aug 2017 15:47:21 -0700 Subject: [PATCH] Add fake fallible HashMap shim over stdlib --- src/fake.rs | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 ++ 2 files changed, 85 insertions(+) create mode 100644 src/fake.rs diff --git a/src/fake.rs b/src/fake.rs new file mode 100644 index 00000000000..203fdb3423a --- /dev/null +++ b/src/fake.rs @@ -0,0 +1,83 @@ +//! This module contains shims around the stdlib HashMap +//! that add fallible methods +//! +//! These methods are a lie. They are not actually fallible. This is just to make +//! it smooth to switch between hashmap impls in a codebase. + +use std::hash::{BuildHasher, Hash}; +use std::collections::HashMap as StdMap; +use std::ops::{Deref, DerefMut}; + +pub use std::collections::hash_map::{Entry, RandomState}; + +pub struct HashMap(StdMap); + +impl Deref for HashMap { + type Target = StdMap; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for HashMap { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl HashMap { + + #[inline] + pub fn new() -> HashMap { + HashMap(StdMap::new()) + } + + #[inline] + pub fn with_capacity(capacity: usize) -> HashMap { + HashMap(StdMap::with_capacity(capacity)) + } + + #[inline] + pub fn with_capacity_fallible(capacity: usize) -> Result, ()> { + Ok(HashMap(StdMap::with_capacity(capacity))) + } +} + + +impl HashMap + where K: Eq + Hash, + S: BuildHasher +{ + #[inline] + pub fn with_hasher_fallible(hash_builder: S) -> Result, ()> { + Ok(HashMap(StdMap::with_hasher(hash_builder))) + } + + #[inline] + pub fn with_capacity_and_hasher_fallible(capacity: usize, hash_builder: S) -> Result, ()> { + Ok(HashMap(StdMap::with_capacity_and_hasher(capacity, hash_builder))) + } + + pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap { + HashMap(StdMap::with_capacity_and_hasher(capacity, hash_builder)) + } + + + #[inline] + pub fn reserve_fallible(&mut self, additional: usize) -> Result<(), ()> { + Ok(self.reserve(additional)) + } + + pub fn shrink_to_fit_fallible(&mut self) -> Result<(), ()> { + Ok(self.shrink_to_fit()) + } + + pub fn entry_fallible(&mut self, key: K) -> Result, ()> { + Ok(self.entry(key)) + } + + #[inline] + pub fn insert_fallible(&mut self, k: K, v: V) -> Result, ()> { + Ok(self.insert(k, v)) + } +} diff --git a/src/lib.rs b/src/lib.rs index db12c725f5d..3cbab53a950 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,8 @@ mod alloc; pub mod hash_map; pub mod hash_set; +pub mod fake; + trait Recover { type Key;