#"Pushing" to a fixed array

3 messages · Page 1 of 1 (latest)

misty shadow
#

I am trying to get used to fixed arrays for backing buffers, but I feel like I am missing a trick. Often I want to do

for do buf[n++] = my_read(&reader) or_break

where n is the current number of active elements in the buffer buf. But since n++ is not allowed in Odin, I have to write

for {
    buf[n] = my_read(&reader) or_break
    n += 1
}

which feels like many lines in comparison. Is there a better way to work with fixed arrays as buffers?

keen quest
#

core:container/small_array exists to wrap a fixed-size array into something that functions more like a dynamic array. This is handy if you want to be able to pass it around, etc.

You might also consider slice.into_dynamic from core:slice to get a "real" dynamic array that uses the given slice as its backing memory (and won't re-allocate). You can, of course, give it a slice to your fixed array. This is probably better for more "single-use" cases, or if you want to also be able to work with allocated dynamic arrays

misty shadow
#

Didn't know about slice.into_dynamic. Seems like what I want! Will definitely consider that moving forward.