Skip to content

Commit

Permalink
Merge pull request #53 from pluots/string-to-box
Browse files Browse the repository at this point in the history
Change from 'String' or 'Arc<String>' to 'Box<str>' or 'Arc<str>' where possible
  • Loading branch information
tgross35 committed Oct 17, 2023
2 parents 9188df3 + b55d3fe commit ba9632b
Show file tree
Hide file tree
Showing 10 changed files with 95 additions and 89 deletions.
2 changes: 1 addition & 1 deletion zspell/src/affix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub struct ParsedCfg {
// Rules for suggestion replacements to try
replacements: Vec<Conversion>,

/// Suggest words that differe by 1 try character
/// Suggest words that differ by 1 try character
try_characters: String,

/// Flag used to indicate words that should not be suggested
Expand Down
32 changes: 13 additions & 19 deletions zspell/src/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub struct Dictionary {

/* the following few types are used to store meta information */
/// A list of all stem words
stems: HashSet<Arc<String>>,
stems: HashSet<Arc<str>>,
/// Affix flags and rules
flags: BTreeMap<u32, FlagValue>,
/// Possible morphs
Expand Down Expand Up @@ -135,9 +135,9 @@ impl Dictionary {
let lower = word.to_lowercase();
(!self.wordlist_forbidden.0.contains_key(word))
&& (self.wordlist.0.contains_key(word)
|| self.wordlist.0.contains_key(&lower)
|| self.wordlist.0.contains_key(lower.as_str())
|| self.wordlist_nosuggest.0.contains_key(word)
|| self.wordlist_nosuggest.0.contains_key(&lower))
|| self.wordlist_nosuggest.0.contains_key(lower.as_str()))
}

/// Check words in a string, returning a list of the start and end indices
Expand Down Expand Up @@ -215,18 +215,14 @@ impl Dictionary {
if self.check_word(word) {
return Ok(());
}
let mut suggestions: Vec<(u32, &String)> = self
let mut suggestions: Vec<(u32, &str)> = self
.wordlist
.0
.keys()
.filter_map(|key| try_levenshtein(key, word, 1).map(|lim| (lim, key)))
.filter_map(|key| try_levenshtein(key, word, 1).map(|lim| (lim, key.as_ref())))
.collect();
suggestions.sort_unstable_by_key(|(k, v)| *k);
Err(suggestions
.iter()
.take(10)
.map(|(k, v)| v.as_str())
.collect())
Err(suggestions.iter().take(10).map(|(k, v)| *v).collect())
}

/// **UNSTABLE** Generate the stems for a single word. Feature gated behind
Expand Down Expand Up @@ -311,11 +307,9 @@ impl Dictionary {
let mut prefix_rules = Vec::new();
let mut suffix_rules = Vec::new();

let stem_rc: &Arc<String> = self
let stem_rc: &Arc<str> = self
.stems
.get_or_insert_with(&StrWrapper::new(stem), |sw: &StrWrapper| {
Arc::new(sw.to_string())
});
.get_or_insert_with(&StrWrapper::new(stem), |sw: &StrWrapper| Arc::from(sw.0));

let mut add_stem = true;
let mut forbid = false;
Expand Down Expand Up @@ -410,9 +404,9 @@ impl Dictionary {
// let flags = dict.iter().find(|d| &d.stem() == friend).map(|d| &d.flags);
todo!()
} else {
let stem_arc: Arc<String> = self
let stem_arc: Arc<str> = self
.stems
.get_or_insert_with(&entry.stem, |stem| Arc::new(stem.to_string()))
.get_or_insert_with(entry.stem.as_str(), |stem| Arc::from(stem))
.clone();

let source = Source::Personal(Box::new(PersonalMeta::new(
Expand All @@ -430,7 +424,7 @@ impl Dictionary {

// Add our word, update its meta
let extra_vec: &mut Vec<Meta> = hmap
.entry_ref(&entry.stem)
.entry_ref(entry.stem.as_str())
.or_insert_with(|| Vec::with_capacity(1));
extra_vec.push(meta);
}
Expand Down Expand Up @@ -466,7 +460,7 @@ impl Dictionary {
///
/// Currently contains a `HashMap<String, Vec<Meta>>`
#[derive(Clone, Debug, PartialEq)]
pub struct WordList(HashMap<String, Vec<Meta>>);
pub struct WordList(HashMap<Box<str>, Vec<Meta>>);

impl WordList {
fn new() -> Self {
Expand All @@ -477,7 +471,7 @@ impl WordList {
/// `zspell-unstable` marker as the internal format may change
#[inline]
#[cfg_attr(feature = "zspell-unstable", visibility::make(pub))]
pub(crate) fn inner(&self) -> &HashMap<String, Vec<Meta>> {
pub(crate) fn inner(&self) -> &HashMap<Box<str>, Vec<Meta>> {
&self.0
}
}
Expand Down
14 changes: 7 additions & 7 deletions zspell/src/dict/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub(super) fn create_affixed_word_map(
prefix_rules: &[&Arc<AfxRule>],
suffix_rules: &[&Arc<AfxRule>],
stem: &str,
stem_rc: &Arc<String>,
stem_rc: &Arc<str>,
dest: &mut WordList,
) -> bool {
if prefix_rules.is_empty() && suffix_rules.is_empty() {
Expand All @@ -32,7 +32,7 @@ pub(super) fn create_affixed_word_map(
for &rule in prefix_rules {
for (idx, result) in rule.apply_patterns(stem) {
let meta = Meta::new(stem_rc.clone(), Source::Affix(rule.clone()));
let meta_vec = dest.0.entry_ref(&result).or_insert_with(Vec::new);
let meta_vec = dest.0.entry_ref(result.as_str()).or_insert_with(Vec::new);
meta_vec.push(meta);
rule_found = true;

Expand All @@ -45,7 +45,7 @@ pub(super) fn create_affixed_word_map(
for &rule in suffix_rules {
for (idx, result) in rule.apply_patterns(stem) {
let meta = Meta::new(stem_rc.clone(), Source::Affix(rule.clone()));
let meta_vec = dest.0.entry_ref(&result).or_insert_with(Vec::new);
let meta_vec = dest.0.entry_ref(result.as_str()).or_insert_with(Vec::new);
meta_vec.push(meta);
rule_found = true;

Expand All @@ -59,7 +59,7 @@ pub(super) fn create_affixed_word_map(
});

for (newword, &pfx_rule, _idx_pfx, _idx_sfx) in words_iter {
let meta_vec = dest.0.entry_ref(&newword).or_insert_with(Vec::new);
let meta_vec = dest.0.entry_ref(newword.as_str()).or_insert_with(Vec::new);
let meta1 = Meta::new(stem_rc.clone(), Source::Affix(rule.clone()));
let meta2 = Meta::new(stem_rc.clone(), Source::Affix(pfx_rule.clone()));
meta_vec.push(meta1);
Expand Down Expand Up @@ -148,11 +148,11 @@ mod tests {

for (i, (word, pfxs, sfxs, expected_slice)) in conditions.iter().enumerate() {
let mut dest = WordList::new();
let stem_rc = Arc::new((*word).to_owned());
let stem_rc = Arc::from(*word);
create_affixed_word_map(pfxs, sfxs, &stem_rc, &stem_rc, &mut dest);

let mut tmp: Vec<(String, _)> = dest.0.into_iter().collect();
let mut result: Vec<_> = tmp.iter().map(|(s, _)| s.as_str()).collect();
let mut tmp: Vec<(Box<str>, _)> = dest.0.into_iter().collect();
let mut result: Vec<_> = tmp.iter().map(|(s, _)| s.as_ref()).collect();
let mut expected: Vec<_> = (*expected_slice).to_owned();
result.sort_unstable();
expected.sort_unstable();
Expand Down
18 changes: 9 additions & 9 deletions zspell/src/dict/rule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ impl AfxRule {
.collect();

ret.patterns.push(AfxRulePattern {
affix: rule.affix.clone(),
affix: rule.affix.as_str().into(),
condition: rule.condition.clone(),
strip: rule.strip.clone(),
strip: rule.strip.as_ref().map(|s| Box::from(s.as_str())),
morph_info,
});
}
Expand Down Expand Up @@ -104,11 +104,11 @@ impl AfxRule {
/// A single affix rule application
#[derive(Clone, Default, Debug, PartialEq, Eq, Hash)]
pub struct AfxRulePattern {
affix: String,
affix: Box<str>,
/// Condition to be met to apply this rule.
condition: Option<ReWrapper>,
/// Characters to strip
strip: Option<String>,
strip: Option<Box<str>>,
/// Associated morph info
morph_info: Vec<Arc<MorphInfo>>,
}
Expand All @@ -118,9 +118,9 @@ impl AfxRulePattern {
#[cfg(test)]
pub fn new(afx: &str, strip: Option<&str>) -> Self {
Self {
affix: afx.to_owned(),
affix: afx.into(),
condition: None,
strip: strip.map(ToOwned::to_owned),
strip: strip.map(Into::into),
morph_info: Vec::new(),
}
}
Expand Down Expand Up @@ -152,10 +152,10 @@ impl AfxRulePattern {
match kind {
RuleType::Prefix => {
// If stripping chars exist, strip them from the prefix
let mut working = self.affix.clone();
let mut working: String = self.affix.as_ref().into();

if let Some(sc) = &self.strip {
working.push_str(s.strip_prefix(sc.as_str()).unwrap_or(s));
working.push_str(s.strip_prefix(sc.as_ref()).unwrap_or(s));
} else {
working.push_str(s);
}
Expand All @@ -165,7 +165,7 @@ impl AfxRulePattern {
RuleType::Suffix => {
// Same logic as above
let mut working = if let Some(sc) = &self.strip {
s.strip_suffix(sc.as_str()).unwrap_or(s).to_owned()
s.strip_suffix(sc.as_ref()).unwrap_or(s).to_owned()
} else {
s.to_owned()
};
Expand Down
12 changes: 6 additions & 6 deletions zspell/src/dict/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,16 @@ fn test_dict_entry_ok() {
"abcd".to_owned(),
&['A' as u32, 'B' as u32, 'C' as u32],
vec![
MorphInfo::InflecPfx("m1".to_owned()),
MorphInfo::TermPfx("m2".to_owned()),
MorphInfo::InflecPfx("m1".into()),
MorphInfo::TermPfx("m2".into()),
],
);
let r4 = DictEntry::new(
"abcd".to_owned(),
&[],
vec![
MorphInfo::InflecPfx("m1".to_owned()),
MorphInfo::TermPfx("m2".to_owned()),
MorphInfo::InflecPfx("m1".into()),
MorphInfo::TermPfx("m2".into()),
],
);

Expand Down Expand Up @@ -80,8 +80,8 @@ fn test_personal_entry_ok() {
"abcd",
Some("ABC"),
vec![
MorphInfo::InflecPfx("m1".to_owned()),
MorphInfo::TermPfx("m2".to_owned()),
MorphInfo::InflecPfx("m1".into()),
MorphInfo::TermPfx("m2".into()),
],
false,
);
Expand Down
10 changes: 5 additions & 5 deletions zspell/src/dict/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ use crate::parser_affix::ParsedRule;
/// Additional information attached to an entry in a dictionary
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Meta {
stem: Arc<String>,
stem: Arc<str>,
source: Source,
}

impl Meta {
pub(crate) fn new(stem_rc: Arc<String>, source: Source) -> Self {
pub(crate) fn new(stem_rc: Arc<str>, source: Source) -> Self {
Self {
stem: stem_rc,
source,
Expand All @@ -35,7 +35,7 @@ impl Meta {
None
}
}) {
return stem.as_str();
return stem;
}
}

Expand Down Expand Up @@ -80,12 +80,12 @@ impl Source {
/// Representation of meta info for a personal dictionary
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PersonalMeta {
friend: Option<Arc<String>>,
friend: Option<Arc<str>>,
morph: Vec<Arc<MorphInfo>>,
}

impl PersonalMeta {
pub fn new(friend: Option<Arc<String>>, morph: Vec<Arc<MorphInfo>>) -> Self {
pub fn new(friend: Option<Arc<str>>, morph: Vec<Arc<MorphInfo>>) -> Self {
Self { friend, morph }
}
}
Expand Down
8 changes: 4 additions & 4 deletions zspell/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,14 @@ impl Display for StrWrapper<'_> {
}
}

impl Equivalent<Rc<String>> for StrWrapper<'_> {
fn equivalent(&self, key: &Rc<String>) -> bool {
impl Equivalent<Rc<str>> for StrWrapper<'_> {
fn equivalent(&self, key: &Rc<str>) -> bool {
self.0 == key.as_ref()
}
}

impl Equivalent<Arc<String>> for StrWrapper<'_> {
fn equivalent(&self, key: &Arc<String>) -> bool {
impl Equivalent<Arc<str>> for StrWrapper<'_> {
fn equivalent(&self, key: &Arc<str>) -> bool {
self.0 == key.as_ref()
}
}
Loading

0 comments on commit ba9632b

Please sign in to comment.