Using inhomogeneous HashMap lookup to avoid string copies


#1

I’m attempting to construct a map from string prefixes to string suffixes and am making a bunch of string copies I’d prefer to avoid. Here’s my code right now:

fn collect_matching_words(mut words: Vec<String>) -> HashMap<String, Vec<String>> {
  let mut collected_words = HashMap::new();
  for word in words.drain(..) {
      let (prefix, suffix) = word.split_at(1);
      collected_words.entry(suffix.to_owned()).or_insert(Vec::new()).push(prefix.to_owned())
  }
  collected_words
}

Every time I’m doing a lookup where the suffix is already present, I’m copying the suffix string for no good reason. At least in theory, it seems to me a hasher could handle both &str and String and only do the string copy when the key is not present. Is there a way to do that?


#2

That can only work if you take a reference to the String-Vector, because if you do not copy, you need the original to survive. However once you’ve done that, you can use a map of slices into the Strings of the vector, or if you want to modify some keys Cow<'a, str>.