topenarrays.nim 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. proc mutate(a: var openarray[int]) =
  2. var i = 0
  3. for x in a.mitems:
  4. x = i
  5. inc i
  6. proc mutate(a: var openarray[char]) =
  7. var i = 1
  8. for ch in a.mitems:
  9. ch = 'a'
  10. static:
  11. var a = [10, 20, 30]
  12. assert a.toOpenArray(1, 2).len == 2
  13. mutate(a)
  14. assert a.toOpenArray(0, 2) == [0, 1, 2]
  15. assert a.toOpenArray(0, 0) == [0]
  16. assert a.toOpenArray(1, 2) == [1, 2]
  17. assert "Hello".toOpenArray(1, 4) == "ello"
  18. var str = "Hello"
  19. str.toOpenArray(2, 4).mutate()
  20. assert str.toOpenArray(0, 4).len == 5
  21. assert str.toOpenArray(0, 0).len == 1
  22. assert str.toOpenArray(0, 0).high == 0
  23. assert str == "Heaaa"
  24. assert str.toOpenArray(0, 4) == "Heaaa"
  25. var arr: array[3..4, int] = [1, 2]
  26. assert arr.toOpenArray(3, 4) == [1, 2]
  27. assert arr.toOpenArray(3, 4).len == 2
  28. assert arr.toOpenArray(3, 3).high == 0
  29. assert arr.toOpenArray(3, 4).toOpenArray(0, 0) == [1]
  30. proc doThing(s: static openArray[int]) = discard
  31. doThing([10, 20, 30].toOpenArray(0, 0))
  32. # bug #19969
  33. proc f(): array[1, byte] =
  34. var a: array[1, byte]
  35. result[0..0] = a.toOpenArray(0, 0)
  36. doAssert static(f()) == [byte(0)]
  37. # bug #15952
  38. proc main1[T](a: openArray[T]) = discard
  39. proc main2[T](a: var openArray[T]) = discard
  40. proc main =
  41. var a = [1,2,3,4,5]
  42. main1(a.toOpenArray(1,3))
  43. main2(a.toOpenArray(1,3))
  44. static: main()
  45. main()
  46. # bug #16306
  47. {.experimental: "views".}
  48. proc test(x: openArray[int]): tuple[id: int] =
  49. let y: openArray[int] = toOpenArray(x, 0, 2)
  50. result = (y[0],)
  51. template fn=
  52. doAssert test([0,1,2,3,4,5]).id == 0
  53. fn() # ok
  54. static: fn()
  55. block: # bug #22095
  56. type
  57. StUint = object
  58. limbs: array[4, uint64]
  59. func shlAddMod(a: var openArray[uint64]) =
  60. a[0] = 10
  61. func divRem(r: var openArray[uint64]) =
  62. shlAddMod(r.toOpenArray(0, 3))
  63. func fn(): StUint =
  64. divRem(result.limbs)
  65. const
  66. z = fn()
  67. doAssert z.limbs[0] == 10