Skip to content

Commit

Permalink
Added String_charAt + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
loumadev committed Nov 29, 2023
1 parent 0a1348f commit ac49710
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
9 changes: 9 additions & 0 deletions include/internal/String.h
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,15 @@ bool String_endsWith(String *string, char *value);
*/
long String_indexOf(String *string, char *value);

/**
* Returns the character at a given index in a String.
*
* @param string The String to get the character from.
* @param index The index of the character to get. (negative values start from the end)
* @return The character at the given index.
*/
char String_charAt(String *string, signed long index);

/**
* Copies the contents of the String to a given buffer of a given length.
*
Expand Down
13 changes: 13 additions & 0 deletions src/internal/String.c
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,19 @@ long String_indexOf(String *string, char *value) {
return result - string->value;
}

char String_charAt(String *string, signed long index) {
if(!string) return '\0';
if(!string->value) return '\0';

// Resolve negative indices
if(index < 0) index = string->length + index;

// Index out of bounds
if(index < 0 || index > (signed long)string->length) return '\0';

return string->value[index];
}

void String_copy(String *string, char *dest, size_t length) {
if(!string) return;
if(!dest) return;
Expand Down
35 changes: 35 additions & 0 deletions test/internal/String.test.c
Original file line number Diff line number Diff line change
Expand Up @@ -521,3 +521,38 @@ DESCRIBE(fromRange, "String_fromRange") {
EXPECT_NULL(str);
})
}

DESCRIBE(charAt, "String_charAt") {
String *str = NULL;

TEST("Simple charAt", {
str = String_alloc("Hello, World!");
EXPECT_EQUAL_CHAR(String_charAt(str, 0), 'H');
EXPECT_EQUAL_CHAR(String_charAt(str, 3), 'l');
EXPECT_EQUAL_CHAR(String_charAt(str, 6), ' ');
EXPECT_EQUAL_CHAR(String_charAt(str, 9), 'r');
EXPECT_EQUAL_CHAR(String_charAt(str, 12), '!');
})

TEST("Single character charAt", {
str = String_alloc("A");
EXPECT_EQUAL_CHAR(String_charAt(str, 0), 'A');
})

TEST("Empty charAt", {
str = String_alloc("");
EXPECT_EQUAL_CHAR(String_charAt(str, 0), '\0');
})

TEST("Negative index", {
str = String_alloc("Hello, World!");
EXPECT_EQUAL_CHAR(String_charAt(str, -1), '!');
EXPECT_EQUAL_CHAR(String_charAt(str, -13), 'H');
})

TEST("Out of bounds charAt", {
str = String_alloc("Hello, World!");
EXPECT_EQUAL_CHAR(String_charAt(str, 13), '\0');
EXPECT_EQUAL_CHAR(String_charAt(str, -14), '\0');
})
}

0 comments on commit ac49710

Please sign in to comment.