ludic/selfhost/support/str.ludic

45 lines
1.4 KiB
Text

# str.ludic — the string handling a compiler lives on: comparison, copying,
# slicing out substrings, and integer<->text. All over raw NUL-terminated
# byte buffers reached with peek8/poke8.
function char_is_digit(c: int) -> bool { return c >= '0' and c <= '9' }
function char_is_alpha(c: int) -> bool {
if c >= 'A' and c <= 'Z' { return true }
if c >= 'a' and c <= 'z' { return true }
return c == '_'
}
function char_is_alnum(c: int) -> bool { return char_is_alpha(c) or char_is_digit(c) }
# does `s` begin with `prefix`? (byte-wise; both NUL-terminated)
function str_starts(s: pointer, prefix: pointer) -> bool {
var i = 0
while prefix[i] != 0 { if s[i] != prefix[i] { return false }; i += 1 }
return true
}
# integer -> fresh decimal string
function itoa(v: int) -> pointer {
if v == 0 { let z = bytes(2); z[0] = '0'; z[1] = 0; return z }
# digits are taken off v as it is, never off -v: the most negative int has no positive twin, and
# -v overflowed back to itself, so a 0x80000000 in an i32 was emitted as a bare "-"
let neg = v < 0
var x = v
let tmp = bytes(24)
var n = 0
while x != 0 {
var d = x % 10
if d < 0 { d = -d }
tmp[n] = 48 + d
x /= 10
n += 1
}
var total = n
if neg { total += 1 }
let out = bytes(total + 1)
var k = 0
if neg { out[0] = '-'; k = 1 }
var i = 0
while i < n { out[k + i] = tmp[n - 1 - i]; i += 1 }
out[total] = 0
return out
}