Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-message

Source of release 0.5.0

0.5.0 / src / engine_text.lucb

## The line format the mail engine shares with the window: fields separated by tabs, a
## record by a newline, with `\t`, `\n` and `\\` escaped inside a field. The engine builds
## its text in luce-std's collections (Buffer, TextPool, List).
from luce_std.collections import Buffer

## Append `data` to `out` as one field: tabs, newlines and backslashes escaped.
pub func put_field(out: Buffer*, data: const u8[]) -> !:
    for byte in data:
        if byte == '\t':
            try out.put(b"\\t")
        elif byte == '\n':
            try out.put(b"\\n")
        elif byte == '\r':
            try out.put(b"\\r")
        elif byte == '\\':
            try out.put(b"\\\\")
        else:
            try out.put_byte(byte)

## The fields of one line, split at tabs, still escaped.
pub struct Fields:
    var line: const u8[]
    var starts: usize[32]
    var ends: usize[32]
    var count: usize

    ## Split `line` (without its newline) at tabs, at most 32 fields.
    pub static func split(line: const u8[]) -> Fields:
        var fields = Fields(line = line)
        var start: usize = 0
        for index in 0..<line.length + 1:
            if index == line.length or line[index] == '\t':
                if fields.count < 32:
                    fields.starts[fields.count] = start
                    fields.ends[fields.count] = index
                    fields.count += 1
                start = index + 1
        return fields

    pub func length() -> usize:
        return self.count

    ## Field `index` as written (escaped); empty past the end.
    pub func raw(index: usize) -> const u8[]:
        if index >= self.count:
            var empty: const u8[]
            return empty
        return self.line[self.starts[index]..<self.ends[index]]

    ## Field `index` unescaped onto `out`.
    pub func unescape(index: usize, out: Buffer*) -> !:
        let data = self.raw(index)
        var at: usize = 0
        while at < data.length:
            var byte = data[at]
            if byte == '\\' and at + 1 < data.length:
                at += 1
                byte = match data[at]:
                    't' => '\t'
                    'n' => '\n'
                    'r' => '\r'
                    _ => data[at]
            try out.put_byte(byte)
            at += 1

    ## Field `index` as a number; zero when it is not one.
    pub func number(index: usize) -> i64:
        let data = self.raw(index)
        var value: i64 = 0
        var negative = false
        for at in 0..<data.length:
            let byte = data[at]
            if at == 0 and byte == '-':
                negative = true
            elif byte >= '0' and byte <= '9':
                value = value * 10 + (i64)(byte - '0')
            else:
                return 0
        return -value if negative else value