Casting non-aliased mutable arrays to immutable in return values

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 29 09:30:09 PDT 2017


On 08/29/2017 09:09 AM, Per Nordlöw wrote:
> Is it recommended to cast an unaliased array to `immutable` after it has
> been initialized?
>
> The reason for asking is that I would like the following function
>
> void[] rawReadNullTerminated(string path)
>     @safe
> {
>     import std.stdio : File;
>     auto file = File(path, `rb`);
>
>     import std.array : uninitializedArray;
>     ubyte[] data = uninitializedArray!(ubyte[])(file.size + 1);
>     file.rawRead(data);
>     data[file.size] = 0;     // null terminator for sentinel
>
>     return data;                // TODO can we cast this to
> `immutable(void)[]`?
> }
>
> to have an immutable return type.
>
> I'm aware of that I need to verify the contexts as UTF-8 if I want to
> treat it as text.

Yes and assumeUnique does exactly that:

   https://dlang.org/library/std/exception/assume_unique.html

Further, if your function is pure, the cast is implicit for the caller:

void[] foo() pure {
     return new void[](10);
}

void main() {
     void[] a = foo();
     immutable(void)[] b = foo();    // works
}

Ali



More information about the Digitalmars-d-learn mailing list