Result and ? in C
Return a value-or-error result, and pass errors up the way Rust's ? does. A medium embedded C problem (Rust patterns for C programmers), run and graded in…
medium · Rust patterns for C programmers · errors · rust · parsing
Rust returns Result<T, E>: either a value or an error, never both, and the ? operator returns the error to the caller immediately. The same shape in C is a struct holding an error code and a value.
Write:
parse_u8(s, len): parselencharacters of decimal digits into aresult_u8:ERR_EMPTYfor no characters,ERR_DIGITfor any non-digit,ERR_RANGEabove 255, otherwiseOKand the value,parse_rgb(s): parse a colour like"12,200,7"(exactly three numbers separated by commas) by callingparse_u8on each part, and returning the first error unchanged as soon as one part fails (?-style). A wrong number of parts isERR_EMPTY.
Starter code
result_u8 parse_u8(const char *s, int len) {
result_u8 res = { OK, 0 };
int v = 0;
for (int i = 0; i < len; i++) v = v * 10 + (s[i] - '0');
res.value = (uint8_t)v;
return res;
}
result_rgb parse_rgb(const char *s) {
result_rgb out = { OK, 0, 0, 0 };
const char *c1 = strchr(s, ','), *c2 = c1 ? strchr(c1 + 1, ',') : NULL;
if (!c1 || !c2) { out.err = ERR_EMPTY; return out; }
out.r = parse_u8(s, (int)(c1 - s)).value;
out.g = parse_u8(c1 + 1, (int)(c2 - c1 - 1)).value;
out.b = parse_u8(c2 + 1, (int)strlen(c2 + 1)).value;
return out;
}Example tests
Good colours
show("12,200,7");
show("0,0,255");Expected output:
"12,200,7": rgb(12, 200, 7)
"0,0,255": rgb(0, 0, 255)Errors are passed up
show("12,x0,7");
show("12,300,7");
show("12,,7");Expected output:
"12,x0,7": ERR_DIGIT
"12,300,7": ERR_RANGE
"12,,7": ERR_EMPTYLearn it first
- Rust patterns for C programmers · Result and ?, Option, enums as state machines, type-state and calling C.