From dad28a269fa0838635a0310f9d1456680f7bbff5 Mon Sep 17 00:00:00 2001 From: Jacek Sieka Date: Fri, 17 Jun 2022 12:45:22 +0200 Subject: [PATCH] result: add `Opt.some` / `Opt.none` (#117) --- stew/results.nim | 18 ++++++++++++++++++ tests/test_results.nim | 4 +++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/stew/results.nim b/stew/results.nim index 99bb5e2..b3e6a26 100644 --- a/stew/results.nim +++ b/stew/results.nim @@ -884,6 +884,24 @@ func filter*[T]( # Options compatibility +template some*[T](O: type Opt, v: T): Opt[T] = + ## Create an `Opt` set to a value + ## + ## ``` + ## let o = Opt.some(42) + ## assert o.isSome and o.get() == 42 + ## ``` + Opt[T].ok(v) + +template none*(O: type Opt, T: type): Opt[T] = + ## Create an `Opt` set to none + ## + ## ``` + ## let o = Opt.none(int) + ## assert o.isNone + ## ``` + Opt[T].err() + template isSome*(o: Opt): bool = ## Alias for `isOk` isOk o diff --git a/tests/test_results.nim b/tests/test_results.nim index 7d5734e..f6eb3e3 100644 --- a/tests/test_results.nim +++ b/tests/test_results.nim @@ -351,6 +351,9 @@ block: # Result[T, void] aka `Opt` doAssert oOk.filter(proc(x: int): bool = false).isErr() doAssert oErr.filter(proc(x: int): bool = true) == oErr + doAssert Opt.some(42).get() == 42 + doAssert Opt.none(int).isNone() + block: # `cstring` dangling reference protection type CSRes = Result[void, cstring] @@ -398,4 +401,3 @@ block: # Experiments counter2 += 1 doAssert counter2 == 1, "one-item collection when set" -