const challenge

Janice Caron caron800 at googlemail.com
Thu Jan 31 12:26:06 PST 2008


OK, here's an example, borrowed a bit from Tango.

    char[] niftyStringFunction(char[] outBuffer, char[] input)
    {
        /*...*/
    }

The idea is, if (outBuffer == null) then the function allocates memory
and returns it; whereas, if (outBuffer != null) then the result is
writen into outBuffer, and the return value is a slice of outBuffer.
(The idea is to minimize allocations).

Converting this to D2 is problematic, because you want to return a
string, but string is invariant, so if you do that, you won't be able
to pass the same buffer back into other, similarly nifty string
functions.

The interesting thing about this sort of function is that there is an
implicit in-contract that outBuffer, if supplied, must be unique (the
caller must have finished with it), and an implicit out-countract that
the return value is unique (even if you return outBuffer, because of
the implicit in-contract), so you /could/ code your way around this by
returning a string, and then casting away the invariance if you want
to reuse the buffer - but that is a nasty kludge. I can come up with
const-correct workarounds which do the job, but none which do the job
/as efficiently/.

Once again, this problem arises because D has no way to express
uniqueness. If we had such a means, then the const-correct prototype
would be

    unique(char)[] niftyStringFunction(unique(char)[] outBuffer, string input)

The workaround is simple enough though: just don't use const at this
level. Treat functions of this ilk as a low-level API layer. Then
supply a higher-level layer with more conventional semantics, which
hides the low-level layer from the caller. All the const casting can
go on in the interface between the two layers.



More information about the Digitalmars-d mailing list