wrapnils: add ??. which returns an Option (#16931)

* wrapnils: add option-like API with ??., isSome, get
* fix test after rebase
* cleanups
* fix changelog
* address comments regarding get vs unsafeGet
This commit is contained in:
Timothee Cour
2021-02-24 05:02:32 -08:00
committed by GitHub
parent 11a7fa68f6
commit 8942586fa6
3 changed files with 73 additions and 67 deletions

View File

@@ -1,15 +1,11 @@
import std/wrapnils
const wrapnilExtendedExports = declared(wrapnil)
# for now, wrapnil, isValid, unwrap are not exported
proc checkNotZero(x: float): float =
doAssert x != 0
x
var witness = 0
proc main() =
var witness = 0
type Bar = object
b1: int
b2: ptr string
@@ -31,8 +27,12 @@ proc main() =
proc fun(a: Bar): auto = a.b2
var a: Foo
var x6 = create(Bar)
x6.b1 = 42
var x6: ptr Bar
when nimvm: discard # pending https://github.com/timotheecour/Nim/issues/568
else:
x6 = create(Bar)
x6.b1 = 42
var a2 = Foo(x1: 1.0, x5: @[10, 11], x6: x6)
var a3 = Foo(x1: 1.2, x3: "abc")
a3.x2 = a3
@@ -50,26 +50,23 @@ proc main() =
doAssert ?.a3.x2.x2.x5.len == 0
doAssert a3.x2.x2.x3.len == 3
when wrapnilExtendedExports:
# example calling wrapnil directly, with and without unwrap
doAssert a3.wrapnil.x2.x2.x3.len == wrapnil(3)
doAssert a3.wrapnil.x2.x2.x3.len.unwrap == 3
doAssert a2.wrapnil.x4.isValid
doAssert not a.wrapnil.x4.isValid
doAssert ?.a.x2.x2.x3[1] == default(char)
# here we only apply wrapnil around gook.foo, not gook (and assume gook is not nil)
doAssert ?.(gook.foo).x2.x2.x1 == 0.0
doAssert ?.a2.x6[] == Bar(b1: 42) # deref for ptr Bar
when nimvm: discard
else:
doAssert ?.a2.x6[] == Bar(b1: 42) # deref for ptr Bar
doAssert ?.a2.x1.checkNotZero == 1.0
doAssert a == nil
# shows that checkNotZero won't be called if a nil is found earlier in chain
doAssert ?.a.x1.checkNotZero == 0.0
# checks that a chain without nil but with an empty seq still throws IndexDefect
doAssertRaises(IndexDefect): discard ?.a2.x8[3]
when nimvm: discard
else:
# checks that a chain without nil but with an empty seq still raises
doAssertRaises(IndexDefect): discard ?.a2.x8[3]
# make sure no double evaluation bug
doAssert witness == 0
@@ -79,4 +76,10 @@ proc main() =
# here, it's used twice, to deref `ref Bar` and then `ptr string`
doAssert ?.a.x9[].fun[] == ""
block: # `??.`
doAssert (??.a3.x2.x2.x3.len).get == 3
doAssert (??.a2.x4).isSome
doAssert not (??.a.x4).isSome
main()
static: main()