topenarrays.nim 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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()