const MEG64 = 1024 * 1024 * 64
var somebuf: array[MEG64, char] # some large buffer
# ...
proc char_arr_stuff(bufx: openArray[char], start: int) =
var
j = 0
c: char
while j < 64:
let k = start + j
debugEcho "j, k: " & $j & ", " & $k # first output: "0, 0" (as expected)
c = bufx[k] # BANG!
# ...
# open a file with (a bit more than) 64MB data (all in a..z,A..Z,0..9)
let bytesRead = myfile.readData(addr(somebuf[0]), MEG64) # Note: This works.
# ...
with char_arr_stuff getting passed in somebuf.
Nim compiles OK but when running it it raises "index 0 not in 0 .. -1 [IndexError]" through raiseIndexError2.
Well noted, the file reading works and somebuf (as well as bufx which is just somebuf passed into the proc) is valid and does contain (the correct) data. So 0 is not within 0 .. -1?? Side note: To be really, really sure I verified that bufx.low() == 0.
Btw @dom96
It drives me nuts that I always have to indent by hand code I insert here. Probably it's just me being forum-stupid. Would you please tell me how to do it better?
Solved ... kind off
The line c = bufx[k]ยดยด above was followed by ``key[j] = c
(which already was a split for debugging and was originally `` key[j] = bufx[start + j]``) and key was a newStringOfCap(64) var.
@Araq whom I want to thank and laud for his friendly help in our chat for providing useful hints and tips drove me to furiously testing/looking at my bufx array and to also try to heap allocate it.
What this lead to was finding the real culprit, namely key - which makes this whole thing even weirder because the compiler was unhappy about the wrong array (bufx instead of key).
The solution (well, rather a work around) was to stack allocate the string key (Don't ask me for the reason; that's something probably only true Nim wizards could find out). Once I had done that everything worked fine, even with index checking turned on.
However, I want to clearly excuse the Nim compiler. The whole stuff I talked about here got fed into heavily inlined and complex code and I've seen way more mature (e.g. C and Pascal) compilers choke on way less demanding code. Nim is still just v. 19.x and I found it all in all to be quite reliable and smart.
While it's not urgent the Nim devs might sometimes want to have a closer look at the array/openarray/string stuff (alloc and checks).