syntax.Keywords
class pub Keywords
A 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)
keywords.iter.select(fn (w) { w.size >= 2 }).each(fn (word) {
let bytes = word.to_byte_array
first.set(bytes.get(0), 1)
second.set(bytes.get(1), 1)
words.insert(bytes)
})
Keywords(words: words, first: first, second: second)
}
fn pub static new(keywords: ref Array[String]) -> Keywords
Returns 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, size: Int) -> Bool {
size >= 2
and @first.get(bytes.get(at)) == 1
and @second.get(bytes.get(at + 1)) == 1
and @words.contains?(bytes.slice(at, size))
}
fn pub contains_range?(bytes: ref ByteArray, at: Int, size: Int) -> Bool
Returns 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 size
arguments specify the index to bytes
and the number of
bytes to check respectively.
Panics
This method panics if at
or at + size
is not within the bounds of
bytes
.
Examples
import syntax (Keywords)
let kw = Keywords.new(['class', 'async', 'fn'])
let input = 'class'.to_byte_array
kw.contains_range?(input, at: 0, size: input.size) # => true