diff --git a/stew/results.nim b/stew/results.nim index 5130729..470e213 100644 --- a/stew/results.nim +++ b/stew/results.nim @@ -304,6 +304,12 @@ template err*[T, E](R: type Result[T, E], x: auto): R = ## Example: `Result[int, string].err("uh-oh")` R(o: false, e: x) +template err*[T](R: type Result[T, cstring], x: string): R = + ## Initialize the result to an error + ## Example: `Result[int, string].err("uh-oh")` + const s = x + R(o: false, e: cstring(s)) + template err*[T](R: type Result[T, void]): R = R(o: false) @@ -312,6 +318,10 @@ template err*[T, E](self: var Result[T, E], x: auto) = ## Example: `result.err("uh-oh")` self = err(type self, x) +template err*[T](self: var Result[T, cstring], x: string) = + const s = x # Make sure we don't return a dangling pointer + self = err(type self, cstring(s)) + template err*[T](self: var Result[T, void]) = ## Set the result as an error ## Example: `result.err()` diff --git a/tests/test_results.nim b/tests/test_results.nim index d6d54a4..b165c03 100644 --- a/tests/test_results.nim +++ b/tests/test_results.nim @@ -266,3 +266,12 @@ func voidF2(): VoidRes = ok() doAssert voidF2().isOk + + +type CSRes = Result[void, cstring] + +func cstringF(s: string): CSRes = + when compiles(err(s)): + doAssert false + +discard cstringF("test")