Skip to content

Commit d085e48

Browse files
authored
results: add mapConvertErr, mapCastErr (#178)
We already have `mapConvert` and `mapCast` - this completes the API with corresponding `Err` versions similar to `mapErr`. The `Convert` / `Cast` operators are of somewhat dubious value - ie they exist as "efficiency" shortcuts for `map` for the case that the mapping should be done as a simple cast / conversion - an alternative would be to deprecate these features and aim for some other, more generic version that involves a type conversion library such as #34, though this inherently, and perhaps rightly, would be limited to "error-free" conversions. Regardless, these helpers provide balance to the existing API.
1 parent 9958aac commit d085e48

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

stew/results.nim

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,36 @@ func mapCast*[T0: not void, E](
628628
else:
629629
result.err(self.eResultPrivate)
630630

631+
func mapConvertErr*[T, E0](
632+
self: Result[T, E0], E1: type): Result[T, E1] {.inline.} =
633+
## Convert result error to E1 using an conversion
634+
# Would be nice if it was automatic...
635+
when E0 is E1:
636+
result = self
637+
else:
638+
if self.oResultPrivate:
639+
when T is void:
640+
result.ok()
641+
else:
642+
result.ok(self.vResultPrivate)
643+
else:
644+
when E1 is void:
645+
result.err()
646+
else:
647+
result.err(E1(self.eResultPrivate))
648+
649+
func mapCastErr*[T, E0](
650+
self: Result[T, E0], E1: type): Result[T, E1] {.inline.} =
651+
## Convert result value to A using a cast
652+
## Would be nice with nicer syntax...
653+
if self.oResultPrivate:
654+
when T is void:
655+
result.ok()
656+
else:
657+
result.ok(self.vResultPrivate)
658+
else:
659+
result.err(cast[E1](self.eResultPrivate))
660+
631661
template `and`*[T0, E, T1](self: Result[T0, E], other: Result[T1, E]): Result[T1, E] =
632662
## Evaluate `other` iff self.isOk, else return error
633663
## fail-fast - will not evaluate other if a is an error

tests/test_results.nim

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,9 @@ block:
131131
doAssert (rErr.orErr(32)).error == 32
132132
doAssert (rOk.orErr(failFast())).get() == rOk.get()
133133

134+
doAssert rErr.mapConvertErr(cstring).error() == cstring(rErr.error())
135+
doAssert rErr.mapCastErr(seq[byte]).error() == cast[seq[byte]](rErr.error())
136+
134137
# string conversion
135138
doAssert $rOk == "ok(42)"
136139
doAssert $rErr == "err(dummy)"

0 commit comments

Comments
 (0)