The array to cast to immutable.
The immutable array.
$(RUNNABLE_EXAMPLE ---- string letters() { char[] result = new char['z' - 'a' + 1]; foreach (i, ref e; result) { e = cast(char)('a' + i); } return assumeUnique(result); } ---- )
The use in the example above is correct because result was private to letters and the memory it referenced can no longer be written to after the function returns. The following example shows an incorrect use of assumeUnique.
Bad:
$(RUNNABLE_EXAMPLE ---- char[] buffer; string letters(char first, char last) { if (first >= last) return null; // fine auto sneaky = buffer; sneaky.length = last - first + 1; foreach (i, ref e; sneaky) { e = cast(char)('a' + i); } return assumeUnique(sneaky); // BAD } ---- )
The example above wreaks havoc on client code because it modifies the returned array that the previous caller considered immutable. To obtain an immutable array from the writable array buffer, replace the last line with:
return to!(string)(sneaky); // not that sneaky anymore
The to call will duplicate the array appropriately.
$(PANEL $(NOTE Checking for uniqueness during compilation is possible in certain cases, especially when a function is marked (or inferred) as `pure`. The following example does not need to call `assumeUnique` because the compiler can infer the uniqueness of the array in the pure function:) $(RUNNABLE_EXAMPLE ---- static string letters() pure { char[] result = new char['z' - 'a' + 1]; foreach (i, ref e; result) { e = cast(char)('a' + i); } return result; } ---- ) For more on infering uniqueness see the $(B unique) and $(B lent) keywords in the $(HTTP www.cs.cmu.edu/~aldrich/papers/aldrich-dissertation.pdf, ArchJava) language. )
The downside of using assumeUnique's convention-based usage is that at this time there is no formal checking of the correctness of the assumption; on the upside, the idiomatic use of assumeUnique is simple and rare enough to be tolerable.
int[] arr = new int[1]; auto arr1 = arr.assumeUnique; static assert(is(typeof(arr1) == immutable(int)[])); assert(arr == null); assert(arr1 == [0]);
int[string] arr = ["a":1]; auto arr1 = arr.assumeUnique; static assert(is(typeof(arr1) == immutable(int[string]))); assert(arr == null); assert(arr1.keys == ["a"]);
Casts a mutable array to an immutable array in an idiomatic manner. Technically, assumeUnique just inserts a cast, but its name documents assumptions on the part of the caller. assumeUnique(arr) should only be called when there are no more active mutable aliases to elements of arr. To strengthen this assumption, assumeUnique(arr) also clears arr before returning. Essentially assumeUnique(arr) indicates commitment from the caller that there is no more mutable access to any of arr's elements (transitively), and that all future accesses will be done through the immutable array returned by assumeUnique.
Typically, assumeUnique is used to return arrays from functions that have allocated and built them.