Skip to content

Commit 5e11362

Browse files
committed
perf: avoid heap allocation in OLED drawString
1 parent c2aae65 commit 5e11362

1 file changed

Lines changed: 22 additions & 11 deletions

File tree

src/helpers/ui/OLEDDisplay.cpp

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -619,11 +619,8 @@ uint16_t OLEDDisplay::drawStringInternal(int16_t xMove, int16_t yMove, const cha
619619

620620
uint16_t OLEDDisplay::drawString(int16_t xMove, int16_t yMove, const String &strUser) {
621621
uint16_t lineHeight = pgm_read_byte(fontData + HEIGHT_POS);
622-
623-
// char* text must be freed!
624-
char* text = strdup(strUser.c_str());
625-
if (!text) {
626-
DEBUG_OLEDDISPLAY("[OLEDDISPLAY][drawString] Can't allocate char array.\n");
622+
const char* text = strUser.c_str();
623+
if (text == nullptr) {
627624
return 0;
628625
}
629626

@@ -642,13 +639,27 @@ uint16_t OLEDDisplay::drawString(int16_t xMove, int16_t yMove, const String &str
642639

643640
uint16_t charDrawn = 0;
644641
uint16_t line = 0;
645-
char* textPart = strtok(text,"\n");
646-
while (textPart != NULL) {
647-
uint16_t length = strlen(textPart);
648-
charDrawn += drawStringInternal(xMove, yMove - yOffset + (line++) * lineHeight, textPart, length, getStringWidth(textPart, length, true), true);
649-
textPart = strtok(NULL, "\n");
642+
const char* lineStart = text;
643+
while (true) {
644+
const char* lineEnd = lineStart;
645+
while (*lineEnd != 0 && *lineEnd != '\n') {
646+
lineEnd++;
647+
}
648+
649+
if (lineEnd == lineStart && *lineEnd == '\n') {
650+
lineStart = lineEnd + 1;
651+
continue;
652+
}
653+
654+
uint16_t length = lineEnd - lineStart;
655+
charDrawn += drawStringInternal(xMove, yMove - yOffset + (line++) * lineHeight, lineStart, length,
656+
getStringWidth(lineStart, length, true), true);
657+
658+
if (*lineEnd == 0) {
659+
break;
660+
}
661+
lineStart = lineEnd + 1;
650662
}
651-
free(text);
652663
return charDrawn;
653664
}
654665

0 commit comments

Comments
 (0)