results: prevent dangling cstring pointers in result (#63)

This commit is contained in:
Jacek Sieka 2020-12-09 17:21:12 +01:00 committed by GitHub
parent ff524ed832
commit e15c1ae012
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 0 deletions

View File

@ -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()`

View File

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