safe-c-std/result.h
Raw file ยท Directory on GitHub
1/* Optional: nothing else in safe-c-std needs it, and safety does not depend on it.
2 A result that is a value or an error, like Rust's Result. Reading the value
3 before checking ok is a compile error, and so is a switch on ok that leaves
4 a case out.
5 typedef RESULT(num, long, enum num_error) num;
6 num parse(struct str s) { ... return ERR(num, NUM_EMPTY); ... return OK(num, v); }
7 num r = parse(s);
8 if (!r.ok) ... r.err ...
9 use(r.value);
10 A result is used: in Safe C dropping one is an error, unless it is cast to (void).
11 TRY(expr, name), like Rust's '?', gives expr's value, or returns its error
12 from a function whose result is struct name. It uses a GNU extension, which
13 gcc and clang have. */
14#ifndef SAFEC_RESULT_H
15#define SAFEC_RESULT_H
16#include "safec.h"
17#include <stdbool.h>
18
19#ifndef SAFEC_MUST_USE
20#if defined(__clang__)
21#define SAFEC_MUST_USE __attribute__((warn_unused_result))
22#else
23#define SAFEC_MUST_USE
24#endif
25#endif
26#define RESULT(name, T, E) \
27 struct SAFEC_MUST_USE name { \
28 bool ok; \
29 union _Tagged_by(ok) { \
30 T value _When(true); \
31 E err _When(false); \
32 }; \
33 }
34#define OK(name, v) ((struct name){.ok = true, .value = (v)})
35#define ERR(name, e) ((struct name){.ok = false, .err = (e)})
36#define TRY(expr, name) \
37 ({ \
38 __typeof__(expr) safec_try_ = (expr); \
39 if (!safec_try_.ok) \
40 return ERR(name, safec_try_.err); \
41 safec_try_.value; \
42 })
43#endif
44