diff options
author | cooldome <cdome@bk.ru> | 2019-08-31 18:23:54 +0100 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2019-08-31 19:23:54 +0200 |
commit | 2b565aad89587114148052eabdd430b923c21394 (patch) | |
tree | e5c70c7a771caabfd2143705e8c33f0010ed296e /tests/iter | |
parent | 9ae0dd611f77c4cd7122e6ac77e0278c1bafbbd7 (diff) | |
download | Nim-2b565aad89587114148052eabdd430b923c21394.tar.gz |
Support iterators returning lent T (#11938)
* lent iterators * rebase tests * update changelog * fix comments, more tests
Diffstat (limited to 'tests/iter')
-rw-r--r-- | tests/iter/tmoditer.nim | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/tests/iter/tmoditer.nim b/tests/iter/tmoditer.nim index 1e6be37e4..34c6321ce 100644 --- a/tests/iter/tmoditer.nim +++ b/tests/iter/tmoditer.nim @@ -27,3 +27,62 @@ for a in items(arr): echo "" +#-------------------------------------------------------------------- +# Lent iterators +#-------------------------------------------------------------------- +type + NonCopyable = object + x: int + + +proc `=destroy`(o: var NonCopyable) = + discard + +proc `=copy`(dst: var NonCopyable, src: NonCopyable) {.error.} + +proc `=sink`(dst: var NonCopyable, src: NonCopyable) = + dst.x = src.x + +iterator lentItems[T](a: openarray[T]): lent T = + for i in 0..a.high: + yield a[i] + +iterator lentPairs[T](a: array[0..1, T]): tuple[key: int, val: lent T] = + for i in 0..a.high: + yield (i, a[i]) + + +let arr1 = [1, 2, 3] +let arr2 = @["a", "b", "c"] +let arr3 = [NonCopyable(x: 1), NonCopyable(x: 2)] +let arr4 = @[(1, "a"), (2, "b"), (3, "c")] + +var accum: string +for x in lentItems(arr1): + accum &= $x +doAssert(accum == "123") + +accum = "" +for x in lentItems(arr2): + accum &= $x +doAssert(accum == "abc") + +accum = "" +for val in lentItems(arr3): + accum &= $val.x +doAssert(accum == "12") + +accum = "" +for i, val in lentPairs(arr3): + accum &= $i & "-" & $val.x & " " +doAssert(accum == "0-1 1-2 ") + +accum = "" +for i, val in lentItems(arr4): + accum &= $i & "-" & $val & " " +doAssert(accum == "1-a 2-b 3-c ") + +accum = "" +for (i, val) in lentItems(arr4): + accum &= $i & "-" & $val & " " +doAssert(accum == "1-a 2-b 3-c ") |