tviews1.nim 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. discard """
  2. output: '''11
  3. 22
  4. 33
  5. 3
  6. 2
  7. 3
  8. 3
  9. 15
  10. (oa: [1, 3, 4])'''
  11. targets: "c cpp"
  12. """
  13. {.experimental: "views".}
  14. proc take(a: openArray[int]) =
  15. echo a.len
  16. proc main(s: seq[int]) =
  17. var x: openArray[int] = s
  18. for i in 0 .. high(x):
  19. echo x[i]
  20. take(x)
  21. take(x.toOpenArray(0, 1))
  22. let y = x
  23. take y
  24. take x
  25. main(@[11, 22, 33])
  26. var x: int
  27. proc foo(x: var int): var int =
  28. once: x = 42
  29. return x
  30. var y: var int = foo(x)
  31. y = 15
  32. echo foo(x)
  33. # bug #16132
  34. # bug #18690
  35. type
  36. F = object
  37. oa: openArray[int]
  38. let s1 = @[1,3,4,5,6]
  39. var test = F(oa: toOpenArray(s1, 0, 2))
  40. echo test
  41. type
  42. Foo = object
  43. x: string
  44. y: seq[int]
  45. data: array[10000, byte]
  46. View[T] = object
  47. x: lent T
  48. proc mainB =
  49. let f = Foo(y: @[1, 2, 3])
  50. let foo = View[Foo](x: f)
  51. assert foo.x.x == ""
  52. assert foo.x.y == @[1, 2, 3]
  53. mainB()
  54. # bug #15897
  55. type Outer = ref object
  56. value: int
  57. type Inner = object
  58. owner: var Outer
  59. var o = Outer(value: 1234)
  60. var v = Inner(owner: o).owner.value
  61. doAssert v == 1234
  62. block: # bug #21674
  63. type
  64. Lent = object
  65. data: lent int
  66. proc foo(s: Lent) =
  67. var m = 12
  68. discard cast[lent int](m)
  69. proc main =
  70. var m1 = 123
  71. var x = Lent(data: m1)
  72. foo(x)
  73. main()
  74. block: # bug #22117
  75. proc main: int =
  76. var a = 10
  77. defer: discard a # extend a's lifetime
  78. var aref: var int = a
  79. #└──── 'aref' borrows from location 'a' which does not live long enough
  80. result = aref
  81. doAssert main() == 10
  82. type
  83. Slice*[T] = object
  84. first, last: int
  85. p: ptr UncheckedArray[T]
  86. var i = 0
  87. converter autoToOpenArray*[T](s: Slice[T]): openArray[T] =
  88. inc i
  89. result = toOpenArray(s.p, s.first, s.last)
  90. proc acceptOpenArray(s: openArray[byte]) = discard
  91. proc bug22597 = # bug #22597
  92. acceptOpenArray(Slice[byte]())
  93. doAssert i == 1
  94. bug22597()
  95. block: # bug #20048
  96. type
  97. Test = object
  98. tokens: openArray[string]
  99. func init(Self: typedesc[Test], tokens: openArray[string]): Self = Self(tokens: tokens)
  100. let data = Test.init(["123"])
  101. doAssert @(data.tokens) == @["123"]