From b81e1bd75db1b8bb33f41d37dfe249383c9e62d5 Mon Sep 17 00:00:00 2001 From: Steven Roose Date: Fri, 19 Jun 2020 11:56:20 +0100 Subject: [PATCH] Add comment to Language::words_by_prefix --- src/language/mod.rs | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/language/mod.rs b/src/language/mod.rs index 8bf3312..fe9f23f 100644 --- a/src/language/mod.rs +++ b/src/language/mod.rs @@ -54,16 +54,6 @@ pub enum Language { } impl Language { - /// Get words from the wordlist that start with the given prefix. - pub fn words_by_prefix(self, prefix: &str) -> &[&'static str] { - let first = match self.word_list().iter().position(|w| w.starts_with(prefix)) { - Some(i) => i, - None => return &[], - }; - let count = self.word_list()[first..].iter().take_while(|w| w.starts_with(prefix)).count(); - &self.word_list()[first .. first + count] - } - /// The word list for this language. #[inline] pub(crate) fn word_list(self) -> &'static [&'static str; 2048] { @@ -88,6 +78,21 @@ impl Language { } } + /// Get words from the wordlist that start with the given prefix. + pub fn words_by_prefix(self, prefix: &str) -> &[&'static str] { + // The words in the wordlist are ordered lexicographically. This means + // that we cannot use `binary_search` to find words more efficiently, + // because the Rust ordering is based on the byte values. However, it + // does mean that words that share a prefix will follow each other. + + let first = match self.word_list().iter().position(|w| w.starts_with(prefix)) { + Some(i) => i, + None => return &[], + }; + let count = self.word_list()[first..].iter().take_while(|w| w.starts_with(prefix)).count(); + &self.word_list()[first .. first + count] + } + /// Get the index of the word in the word list. #[inline] pub(crate) fn find_word(self, word: &str) -> Option {