1 // Copyright 2018 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <string>
6
7 #include <lib/fit/result.h>
8 #include <unittest/unittest.h>
9
10 namespace {
11 namespace example1 {
divide(int dividend,int divisor)12 fit::result<int, std::string> divide(int dividend, int divisor) {
13 if (divisor == 0)
14 return fit::error<std::string>("divide by zero");
15 return fit::ok(dividend / divisor);
16 }
17
try_divide(int dividend,int divisor)18 int try_divide(int dividend, int divisor) {
19 auto result = divide(dividend, divisor);
20 if (result.is_ok()) {
21 printf("%d / %d = %d\n", dividend, divisor, result.value());
22 return result.value();
23 }
24 printf("%d / %d: ERROR %s\n", dividend, divisor, result.error().c_str());
25 return -999;
26 }
27
open(std::string secret)28 fit::result<> open(std::string secret) {
29 printf("guessing \"%s\"\n", secret.c_str());
30 if (secret == "sesame") {
31 puts("yes!");
32 return fit::ok();
33 }
34 puts("no.");
35 return fit::error();
36 }
37
guess_combination()38 bool guess_combination() {
39 return open("friend") || open("sesame") || open("I give up");
40 }
41
test()42 bool test() {
43 BEGIN_TEST;
44
45 EXPECT_EQ(2, try_divide(5, 2));
46 EXPECT_EQ(-999, try_divide(5, 0));
47 EXPECT_TRUE(guess_combination());
48
49 END_TEST;
50 }
51 } // namespace example1
52 } // namespace
53
54 BEGIN_TEST_CASE(result_examples)
55 RUN_TEST(example1::test)
56 END_TEST_CASE(result_examples)
57