undar-lang/test/str.ul

129 lines
1.9 KiB
Plaintext

/**
* Constants
*/
const str nl = "\n";
/**
* Print with a newline
*/
function pln(str string) {
for (byte c in string) {
putchar(c);
}
putchar(nl);
}
/**
* Concatinates 2 strings
*/
function concat(str src1, str src2) str {
str result = malloc(src1.length + src2.length);
memcpy(result[0].ptr, src1.ptr);
memcpy(result[src1.length].ptr, src2.ptr);
return result;
}
/**
* finds index of string, -1 if not found
*/
function str_index_of(str haystack, byte needle) int {
int i = -1;
for (byte c in haystack) {
i = i + 1;
if (c == needle) {
break;
}
}
return i;
}
/**
* checks if 2 strings are equal
*/
function str_eq(str src1, str src2) bool {
if (src1.length != src2.length) return false;
for (int i=0; src1.length; i++) {
if (src1[i] != src2[i]) return false;
}
return true;
}
/**
* Slice string
*/
function str_slice(str src, int start, int stop) str {
int len = stop - start;
str result = malloc(len);
for (int i=start; i<stop; i++) {
result[i] = src[i];
}
return result;
}
/**
* 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 % 10;
n /= 10;
} while(n > 0);
if(neg) buffer[--i] = '-';
str result = malloc(6 - i);
memcpy(result, buffer[0].ptr + i, 6 - i);
return result;
}
/**
* nat to string
*/
function ntos(nat src) str {
byte buffer[5];
nat i = 5;
do {
buffer[--i] = '0' + n % 10;
n /= 10;
} while(n > 0);
str result = malloc(5 - i);
memcpy(result, buffer[0].ptr + i, 5 - i);
return result;
}
/**
* real to string
*/
function rtos(real src) str {
}
/**
* string to int
*/
function stoi(str src) int {
}
/**
* string to nat
*/
function ston(str src) nat {
}
/**
* string to real
*/
function stor(str src) real {
}