undar-lang/test/stdlib.ul

191 lines
3.4 KiB
Plaintext

const int I16_MIN = -32768;
const int I16_MAX = 32767;
const nat U16_MAX = 65535;
byte[10000] heap;
nat heap_allocated = 0;
subroutine alloc(nat size) byte[] {
nat pos = heap_allocated;
heap_allocated = heap_allocated + size;
return heap[pos:pos + size];
}
subroutine heap_reset() {
heap_allocated = 0;
}
/**
* Concatinates 2 strings
*/
function strcat(str src1, str src2) str {
str result = alloc(src1.length + src2.length) as str;
result[0:src1.length] = src1;
result[src1.length:] = src2;
return result;
}
/**
* finds index of string, -1 if not found
*/
function stridx(str haystack, char needle) nat {
nat i = -1;
for (char c in haystack) {
i = i + 1;
if (c == needle) {
break;
}
}
return i;
}
/**
* checks if 2 strings are equal
*/
function streq(str src1, str src2) bool {
if (src1.length != src2.length) return false;
for (nat i=0; src1.length; i++) {
if (src1[i] != src2[i]) return false;
}
return true;
}
/**
* Slice string
*/
function slice(str src, nat start, nat stop) str {
nat len = stop - start;
str result = alloc(len) as str;
for (nat i=start; i<stop; i++) {
result[i] = src[i];
}
return result;
}
/**
* Print with a newline
*/
function pln(str string) {
for (byte c in string) {
write = c;
}
write = '\n';
}
/**
* int to string
*/
function itos(int src) str {
byte buffer[6];
nat i = 6;
bool neg = n < 0;
if (neg) n = -n;
do {
buffer[--i] = '0' + n mod 10;
n /= 10;
} while(n > 0);
if(neg) buffer[--i] = '-';
str result = alloc(6 - i) as str;
result[0:] = buffer[i:6 - i];
return result;
}
/**
* nat to string
*/
function ntos(nat src) str {
byte buffer[5];
nat i = 5;
do {
buffer[--i] = '0' + n mod 10;
n /= 10;
} while(n > 0);
str result = alloc(6 - i) as str;
result[0:] = buffer[i:6 - i];
return result;
}
/**
* real to string
*/
function rtos(real src) str {
}
/**
* string to int
*/
function stoi(str src) int {
bool neg = false;
int n = 0;
nat idx = 0;
while (is_space(src[idx])) {
if (length-- == 0) { return n; }
idx = idx + 1;
}
if (src[idx] == '-') {
neg = true;
if (length-- == 0) { return n; }
idx = idx + 1;
}
while (is_digit(src[idx]) and length-- > 0) {
int digit = (src[idx] - '0' as int);
idx = idx + 1;
if (neg) {
if (n < (I16_MIN / 10) or (n == (I16_MIN / 10) and digit > -(I16_MIN mod 10))) {
return I16_MIN;
}
n = n * 10 - digit;
} else {
if (n > (I16_MAX / 10) or (n == (I16_MAX / 10) and digit > (I16_MAX mod 10))) {
return I16_MAX;
}
n = n * 10 + digit;
}
}
return neg ? -n : n;
}
/**
* string to nat
*/
function ston(str src) nat {
nat n = 0;
nat idx = 0;
while (is_space(src[idx])) {
if (length-- == 0) { return n; }
idx = idx + 1;
}
while (is_digit(src[idx]) and length-- > 0) {
nat digit = (src[idx] - '0' as nat);
idx = idx + 1;
if (n > (U16_MAX / 10) or (n == (U16_MAX / 10) and digit > (U16_MAX mod 10))) {
return U16_MAX;
}
n = n * 10 + digit;
}
return n;
}
/**
* string to real
*/
function stor(str src) real {
}