From 38af645d492349c9ba3204e2e1c6a460113af3d0 Mon Sep 17 00:00:00 2001 From: Maxime Chevalier-Boisvert Date: Sat, 11 Nov 2023 14:13:43 -0500 Subject: [PATCH] Add strcasecmp() to string.h --- ncc/examples/mini_bbs.c | 18 +++++++++--------- ncc/include/string.h | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/ncc/examples/mini_bbs.c b/ncc/examples/mini_bbs.c index ac3c0ff..431f072 100644 --- a/ncc/examples/mini_bbs.c +++ b/ncc/examples/mini_bbs.c @@ -352,16 +352,12 @@ void on_incoming_data(u64 socket_id, u64 num_bytes) if (p_user->state == STATE_WRITE_MSG) { - bool done = ( - strcmp(read_buf, "Done\n") == 0 || - strcmp(read_buf, "Done\r\n") == 0 || - strcmp(read_buf, "done\n") == 0 || - strcmp(read_buf, "done\r\n") == 0 - ); + // Strip trailing whitespace from the buffer + rstrip_ws(read_buf); - if (done) + if (strcasecmp(read_buf, "done") == 0) { - // Strip trailing whitespace + // Strip trailing whitespace in the message buffer rstrip_ws(p_user->msg_buf); // If this is an empty message, do nothing @@ -386,9 +382,13 @@ void on_incoming_data(u64 socket_id, u64 num_bytes) return; } + // Add back a newline on the message buffer because + // we stripped whitespace earlier + strncat(p_user->msg_buf, "\n", 1); + + // Append new line to the user's message buffer size_t msg_len = strlen(p_user->msg_buf); size_t len = strlen(read_buf); - size_t max_chars = MAX_MSG_LEN - 1 - msg_len; strncat(p_user->msg_buf, read_buf, max_chars); diff --git a/ncc/include/string.h b/ncc/include/string.h index b19b4c1..d55d4ad 100644 --- a/ncc/include/string.h +++ b/ncc/include/string.h @@ -2,6 +2,7 @@ #define __STRING_H__ #include +#include #ifndef memcpy #define memcpy(dst, src, num_bytes) asm (dst, src, num_bytes) -> void { syscall memcpy; } @@ -37,6 +38,27 @@ int strcmp(char* a, char* b) return 0; } +// Perform case-insensitive string comparison +// This function is non-standard, but offered by many compilers. +int strcasecmp(char* a, char* b) +{ + for (size_t i = 0;; ++i) + { + char ch_a = tolower(a[i]); + char ch_b = tolower(b[i]); + + if (ch_a < ch_b) + return -1; + else if (ch_a > ch_b) + return 1; + + if (ch_a == 0) + break; + } + + return 0; +} + int strncmp(char* a, char* b, size_t num) { for (size_t i = 0; i < num; ++i)