From 624ba368dd919e1b75e30866836a7b3ed5907a57 Mon Sep 17 00:00:00 2001 From: Ben Winston Date: Thu, 6 Jun 2024 22:31:35 -0400 Subject: refactor for less looping --- booki.c | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/booki.c b/booki.c index 2bd30bf..6840849 100644 --- a/booki.c +++ b/booki.c @@ -634,19 +634,26 @@ char* next_book(char* current_pos) { char* characters_from_end(char* str, int len, int number_of_chars) { assert(len >= number_of_chars); - int retchars = number_of_chars; - char* newptr = str + len - 1; + + // let's not zoom past the beginning of the string + if (number_of_chars == 0) + return str; + + // start at the end of the string, locate all code points + char* newptr = str + len; // will update to last character in do..while unsigned char ch; - int total_bytes = 0; - while (number_of_chars > 0) { + do { + // update the pointer, get the character + newptr--; + len--; ch = (unsigned char) *newptr; - // if we're at the first byte of a unicode point, adjust + + // if we're at the first byte of a unicode point, we've found a whole character if (ch < 0x80 || ch >= 0xC3) number_of_chars--; - newptr--; - total_bytes++; - } - return newptr + 1; + } while (number_of_chars > 0 && len > 0); + + return newptr; } /*** search ***/ -- cgit v1.2.3