Files
zern/src/std.zr
2025-06-07 13:27:22 +02:00

129 lines
2.6 KiB
Plaintext

func panic[msg: String] : I64
printf("PANIC: %s\n", msg)
exit(1)
func print[x: String] : I64
printf("%s\n", x)
func print_i64[x: I64] : I64
printf("%ld\n", x)
func String.concat[a: String, b: String] : String
let c: String = malloc(strlen(a) + strlen(b) + 1)
strcpy(c, a)
strcat(c, b)
return c
func String.substr[s: String, start: I64, length: I64] : String
let out: String = malloc(length + 1)
strlcpy(out, s + start, length + 1)
return out
func String.rev[s: String] : String
let len: I64 = strlen(s)
let out: String = malloc(len + 1)
for i in 0:len
let c: Char = String.nth(s, len - i - 1)
String.set(out, i, c)
String.set(out, len, 0)
return out
func IO.read_file[path: String]: String
let file: Ptr = fopen(path, "rb")
if !file
panic("failed to open file")
fseek(file, 0, 2)
let size: I64 = ftell(file)
rewind(file)
let buffer: String = malloc(size + 1)
let n: I64 = fread(buffer, 1, size, file)
String.set(buffer, n, 0)
fclose(file)
return buffer
func IO.write_file[path: String, content: String] : I64
let file: Ptr = fopen(path, "wb")
if !file
panic("failed to open file")
fwrite(content, 1, strlen(content), file)
fclose(file)
func Char.to_i64[c: Char]: I64
return c - 48
func I64.to_string[n: I64] : String
let x: I64 = malloc(21)
sprintf(x, "%ld", n)
return x
func I64.parse[s: String] : I64
return strtol(s, 0, 0)
func Math.gcd[a: I64, b: I64] : I64
while b != 0
let tmp: I64 = b
b = a % b
a = tmp
return a
func Math.min[a: I64, b: I64] : I64
if a < b
return a
return b
func Math.max[a: I64, b: I64] : I64
if a > b
return a
return b
func Math.abs[n: I64] : I64
if n < 0
return -n
return n
func Math.pow[b: I64, e: I64] : I64
let out: I64 = 1
for i in 0:e
out = out * b
return out
func Math.lcm[a: I64, b: I64] : I64
return (a * b) / Math.gcd(a, b)
func Math.isqrt[n: I64] : I64
if n < 0
return -1
if n == 0 || n == 1
return n
let guess: I64 = n
let next_guess: I64 = (guess + n / guess) / 2
while next_guess < guess
guess = next_guess
next_guess = (guess + n / guess) / 2
return guess
func Math.is_prime[n: I64]: I64
if n <= 1
return false
if n == 2 || n == 3
return true
if n % 2 == 0 || n % 3 == 0
return false
let i: I64 = 5
while i * i <= n
if n % i == 0 || n % (i + 2) == 0
return false
i = i + 6
return true
func Array.new[] : Array
return calloc(1, 24)