Skip to content

Commit

Permalink
Implement strcat in stdlib
Browse files Browse the repository at this point in the history
  • Loading branch information
elimirks committed Dec 26, 2021
1 parent 02702ad commit 304f77a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
25 changes: 24 additions & 1 deletion assets/stdlib.b
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,32 @@ charcmp(c1, c2) {
}
/*
* Returns a malloc'd new string!
* Concatenates the two given strings.
* @return a malloc'd new string
*/
strcat(s1, s2) {
auto s1len, s2len, s2lastIndex, newLen, newQuadLen, new, newptr;
s1len = strlen(s1);
s2len = strlen(s2);
/* +1 in case we need it for a null byte.
* Since we round up for newQuadLen, this
* won't ever needlessly allocate an extra quad.
*/
newLen = s1len + s2len + 1;
/* Allocate number of quads we need */
newQuadLen = ((newLen + 7) & ~7) >> 3;
new = malloc(newQuadLen);
memmove(new, s1, ((s1len + 7) & ~7) >> 3);
s2lastIndex = ((s2len + 7) & ~7) >> 3;
newptr = new + s1len;
memmove(newptr, s2, s2lastIndex);
/* Must manually null terminate if s2len is a multiple of 8 */
if ((s2len & 255) == 0) {
new[newQuadLen - 1] = 0;
}
return(new);
}
/**
Expand Down
5 changes: 5 additions & 0 deletions test/strops.b
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ show_strcmp() {
putstr("*n");
}

show_strcat() {
putstr(strcat("Hello Mars, ", "goodbye Earth*n"));
}

main() {
show_strcmp();
show_strcat();
}

0 comments on commit 304f77a

Please sign in to comment.