Skip to content

Commit

Permalink
Implement getline and atoi
Browse files Browse the repository at this point in the history
  • Loading branch information
elimirks committed Dec 7, 2022
1 parent fece23b commit fc42c95
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 1 deletion.
70 changes: 69 additions & 1 deletion assets/stdlib.b
Original file line number Diff line number Diff line change
Expand Up @@ -344,4 +344,72 @@ sys_fork() {

sys_execve(filename, argv, envp) {
return(syscall(59, filename, argv, envp));
}
}

/* Parses an int out of a string.
* Warning: Will return 0 for invalid ints!
*/
atoi(s) {
auto ptr, len, value 0, isNegative 0;
len = strlen(s);
ptr = s;
if (len == 0) {
return(0);
}
if ((*ptr & 0377) == '-') {
isNegative = 1;
ptr =+ 1;
}
while (((*ptr & 0377) >= '0') & ((*ptr & 0377) <= '9')) {
value =* 10;
value =+ (*ptr & 0377) - '0';
ptr =+ 1;
}
if (isNegative) {
return(-value);
} else {
return(value);
}
}

/*
* Similar to the C implementation.
* @see https://linux.die.net/man/3/getline
*/
getline(buf, buflen, fd) {
if (*buf == 0) {
/* 32 bytes for the initial buffer */
*buflen = 32;
*buf = malloc(*buflen / 8);
}

auto bufptr;
bufptr = *buf;

while (1) {
auto nread;
nread = syscall(0, fd, bufptr, 1);
if (nread < 0) {
panic("Failed reading file");
}
if (nread == 0) {
*bufptr = 0;
auto len;
len = bufptr - *buf;
if (len == 0) {
return(-1);
} else {
return(len);
}
} else if ((*bufptr & 0377) == '*n') {
*bufptr = 0;
return(bufptr - *buf);
}
bufptr =+ 1;
if (bufptr - *buf >= *buflen) {
*buflen =+ 32;
/* printf("Resized to %d*n", *buflen); */
*buf = realloc(*buf, *buflen / 8);
}
}
}
15 changes: 15 additions & 0 deletions examples/lazyquine.b
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#import "../assets/stdlib.b";

main() {
auto fd;
fd = syscall(2, "examples/lazyquine.b", 0, 0);
if (fd < 0) {
panic("Failed opening file.");
}
auto buf 0;
auto bufsize 0;
while (getline(&buf, &bufsize, fd) != -1) {
printf("%s*n", buf);
}
free(buf);
}
11 changes: 11 additions & 0 deletions test/atoi.b
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#import "../assets/best.b";

main() {
assert_eq_int(42, atoi("42"));
assert_eq_int(0, atoi("x42"));
assert_eq_int(1234567890, atoi("1234567890"));
assert_eq_int(42, atoi("42abc"));
assert_eq_int(-42, atoi("-42"));
assert_eq_int(0, atoi("-"));
assert_eq_int(0, atoi("-abch1234"));
}
9 changes: 9 additions & 0 deletions test/strops.b
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,18 @@ test_strcat() {
);
}

test_strlen() {
assert_eq_int(4, strlen("abcd"));
assert_eq_int(4, strlen("abcd*0efg"));
assert_eq_int(8, strlen("12345678*0abcd"));
assert_eq_int(0, strlen("*012345678"));
assert_eq_int(0, strlen(""));
}

main() {
test_charlen();
test_charcmp();
test_strcmp();
test_strcat();
test_strlen();
}

0 comments on commit fc42c95

Please sign in to comment.