Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with openarrays and slices #4179

Closed
zeitbit opened this issue May 17, 2016 · 2 comments
Closed

Problem with openarrays and slices #4179

zeitbit opened this issue May 17, 2016 · 2 comments

Comments

@zeitbit
Copy link

zeitbit commented May 17, 2016

In this example the output is incorrect, it is @[5, 5, 0, 1, 2, 3, 4, 0, 0, 0] but it should be @[0, 1, 2, 3, 4].

proc test(a: seq[int], b: var openarray[int]) =
    b = a[0 .. 4]

var
    a = @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    b = newSeq[int](10)

test(a, b)
echo b

Nim Compiler Version 0.13.1 (2016-05-13) [MacOSX: amd64]

@Parashurama
Copy link
Contributor

Confirmed on Linux latest devel.
Works OK if replacing openarray by seq

However, I not so sure you are supposed to use openarray like that. here is the generated C code.

// code for test(a: seq[int], b: var openarray[int])
-N_NIMCALL(void, test_94003_1385730820)(TY94083* a0, NI* b0, NI b0Len0)

// code for test(a: seq[int], b: var seq[int])
+N_NIMCALL(void, test_94003_1385730820)(TY94083* a0, TY94083** b0)
 }

As you can see an openarray is literally a pointer to the data, and a size. It doen't care what the original object was, and so I pretty sure you are not supposed to assign a seq or a string to it directly.

I think this should be a compile time error.

You might, however, assign data to to its slice with something like this.

proc `[]=`[T](s: var openarray[T]; x: Slice[int]; b: openarray[T]) =
    assert(x.a <= s.high and x.b <= s.high)
    var idx = 0
    for i in x.a..x.b:
        s[i] = b[idx]
        inc(idx)

proc test(a: seq[int], b: var openarray[int]) =
    # assign to openarray slice. original data must be at least slice size.
    b[0 .. 4] = a[0 .. 4]

@zeitbit
Copy link
Author

zeitbit commented May 18, 2016

Yes, I know it works with seqs, but if it's not allowed to assign data to openarrays with slices then the compiler should generate an error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants