better support for slices as views (#15414)

* moved view tests to tests/views
* refactoring
* more refactorings
* better support for system.toOpenArray for first class view types
This commit is contained in:
Andreas Rumpf 2020-09-27 09:20:10 +02:00 • committed by GitHub
commit 57b7841c18
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 100 additions and 44 deletions

View file

@ -0,0 +1,18 @@
discard """
errormsg: "cannot borrow"
nimout: '''tcannot_borrow.nim(16, 7) Error: cannot borrow meh; what it borrows from is potentially mutated
tcannot_borrow.nim(17, 3) the mutation is here
tcannot_borrow.nim(16, 7) is the statement that connected the mutation to the parameter'''
line: 16
"""
{.experimental: "views".}
type
Foo = object
field: string
proc dangerous(s: var seq[Foo]) =
let meh: lent Foo = s[0]
s.setLen 0
echo meh.field

View file

@ -0,0 +1,37 @@
discard """
output: '''asdf
231
'''
cmd: "nim c --gc:arc -d:useMalloc -g $file"
valgrind: true
"""
{.experimental: "views".}
const
Whitespace = {' ', '\t', '\n', '\r'}
iterator split*(s: string, seps: set[char] = Whitespace,
maxsplit: int = -1): openArray[char] =
var last = 0
var splits = maxsplit
while last <= len(s):
var first = last
while last < len(s) and s[last] notin seps:
inc(last)
if splits == 0: last = len(s)
yield toOpenArray(s, first, last-1)
if splits == 0: break
dec(splits)
inc(last)
proc `$`(x: openArray[char]): string =
result = newString(x.len)
for i in 0..<x.len: result[i] = x[i]
proc main() =
for x in split("asdf 231"):
echo x
main()

27
tests/views/tviews1.nim Normal file
View file

@ -0,0 +1,27 @@
discard """
output: '''11
22
33
3
2
3'''
targets: "c cpp"
"""
{.experimental: "views".}
proc take(a: openArray[int]) =
echo a.len
proc main(s: seq[int]) =
var x: openArray[int] = s
for i in 0 .. high(x):
echo x[i]
take(x)
take(x.toOpenArray(0, 1))
let y = x
take y
main(@[11, 22, 33])