typeclassborrow.nim 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import std/tables
  2. type
  3. Foo = distinct seq[int]
  4. Bar[N: static[int]] = distinct seq[int]
  5. Baz = distinct Bar[10]
  6. proc newSeq(s: var Foo, n: Natural) {.borrow.}
  7. proc newSeq(s: var Bar, n: Natural) {.borrow.}
  8. proc newSeq(s: var Baz, n: Natural) {.borrow.}
  9. proc `$`(s: Foo): string {.borrow.}
  10. proc `$`(s: Bar): string {.borrow.}
  11. proc `$`(s: Baz): string {.borrow.}
  12. proc doThing(b: Bar) = discard
  13. proc doThing(b: Baz) {.borrow.}
  14. var
  15. foo: Foo
  16. bar: Bar[10]
  17. baz: Baz
  18. newSeq(foo, 100)
  19. newSeq(bar, bar.N)
  20. newSeq(baz, 10)
  21. bar.doThing()
  22. baz.doThing()
  23. assert $seq[int](foo) == $foo
  24. assert $seq[int](bar) == $bar
  25. assert $seq[int](baz) == $baz
  26. type
  27. Fine* = distinct string
  28. proc `==`*(x, y: Fine): bool {.borrow.} =
  29. ## Here is the documentation
  30. runnableExamples:
  31. var x = Fine("1234")
  32. var y = Fine("1234")
  33. doAssert x == y
  34. doAssert false
  35. var x = Fine("1234")
  36. var y = Fine("1234")
  37. doAssert x == y
  38. block: # bug #22902
  39. type
  40. DistinctTable = distinct Table[int, int]
  41. proc `[]`(t: DistinctTable; key: int): lent int {.borrow.}