Why invariants in D 2.0 std.string?
Janice Caron
caron800 at googlemail.com
Wed Nov 7 00:04:38 PST 2007
On Nov 7, 2007 4:33 AM, David B. Held <dheld at codelogicconsulting.com> wrote:
> > How does invariant allow better optimization than const?
> > [...]
>
> A const string may be intrinsically mutable but you only have a
> read-only view of it. An invariant string is intrinsically immutable,
> so you can make extra assumptions about what it won't do while you poke it.
For example, suppose you had a function
/* case (a) */
uint inPlaceReplaceAll( char[] s, const(char)[] from, const(char)[] to );
/* case (b) */
uint inPlaceReplaceAll( char[] s, invariant(char)[] from,
invariant(char)[] to );
In case b, the compiler may safely assume that s and from do not
overlap. In case a, they might. Ditto pattern and to.
Here's another example
/* case (a) */
char[] s;
const(char)[] t = s.tolower();
s[0] = 'H';
writefln(t);
/* case (b) */
char[] s;
invariant(char)[] t = s.tolower();
s[0] = 'H';
writefln(t);
In case (a), the program may or may not modify t, depending on whether
or not tolower() returned the original, or a copy. But in case (b),
the code won't even complile, because s can't be intrinsically cast to
invariant. To make the tolower() line compile, you have to force s to
be invariant - in which case the assignment of s[0] in the following
line will fail to compile. This example promises that your code will
run predicably.
More information about the Digitalmars-d
mailing list