const challenge

Georg Wrede georg at nospam.org
Thu Jan 31 13:22:55 PST 2008


Janice Caron wrote:
> 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.

Unique sounds interesting. And new to me, at least as a definable concept.

Question: suppose you have something defined as unique, and then 
somebody makes a copy of it. What happens to the uniqueness?

(You may want to explain this even more broadly if you know that most 
people have had problems getting some specific part of the idea.)



More information about the Digitalmars-d mailing list