dymokomi/luce-imap
Source of release 0.6.0
0.6.0 / src / imap / buffer.lucb
#==============================================================================================
#
# imap/buffer - Bytes written into luce-std's collections.Buffer
#
# DESCRIPTION:
# Commands and results grow in luce-std `collections` storage (Buffer, List,
# TextPool). A view lasts until the next append: results a session hands out are
# views into storage it reuses for the next command. These helpers add what IMAP
# writes into a Buffer: decimal numbers, base64, and ASCII case comparison.
#
#==============================================================================================
## Append `value` in decimal.
func put_decimal(out: collections.Buffer*, value: u64) -> !:
try strings.write_u64(out, value, "")
## The ASCII lower case of `byte`.
func lower(byte: u8) -> u8:
return byte + 32 if byte >= 'A' and byte <= 'Z' else byte
## Whether `a` and `b` are equal ignoring ASCII case.
pub func same(a: const u8[], b: const u8[]) -> bool:
if a.length != b.length:
return false
for index in 0..<a.length:
if lower(a[index]) != lower(b[index]):
return false
return true
## Whether `text` starts with `prefix` ignoring ASCII case.
func starts(text: const u8[], prefix: const u8[]) -> bool:
return text.length >= prefix.length and same(text[0..<prefix.length], prefix)
let base64_letters: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
## Append `data` in base64 on one line, as SASL wants it.
func put_base64(data: const u8[], out: collections.Buffer*) -> !:
let letters = base64_letters.bytes
var index: usize = 0
while index < data.length:
let remaining = data.length - index
var group: u32 = (u32)data[index] << 16
if remaining > 1:
group |= (u32)data[index + 1] << 8
if remaining > 2:
group |= data[index + 2]
try out.put_byte(letters[(group >> 18) & 63])
try out.put_byte(letters[(group >> 12) & 63])
try out.put_byte(letters[(group >> 6) & 63] if remaining > 1 else '=')
try out.put_byte(letters[group & 63] if remaining > 2 else '=')
index += 3 if remaining >= 3 else remaining