Simvik

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): parse len characters of decimal digits into a result_u8: ERR_EMPTY for no characters, ERR_DIGIT for any non-digit, ERR_RANGE above 255, otherwise OK and the value,
  • parse_rgb(s): parse a colour like "12,200,7" (exactly three numbers separated by commas) by calling parse_u8 on each part, and returning the first error unchanged as soon as one part fails (?-style). A wrong number of parts is ERR_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_EMPTY

Learn it first