syntax.Keywords
type pub KeywordsA type to efficiently check if certain words are keywords.
This type only supports keywords with a minimum size of two bytes. Input smaller than two bytes is never treated as a keyword.
Static methods
new
Show source codeHide source code
fn pub static new(keywords: ref Array[String]) -> Keywords {
let words = Set.new
let first = ByteArray.filled(with: 0, times: 255)
let second = ByteArray.filled(with: 0, times: 255)
for word in keywords.iter.select(fn (w) { w.size >= 2 }) {
let bytes = word.to_byte_array
first.set(bytes.get(0).or_panic, 1)
second.set(bytes.get(1).or_panic, 1)
words.insert(bytes)
}
Keywords(words: words, first: first, second: second)
}fn pub static new(keywords: ref Array[String]) -> KeywordsReturns a new Keywords populated using the list of keywords.
Examples
import syntax (Keywords)
Keywords.new(['fn', 'class', 'async'])
Instance methods
contains_range?
Show source codeHide source code
fn pub contains_range?(bytes: ref ByteArray, at: Int, end: Int) -> Bool {
(end - at) >= 2
and @first.get(bytes.get(at).or_panic).or_panic == 1
and @second.get(bytes.get(at + 1).or_panic).or_panic == 1
and @words.contains?(bytes.slice(at, end).to_byte_array)
}fn pub contains_range?(bytes: ref ByteArray, at: Int, end: Int) -> BoolReturns true if the range of bytes in bytes is a valid keyword.
In the best case scenario, this method doesn't perform any allocations (e.g.
the first two bytes don't match any known keywords). In the worst case it
slices bytes into a subslice and compares that to the known list of
keywords.
The bytes argument is a ByteArray (e.g. a reusable buffer) to check.
The at and end arguments specify the start and end indexes to bytes
respectively.
Panics
This method panics if the range is not within bounds.
Examples
import syntax (Keywords)
let kw = Keywords.new(['class', 'async', 'fn'])
let input = 'class'.to_byte_array
kw.contains_range?(input, at: 0, end: 5) # => true