///|
/// Half-open UTF-16 code-unit offsets into a well-formed source line.
/// Standalone tokenizers return endpoints on Unicode scalar boundaries.
#derive(Eq, Debug)
pub(all) struct Span {
start : Int32
end : Int32
style : String?
}
///|
/// Number of UTF-16 code units in a scalar, given its first code unit in
/// well-formed source text.
pub fn scalar_width(first : UInt16) -> Int32 {
if first.is_leading_surrogate() {
2
} else {
1
}
}
///|
/// Visit tokens in a well-formed UTF-16 line. The mode returns an exclusive end offset and style
/// for the token at start. Every token must advance to a scalar boundary within the line.
pub fn spans(line : String, read : (Int32) -> (Int32, String?)) -> Iter[Span] {
let mut pos = 0
Iter(() => {
guard pos < line.length() else { return None }
let start = pos
let (end, style) = read(start)
guard start < end && end <= line.length() else {
abort("invalid token end offset")
}
guard end == line.length() || !line[end].is_trailing_surrogate() else {
abort("token end splits a UTF-16 surrogate pair")
}
pos = end
Some({ start, end, style, })
})
}
///|
/// Iterate over lines split by LF, CRLF or CR, including a final empty line.
pub fn lines(text : String) -> Iter[String] {
let mut start = 0
let mut done = false
Iter(() => {
guard !done else { return None }
let mut end = start
while end < text.length() && text[end] != '\n' && text[end] != '\r' {
end += 1
}
let line = text.clamped_view(start~, end~).to_owned()
done = end == text.length()
if !done {
start = end + 1
if text[end] == '\r' && start < text.length() && text[start] == '\n' {
start += 1
}
}
Some(line)
})
}