Question

How do I create a function that supports static arrays of any size?

Something like:

@safe pure nothrow void fillArray(ref ubyte[] array) {
    /**
     * How do I make this function support arrays of any
     * size; but they don't have to be dynamic?
    **/
}
Was it helpful?

Solution 2

What you need to do is remove the ref from your argument. When you use reference, it means that when you resize the array inside the function, it'll also be resized outside the function, which obviously isn't possible with static arrays.

When you do not use ref, you can still edit the array contents. When you resize the array however, only the local copy of the array pointer will get updated with the new length. The local copy will have a different size; the original pointer will still have it's original size.

If you sliced the array, it'd work too, because the reference the function got would be a new made reference to that slice of the array anyway; it would not equal the original reference.

OTHER TIPS

ratchet freak said it in the comment, but I'll put it as an answer too. The solution is to just use a regular slice:

void fillArray(ubyte[] array) {}

And then static arrays can be passed to it without extra effort, and, of course, you can still slice them to pass just a portion to it too.

int[4] foo;
fillArray(foo); // ok, passes the whole thing
fillArray(foo[0 .. 2]); // passes only the first two

If you append to the slice in fillArray, that can break things, because appending to a slice will reallocate it - since it isn't ref, you can change what the contents, but not the address or length. Think of a slice as a pointer+length pair:

void fillArray(ubyte* data, size_t length) {}

You can change *data, or data[0], data[1], etc., filling the contents, but if you changed the length or the pointer itself, that won't be seen outside the function, unless ref of course, just like changing any other int value in a function.

And you can't do ref to resize a static array since resizing a static array is impossible anyway!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top