Skip to content

Commit ab21d41

Browse files
Explorer09BenBE
authored andcommitted
Use size_t for offsets in Text & Graph meter routines
Don't assume a meter's caption string length will fit the type of 'int'. Use 'size_t' for the string lengths instead. Even though an overflow on the string length is unlikely, this makes the code more robust. Signed-off-by: Kang-Che Sung <explorer09@gmail.com>
1 parent 9a72f1c commit ab21d41

1 file changed

Lines changed: 19 additions & 12 deletions

File tree

Meter.c

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -49,16 +49,19 @@ static inline void Meter_displayBuffer(const Meter* this, RichString* out) {
4949
/* ---------- TextMeterMode ---------- */
5050

5151
static void TextMeterMode_draw(Meter* this, int x, int y, int w) {
52+
if (w <= 0)
53+
return;
54+
5255
const char* caption = Meter_getCaption(this);
5356
attrset(CRT_colors[METER_TEXT]);
5457
mvaddnstr(y, x, caption, w);
5558
attrset(CRT_colors[RESET_COLOR]);
5659

57-
int captionLen = strlen(caption);
58-
x += captionLen;
59-
w -= captionLen;
60-
if (w <= 0)
60+
size_t captionLen = strlen(caption);
61+
if ((size_t)w <= captionLen)
6162
return;
63+
x += (int)captionLen;
64+
w -= (int)captionLen;
6265

6366
RichString_begin(out);
6467
Meter_displayBuffer(this, &out);
@@ -301,6 +304,10 @@ static void LEDMeterMode_drawDigit(int x, int y, int n) {
301304
}
302305

303306
static void LEDMeterMode_draw(Meter* this, int x, int y, int w) {
307+
assert(x >= 0);
308+
if (w <= 0)
309+
return;
310+
304311
#ifdef HAVE_LIBNCURSESW
305312
if (CRT_utf8)
306313
LEDMeterMode_digits = LEDMeterMode_digitsUtf8;
@@ -318,25 +325,25 @@ static void LEDMeterMode_draw(Meter* this, int x, int y, int w) {
318325
y + 2;
319326
attrset(CRT_colors[LED_COLOR]);
320327
const char* caption = Meter_getCaption(this);
321-
mvaddstr(yText, x, caption);
322-
int xx = x + strlen(caption);
328+
mvaddnstr(yText, x, caption, w);
329+
size_t xx = (size_t)x + strlen(caption);
323330
int len = RichString_sizeVal(out);
324-
for (int i = 0; i < len; i++) {
331+
for (size_t i = 0; i < (size_t)len; i++) {
325332
int c = RichString_getCharVal(out, i);
326333
if (c >= '0' && c <= '9') {
327-
if (xx - x + 4 > w)
334+
if (xx + 4 > (unsigned int)x + (unsigned int)w)
328335
break;
329336

330-
LEDMeterMode_drawDigit(xx, y, c - '0');
337+
LEDMeterMode_drawDigit((int)xx, y, c - '0');
331338
xx += 4;
332339
} else {
333-
if (xx - x + 1 > w)
340+
if (xx + 1 > (unsigned int)x + (unsigned int)w)
334341
break;
335342
#ifdef HAVE_LIBNCURSESW
336343
const cchar_t wc = { .chars = { c, '\0' }, .attr = 0 }; /* use LED_COLOR from attrset() */
337-
mvadd_wch(yText, xx, &wc);
344+
mvadd_wch(yText, (int)xx, &wc);
338345
#else
339-
mvaddch(yText, xx, c);
346+
mvaddch(yText, (int)xx, c);
340347
#endif
341348
xx += 1;
342349
}

0 commit comments

Comments
 (0)