twrapnils.nim 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import std/wrapnils
  2. const wrapnilExtendedExports = declared(wrapnil)
  3. # for now, wrapnil, isValid, unwrap are not exported
  4. proc checkNotZero(x: float): float =
  5. doAssert x != 0
  6. x
  7. var witness = 0
  8. proc main() =
  9. type Bar = object
  10. b1: int
  11. b2: ptr string
  12. type Foo = ref object
  13. x1: float
  14. x2: Foo
  15. x3: string
  16. x4: Bar
  17. x5: seq[int]
  18. x6: ptr Bar
  19. x7: array[2, string]
  20. x8: seq[int]
  21. x9: ref Bar
  22. type Gook = ref object
  23. foo: Foo
  24. proc fun(a: Bar): auto = a.b2
  25. var a: Foo
  26. var x6 = create(Bar)
  27. x6.b1 = 42
  28. var a2 = Foo(x1: 1.0, x5: @[10, 11], x6: x6)
  29. var a3 = Foo(x1: 1.2, x3: "abc")
  30. a3.x2 = a3
  31. var gook = Gook(foo: a)
  32. proc initFoo(x1: float): auto =
  33. witness.inc
  34. result = Foo(x1: x1)
  35. doAssert ?.a.x2.x2.x1 == 0.0
  36. doAssert ?.a3.x2.x2.x1 == 1.2
  37. doAssert ?.a3.x2.x2.x3[1] == 'b'
  38. doAssert ?.a3.x2.x2.x5.len == 0
  39. doAssert a3.x2.x2.x3.len == 3
  40. when wrapnilExtendedExports:
  41. # example calling wrapnil directly, with and without unwrap
  42. doAssert a3.wrapnil.x2.x2.x3.len == wrapnil(3)
  43. doAssert a3.wrapnil.x2.x2.x3.len.unwrap == 3
  44. doAssert a2.wrapnil.x4.isValid
  45. doAssert not a.wrapnil.x4.isValid
  46. doAssert ?.a.x2.x2.x3[1] == default(char)
  47. # here we only apply wrapnil around gook.foo, not gook (and assume gook is not nil)
  48. doAssert ?.(gook.foo).x2.x2.x1 == 0.0
  49. doAssert ?.a2.x6[] == Bar(b1: 42) # deref for ptr Bar
  50. doAssert ?.a2.x1.checkNotZero == 1.0
  51. doAssert a == nil
  52. # shows that checkNotZero won't be called if a nil is found earlier in chain
  53. doAssert ?.a.x1.checkNotZero == 0.0
  54. # checks that a chain without nil but with an empty seq still throws IndexDefect
  55. doAssertRaises(IndexDefect): discard ?.a2.x8[3]
  56. # make sure no double evaluation bug
  57. doAssert witness == 0
  58. doAssert ?.initFoo(1.3).x1 == 1.3
  59. doAssert witness == 1
  60. # here, it's used twice, to deref `ref Bar` and then `ptr string`
  61. doAssert ?.a.x9[].fun[] == ""
  62. main()