Skip to content

Commit

Permalink
improve code involving entries
Browse files Browse the repository at this point in the history
In most cases, and_modify and/or or_insert(_X) can be used,
rather than matching on Vacant and Occupied.
  • Loading branch information
pchampin committed Dec 6, 2023
1 parent 586bcd5 commit c4a4f33
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 77 deletions.
45 changes: 15 additions & 30 deletions c14n/src/rdfc10.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
//! <https://www.w3.org/TR/rdf-canon/>
use std::cmp::Ordering;
use std::collections::btree_map::Entry::*;
use std::collections::BTreeMap;
use std::fmt::Write;
use std::io;
Expand Down Expand Up @@ -160,25 +159,19 @@ pub fn relabel_with<'a, H: HashFunction, D: Dataset>(
));
}
if let Some(bnid) = component.bnode_id() {
match state.b2q.entry(Rc::from(bnid.as_str())) {
Vacant(e) => {
e.insert(vec![quad]);
}
Occupied(mut e) => e.get_mut().push(quad),
}
state
.b2q
.entry(Rc::from(bnid.as_str()))
.or_default()
.push(quad);
}
}
}
// Step 3
for (bnid, quads) in state.b2q.iter() {
let hash = hash_first_degree_quads::<H, _>(bnid, &quads[..]);
let bnid2 = Rc::clone(bnid);
match state.h2b.entry(hash) {
Vacant(e) => {
e.insert(vec![bnid2]);
}
Occupied(mut e) => e.get_mut().push(bnid2),
}
state.h2b.entry(hash).or_default().push(bnid2);
state.b2h.insert(Rc::clone(bnid), hash);
}
// Step 4
Expand Down Expand Up @@ -327,12 +320,7 @@ impl<'a, H: HashFunction, T: Term> C14nState<'a, H, T> {
}
let hash = self.hash_related_bnode(&bnid, quad, issuer, position);
let bnid = Box::from(bnid.as_str());
match hn.entry(hash) {
Vacant(e) => {
e.insert(vec![bnid]);
}
Occupied(mut e) => e.get_mut().push(bnid),
}
hn.entry(hash).or_default().push(bnid);
}
}
}
Expand Down Expand Up @@ -438,17 +426,14 @@ impl BnodeIssuer {
fn issue(&mut self, bnid: &str) -> (&str, bool) {
let key = Rc::from(bnid);
let key2 = Rc::clone(&key);
match self.issued.entry(key) {
Occupied(e) => (e.into_mut().as_str(), false),
Vacant(e) => {
let counter = self.issued_order.len();
let ret = e.insert(BnodeId::new_unchecked(
format!("{}{}", self.prefix.as_str(), counter).into(),
));
self.issued_order.push(key2);
(ret.as_str(), true)
}
}
let mut new = false;
let ret = self.issued.entry(key).or_insert_with(|| {
new = true;
let counter = self.issued_order.len();
self.issued_order.push(key2);
BnodeId::new_unchecked(format!("{}{}", self.prefix.as_str(), counter).into())
});
(ret.as_str(), new)
}
}

Expand Down
28 changes: 12 additions & 16 deletions jsonld/src/serializer/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use sophia_api::ns::rdf;
use sophia_api::quad::Quad;
use sophia_api::source::{QuadSource, SinkError, StreamResult};
use sophia_api::term::{Term, TermKind, TryFromTerm};
use std::collections::hash_map::Entry::*;
use std::collections::{HashMap, HashSet};

/// JSON-LD serializer engine
Expand Down Expand Up @@ -90,18 +89,16 @@ impl<'a, L> Engine<'a, L> {
}
if q.o().is_bnode() {
let parent = (is, q.p().as_id());
match self.unique_parent.entry(q.o().as_id()) {
Vacant(e) => {
e.insert(Some(parent));
}
Occupied(mut e) => {
if let Some(p) = e.get() {
self.unique_parent
.entry(q.o().as_id())
.and_modify(|opt| {
if let Some(p) = opt {
if p != &parent {
e.insert(None);
opt.take();
}
}
}
}
})
.or_insert_with(|| Some(parent));
}
Ok(())
})
Expand All @@ -110,16 +107,15 @@ impl<'a, L> Engine<'a, L> {
fn index<T: Into<Box<str>>, U: Into<Box<str>>>(&mut self, g_id: T, s_id: U) -> usize {
let g_id: Box<str> = g_id.into();
let s_id: Box<str> = s_id.into();
match self.index.entry((g_id.clone(), s_id.clone())) {
Vacant(e) => {
*self
.index
.entry((g_id.clone(), s_id.clone()))
.or_insert_with(|| {
let i = self.gs_id.len();
e.insert(i);
self.gs_id.push((g_id, s_id));
self.node.push(HashMap::new());
i
}
Occupied(e) => *e.get(),
}
})
}

fn make_rdf_object<T>(&mut self, o: T, g_id: &str) -> RdfObject
Expand Down
11 changes: 7 additions & 4 deletions jsonld/src/util_traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,13 @@ pub trait HashMapUtil<T> {

impl<T, U: From<T> + PartialEq> HashMapUtil<T> for HashMap<Box<str>, Vec<U>> {
fn push_if_new<V: Into<Box<str>>>(&mut self, key: V, val: T) {
let vals = match self.entry(key.into()) {
Vacant(e) => e.insert(Vec::new()),
Occupied(e) => e.into_mut(),
match self.entry(key.into()) {
Occupied(e) => {
e.into_mut().push_if_new(val);
}
Vacant(e) => {
e.insert(vec![val.into()]);
}
};
vals.push_if_new(val);
}
}
48 changes: 21 additions & 27 deletions turtle/src/serializer/_pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,24 +431,23 @@ fn build_labelled<'a>(d: &'a PrettifiableDataset) -> BTreeSet<&'a SimpleTerm<'a>
let q = q.unwrap();
for (i, t) in iter_spog(q).enumerate() {
match t.kind() {
TermKind::BlankNode => match profiles.entry(t) {
Vacant(e) => {
e.insert(BnodeProfile {
TermKind::BlankNode => {
profiles
.entry(t)
.and_modify(|profile: &mut BnodeProfile| {
if !profile.bad {
profile.add_named_graph(q.g());
profile.update_positions(i, &q);
}
})
.or_insert_with(|| BnodeProfile {
bad: (i == 1 || i == 3),
named_graphs: [q.g()].into_iter().collect(),
out_degree: usize::from(i == 0),
predecessor: if i == 2 { Some(q.s()) } else { None },
visited: false,
});
}
Occupied(mut e) => {
let profile = e.get_mut();
if !profile.bad {
profile.add_named_graph(q.g());
profile.update_positions(i, &q);
}
}
},
}
TermKind::Triple => {
let mut atoms = t.atoms();
let [s, p, o] = t.triple().unwrap().spo();
Expand All @@ -458,21 +457,16 @@ fn build_labelled<'a>(d: &'a PrettifiableDataset) -> BTreeSet<&'a SimpleTerm<'a>
// if it must be labelled or not
}
for a in t.atoms().filter(Term::is_blank_node) {
match profiles.entry(a) {
Vacant(e) => {
e.insert(BnodeProfile {
bad: true,
named_graphs: Default::default(),
out_degree: 0,
predecessor: None,
visited: false,
});
}
Occupied(mut e) => {
let profile = e.get_mut();
profile.bad = true;
}
}
profiles
.entry(a)
.and_modify(|profile| profile.bad = true)
.or_insert_with(|| BnodeProfile {
bad: true,
named_graphs: Default::default(),
out_degree: 0,
predecessor: None,
visited: false,
});
}
}
_ => (),
Expand Down

0 comments on commit c4a4f33

Please sign in to comment.