1
Fork 0

update everything to use Entry defaults

This commit is contained in:
Alexis 2015-03-01 09:42:11 -05:00
parent 1c35953cf8
commit 93cdf1f278
12 changed files with 24 additions and 84 deletions

View file

@ -1587,21 +1587,12 @@ impl<K: Ord, V> BTreeMap<K, V> {
/// ``` /// ```
/// # #![feature(collections)] /// # #![feature(collections)]
/// use std::collections::BTreeMap; /// use std::collections::BTreeMap;
/// use std::collections::btree_map::Entry;
/// ///
/// let mut count: BTreeMap<&str, usize> = BTreeMap::new(); /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
/// ///
/// // count the number of occurrences of letters in the vec /// // count the number of occurrences of letters in the vec
/// for x in vec!["a","b","a","c","a","b"].iter() { /// for x in vec!["a","b","a","c","a","b"] {
/// match count.entry(*x) { /// *count.entry(x).default(0) += 1;
/// Entry::Vacant(view) => {
/// view.insert(1);
/// },
/// Entry::Occupied(mut view) => {
/// let v = view.get_mut();
/// *v += 1;
/// },
/// }
/// } /// }
/// ///
/// assert_eq!(count["a"], 3); /// assert_eq!(count["a"], 3);

View file

@ -632,21 +632,12 @@ impl<V> VecMap<V> {
/// ``` /// ```
/// # #![feature(collections)] /// # #![feature(collections)]
/// use std::collections::VecMap; /// use std::collections::VecMap;
/// use std::collections::vec_map::Entry;
/// ///
/// let mut count: VecMap<u32> = VecMap::new(); /// let mut count: VecMap<u32> = VecMap::new();
/// ///
/// // count the number of occurrences of numbers in the vec /// // count the number of occurrences of numbers in the vec
/// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4].iter() { /// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4] {
/// match count.entry(*x) { /// *count.entry(x).default(0) += 1;
/// Entry::Vacant(view) => {
/// view.insert(1);
/// },
/// Entry::Occupied(mut view) => {
/// let v = view.get_mut();
/// *v += 1;
/// },
/// }
/// } /// }
/// ///
/// assert_eq!(count[1], 3); /// assert_eq!(count[1], 3);

View file

@ -426,8 +426,7 @@ impl<'a> Context<'a> {
info!("lib candidate: {}", path.display()); info!("lib candidate: {}", path.display());
let hash_str = hash.to_string(); let hash_str = hash.to_string();
let slot = candidates.entry(hash_str).get().unwrap_or_else( let slot = candidates.entry(hash_str).default_with(|| (HashMap::new(), HashMap::new()));
|vacant_entry| vacant_entry.insert((HashMap::new(), HashMap::new())));
let (ref mut rlibs, ref mut dylibs) = *slot; let (ref mut rlibs, ref mut dylibs) = *slot;
if rlib { if rlib {
rlibs.insert(fs::realpath(path).unwrap(), kind); rlibs.insert(fs::realpath(path).unwrap(), kind);

View file

@ -160,12 +160,7 @@ fn build_nodeid_to_index(decl: Option<&ast::FnDecl>,
cfg.graph.each_node(|node_idx, node| { cfg.graph.each_node(|node_idx, node| {
if let cfg::CFGNodeData::AST(id) = node.data { if let cfg::CFGNodeData::AST(id) = node.data {
match index.entry(id).get() { index.entry(id).default(vec![]).push(node_idx);
Ok(v) => v.push(node_idx),
Err(e) => {
e.insert(vec![node_idx]);
}
}
} }
true true
}); });
@ -185,12 +180,7 @@ fn build_nodeid_to_index(decl: Option<&ast::FnDecl>,
visit::walk_fn_decl(&mut formals, decl); visit::walk_fn_decl(&mut formals, decl);
impl<'a, 'v> visit::Visitor<'v> for Formals<'a> { impl<'a, 'v> visit::Visitor<'v> for Formals<'a> {
fn visit_pat(&mut self, p: &ast::Pat) { fn visit_pat(&mut self, p: &ast::Pat) {
match self.index.entry(p.id).get() { self.index.entry(p.id).default(vec![]).push(self.entry);
Ok(v) => v.push(self.entry),
Err(e) => {
e.insert(vec![self.entry]);
}
}
visit::walk_pat(self, p) visit::walk_pat(self, p)
} }
} }

View file

@ -11,7 +11,6 @@
use middle::infer::{InferCtxt}; use middle::infer::{InferCtxt};
use middle::ty::{self, RegionEscape, Ty}; use middle::ty::{self, RegionEscape, Ty};
use std::collections::HashSet; use std::collections::HashSet;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::default::Default; use std::default::Default;
use syntax::ast; use syntax::ast;
use util::common::ErrorReported; use util::common::ErrorReported;
@ -437,9 +436,7 @@ fn register_region_obligation<'tcx>(tcx: &ty::ctxt<'tcx>,
debug!("register_region_obligation({})", debug!("register_region_obligation({})",
region_obligation.repr(tcx)); region_obligation.repr(tcx));
match region_obligations.entry(region_obligation.cause.body_id) { region_obligations.entry(region_obligation.cause.body_id).default(vec![])
Vacant(entry) => { entry.insert(vec![region_obligation]); }, .push(region_obligation);
Occupied(mut entry) => { entry.get_mut().push(region_obligation); },
}
} }

View file

@ -5669,9 +5669,7 @@ pub fn lookup_field_type<'tcx>(tcx: &ctxt<'tcx>,
node_id_to_type(tcx, id.node) node_id_to_type(tcx, id.node)
} else { } else {
let mut tcache = tcx.tcache.borrow_mut(); let mut tcache = tcx.tcache.borrow_mut();
let pty = tcache.entry(id).get().unwrap_or_else( tcache.entry(id).default_with(|| csearch::get_field_type(tcx, struct_id, id)).ty
|vacant_entry| vacant_entry.insert(csearch::get_field_type(tcx, struct_id, id)));
pty.ty
}; };
ty.subst(tcx, substs) ty.subst(tcx, substs)
} }
@ -6819,9 +6817,7 @@ pub fn replace_late_bound_regions<'tcx, T, F>(
debug!("region={}", region.repr(tcx)); debug!("region={}", region.repr(tcx));
match region { match region {
ty::ReLateBound(debruijn, br) if debruijn.depth == current_depth => { ty::ReLateBound(debruijn, br) if debruijn.depth == current_depth => {
let region = let region = *map.entry(br).default_with(|| mapf(br));
* map.entry(br).get().unwrap_or_else(
|vacant_entry| vacant_entry.insert(mapf(br)));
if let ty::ReLateBound(debruijn1, br) = region { if let ty::ReLateBound(debruijn1, br) = region {
// If the callback returns a late-bound region, // If the callback returns a late-bound region,

View file

@ -35,7 +35,6 @@ use syntax::parse::token::InternedString;
use getopts; use getopts;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::env; use std::env;
use std::fmt; use std::fmt;
use std::path::PathBuf; use std::path::PathBuf;
@ -1037,10 +1036,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
None => early_error("--extern value must be of the format `foo=bar`"), None => early_error("--extern value must be of the format `foo=bar`"),
}; };
match externs.entry(name.to_string()) { externs.entry(name.to_string()).default(vec![]).push(location.to_string());
Vacant(entry) => { entry.insert(vec![location.to_string()]); },
Occupied(mut entry) => { entry.get_mut().push(location.to_string()); },
}
} }
let crate_name = matches.opt_str("crate-name"); let crate_name = matches.opt_str("crate-name");

View file

@ -112,7 +112,6 @@ use util::nodemap::{DefIdMap, FnvHashMap, NodeMap};
use util::lev_distance::lev_distance; use util::lev_distance::lev_distance;
use std::cell::{Cell, Ref, RefCell}; use std::cell::{Cell, Ref, RefCell};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::mem::replace; use std::mem::replace;
use std::rc::Rc; use std::rc::Rc;
use std::iter::repeat; use std::iter::repeat;
@ -1362,11 +1361,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
closure_def_id: ast::DefId, closure_def_id: ast::DefId,
r: DeferredCallResolutionHandler<'tcx>) { r: DeferredCallResolutionHandler<'tcx>) {
let mut deferred_call_resolutions = self.inh.deferred_call_resolutions.borrow_mut(); let mut deferred_call_resolutions = self.inh.deferred_call_resolutions.borrow_mut();
let mut vec = match deferred_call_resolutions.entry(closure_def_id) { deferred_call_resolutions.entry(closure_def_id).default(vec![]).push(r);
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(Vec::new()),
};
vec.push(r);
} }
fn remove_deferred_call_resolutions(&self, fn remove_deferred_call_resolutions(&self,

View file

@ -876,9 +876,7 @@ impl DocFolder for Cache {
if let clean::ImplItem(ref i) = item.inner { if let clean::ImplItem(ref i) = item.inner {
match i.trait_ { match i.trait_ {
Some(clean::ResolvedPath{ did, .. }) => { Some(clean::ResolvedPath{ did, .. }) => {
let v = self.implementors.entry(did).get().unwrap_or_else( self.implementors.entry(did).default(vec![]).push(Implementor {
|vacant_entry| vacant_entry.insert(Vec::with_capacity(1)));
v.push(Implementor {
def_id: item.def_id, def_id: item.def_id,
generics: i.generics.clone(), generics: i.generics.clone(),
trait_: i.trait_.as_ref().unwrap().clone(), trait_: i.trait_.as_ref().unwrap().clone(),
@ -1080,9 +1078,7 @@ impl DocFolder for Cache {
}; };
if let Some(did) = did { if let Some(did) = did {
let v = self.impls.entry(did).get().unwrap_or_else( self.impls.entry(did).default(vec![]).push(Impl {
|vacant_entry| vacant_entry.insert(Vec::with_capacity(1)));
v.push(Impl {
impl_: i, impl_: i,
dox: dox, dox: dox,
stability: item.stability.clone(), stability: item.stability.clone(),
@ -1334,9 +1330,8 @@ impl Context {
Some(ref s) => s.to_string(), Some(ref s) => s.to_string(),
}; };
let short = short.to_string(); let short = short.to_string();
let v = map.entry(short).get().unwrap_or_else( map.entry(short).default(vec![])
|vacant_entry| vacant_entry.insert(Vec::with_capacity(1))); .push((myname, Some(plain_summary_line(item.doc_value()))));
v.push((myname, Some(plain_summary_line(item.doc_value()))));
} }
for (_, items) in &mut map { for (_, items) in &mut map {

View file

@ -352,9 +352,7 @@ fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
} }
}; };
let name = name.to_string(); let name = name.to_string();
let locs = externs.entry(name).get().unwrap_or_else( externs.entry(name).default(vec![]).push(location.to_string());
|vacant_entry| vacant_entry.insert(Vec::with_capacity(1)));
locs.push(location.to_string());
} }
Ok(externs) Ok(externs)
} }

View file

@ -307,10 +307,7 @@
//! let message = "she sells sea shells by the sea shore"; //! let message = "she sells sea shells by the sea shore";
//! //!
//! for c in message.chars() { //! for c in message.chars() {
//! match count.entry(c) { //! *count.entry(c).default(0) += 1;
//! Entry::Vacant(entry) => { entry.insert(1); },
//! Entry::Occupied(mut entry) => *entry.get_mut() += 1,
//! }
//! } //! }
//! //!
//! assert_eq!(count.get(&'s'), Some(&8)); //! assert_eq!(count.get(&'s'), Some(&8));
@ -343,10 +340,7 @@
//! for id in orders.into_iter() { //! for id in orders.into_iter() {
//! // If this is the first time we've seen this customer, initialize them //! // If this is the first time we've seen this customer, initialize them
//! // with no blood alcohol. Otherwise, just retrieve them. //! // with no blood alcohol. Otherwise, just retrieve them.
//! let person = match blood_alcohol.entry(id) { //! let person = blood_alcohol.entry(id).default(Person{id: id, blood_alcohol: 0.0});
//! Entry::Vacant(entry) => entry.insert(Person{id: id, blood_alcohol: 0.0}),
//! Entry::Occupied(entry) => entry.into_mut(),
//! };
//! //!
//! // Reduce their blood alcohol level. It takes time to order and drink a beer! //! // Reduce their blood alcohol level. It takes time to order and drink a beer!
//! person.blood_alcohol *= 0.9; //! person.blood_alcohol *= 0.9;

View file

@ -66,9 +66,8 @@ pub fn apply_mark(m: Mrk, ctxt: SyntaxContext) -> SyntaxContext {
/// Extend a syntax context with a given mark and sctable (explicit memoization) /// Extend a syntax context with a given mark and sctable (explicit memoization)
fn apply_mark_internal(m: Mrk, ctxt: SyntaxContext, table: &SCTable) -> SyntaxContext { fn apply_mark_internal(m: Mrk, ctxt: SyntaxContext, table: &SCTable) -> SyntaxContext {
let key = (ctxt, m); let key = (ctxt, m);
* table.mark_memo.borrow_mut().entry(key).get().unwrap_or_else( * table.mark_memo.borrow_mut().entry(key)
|vacant_entry| .default_with(|| idx_push(&mut *table.table.borrow_mut(), Mark(m, ctxt)))
vacant_entry.insert(idx_push(&mut *table.table.borrow_mut(), Mark(m, ctxt))))
} }
/// Extend a syntax context with a given rename /// Extend a syntax context with a given rename
@ -84,9 +83,8 @@ fn apply_rename_internal(id: Ident,
table: &SCTable) -> SyntaxContext { table: &SCTable) -> SyntaxContext {
let key = (ctxt, id, to); let key = (ctxt, id, to);
* table.rename_memo.borrow_mut().entry(key).get().unwrap_or_else( * table.rename_memo.borrow_mut().entry(key)
|vacant_entry| .default_with(|| idx_push(&mut *table.table.borrow_mut(), Rename(id, to, ctxt)))
vacant_entry.insert(idx_push(&mut *table.table.borrow_mut(), Rename(id, to, ctxt))))
} }
/// Apply a list of renamings to a context /// Apply a list of renamings to a context