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" -