Passing a ubyte[] to a function taking a 'ref ubyte[16]'

Johannes Pfau nospam at example.com
Sat Jun 23 11:23:26 PDT 2012


I'm working on the new design for std.hash and I hit an interesting
problem:

The OOP interface has to take buffers as slices with unknown length, as
the length differs between hashes and I have to put a common function
declaration in a interface. So I have this:
------------
interface Digest
{
    ubyte[] finish(ubyte[] buf);
}
------------

Now the template API can and should use the correct type, so there
finish is defined like this:
------------
struct MD5
{
    void finish(ref ubyte[16] data);
}
------------

And the interface implementation for MD5 has to call the MD5 structs
finish function:
------------
class MD5Digest : Digest
{
    private MD5 _digest;

    ubyte[] finish(ubyte[] buf)
    {
        enforce(buf.length >= 16);
        _digest.finish(buf); //How to do this?
    }
}
------------

So how to pass a ubyte[] to a function expecting a ref ubyte[16]
without allocating/using any extra memory (Not even stack)?

This seems to work, but it's very ugly:
------------
_digest.finish(*cast(ubyte[16]*)buf.ptr);
------------

I thought this might create a temporary, but it passes all unittests,
so it seems to work?


More information about the Digitalmars-d-learn mailing list