Skip to content

[rtext] Use libc for TextLength(), TextCopy(), TextSubtext() and TextInsert() #4911

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 11 additions & 26 deletions src/rtext.c
Original file line number Diff line number Diff line change
Expand Up @@ -1401,9 +1401,7 @@ unsigned int TextLength(const char *text)

if (text != NULL)
{
// NOTE: Alternative: use strlen(text)

while (*text++) length++;
length = strlen(text);
}

return length;
Expand Down Expand Up @@ -1497,20 +1495,13 @@ int TextCopy(char *dst, const char *src)
{
int bytes = 0;

if ((src != NULL) && (dst != NULL))
// strcpy is marked restrict, meaning src and dst must not alias.
// Attempt to defend against that, but this is not fully robust
// as someone could pass in two sub-portions of the same string.
Copy link
Author

@williewillus williewillus Apr 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note that this is also already a problem with the preexisting code, so we aren't necessarily regressing here

if ((src != NULL) && (dst != NULL) && (src != dst))
{
// NOTE: Alternative: use strcpy(dst, src)

while (*src != '\0')
{
*dst = *src;
dst++;
src++;

bytes++;
}

*dst = '\0';
strcpy(dst, src);
bytes = strlen(src);
}

return bytes;
Expand Down Expand Up @@ -1547,13 +1538,7 @@ const char *TextSubtext(const char *text, int position, int length)
if (length > maxLength) length = maxLength;
if (length >= MAX_TEXT_BUFFER_LENGTH) length = MAX_TEXT_BUFFER_LENGTH - 1;

// NOTE: Alternative: memcpy(buffer, text + position, length)

for (int c = 0 ; c < length ; c++)
{
buffer[c] = text[position + c];
}

memcpy(buffer, text + position, length);
buffer[length] = '\0';

return buffer;
Expand Down Expand Up @@ -1618,9 +1603,9 @@ char *TextInsert(const char *text, const char *insert, int position)

char *result = (char *)RL_MALLOC(textLen + insertLen + 1);

for (int i = 0; i < position; i++) result[i] = text[i];
for (int i = position; i < insertLen + position; i++) result[i] = insert[i];
for (int i = (insertLen + position); i < (textLen + insertLen); i++) result[i] = text[i];
memcpy(result, text, position);
memcpy(result + position, insert, insertLen);
memcpy(result + position + insertLen, text + position, textLen - position);

result[textLen + insertLen] = '\0'; // Make sure text string is valid!

Expand Down