-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
constexpr_test.cc
57 lines (46 loc) · 1.4 KB
/
constexpr_test.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* @file constexpr_test.cc
* @author Basit Ayantunde <[email protected]>
* @date 2020-06-05
*
* @copyright MIT License
*
* Copyright (c) 2020-2022 Basit Ayantunde
*
*/
#include "stx/option.h"
#include "stx/result.h"
#if STX_OPTION_IS_CONSTEXPR && STX_RESULT_IS_CONSTEXPR // check if it'll work
using stx::Ok, stx::Err, stx::Result;
using stx::Some, stx::None, stx::Option;
constexpr auto divide(int x, int y) -> Option<int>
{
if (y == 0)
return None;
return Some(x / y);
}
static_assert(divide(56, 1).unwrap_or_default() == 56);
static_assert(divide(56, 0).unwrap_or_default() == 0);
static_assert(divide(56, 10).match([](int v) { return v; },
[]() { return -1; }) == 5);
static_assert(divide(56, 0).match([](int v) { return v; },
[]() { return -1; }) == -1);
enum class Error
{
Range
};
constexpr auto add(int8_t x, int8_t y) -> Result<int8_t, Error>
{
int16_t acc = x;
acc += y;
if (acc > 127)
return Err(Error::Range);
return Ok((int8_t) acc);
}
static_assert(add(0, 10).unwrap_or_default() == 10);
static_assert(add(127, 1).unwrap_or_default() == 0);
static_assert(add(56, 10).match([](int8_t v) { return v; },
[](Error) { return -1; }) == 66);
static_assert(add(56, 100).match([](int8_t v) { return v; },
[](Error) { return -1; }) == -1);
#endif