results: prevent dangling cstring pointers in result (#63)
This commit is contained in:
parent
ff524ed832
commit
e15c1ae012
|
@ -304,6 +304,12 @@ template err*[T, E](R: type Result[T, E], x: auto): R =
|
||||||
## Example: `Result[int, string].err("uh-oh")`
|
## Example: `Result[int, string].err("uh-oh")`
|
||||||
R(o: false, e: x)
|
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 =
|
template err*[T](R: type Result[T, void]): R =
|
||||||
R(o: false)
|
R(o: false)
|
||||||
|
|
||||||
|
@ -312,6 +318,10 @@ template err*[T, E](self: var Result[T, E], x: auto) =
|
||||||
## Example: `result.err("uh-oh")`
|
## Example: `result.err("uh-oh")`
|
||||||
self = err(type self, x)
|
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]) =
|
template err*[T](self: var Result[T, void]) =
|
||||||
## Set the result as an error
|
## Set the result as an error
|
||||||
## Example: `result.err()`
|
## Example: `result.err()`
|
||||||
|
|
|
@ -266,3 +266,12 @@ func voidF2(): VoidRes =
|
||||||
ok()
|
ok()
|
||||||
|
|
||||||
doAssert voidF2().isOk
|
doAssert voidF2().isOk
|
||||||
|
|
||||||
|
|
||||||
|
type CSRes = Result[void, cstring]
|
||||||
|
|
||||||
|
func cstringF(s: string): CSRes =
|
||||||
|
when compiles(err(s)):
|
||||||
|
doAssert false
|
||||||
|
|
||||||
|
discard cstringF("test")
|
||||||
|
|
Loading…
Reference in New Issue