opCmp on a struct keyed by an array of bytes

Ali Çehreli acehreli at yahoo.com
Tue Nov 12 13:38:52 PST 2013


On 11/12/2013 01:06 PM, Charles Hixson wrote:
> Is there any better way to write the method than:
> (cmp doesn't seem to work, and byte arrays don't have an opCmp method.)
>
>   int opCmp(ref const B24 b) const
> {    for    (int i = 0;    i < 24;    i++)
>        {    if    (bytes[i] < b.bytes[i])    return    -1;
>              if    (bytes[i] > b.bytes[i])    return    1;
>         }
>         return    0;
> }    //    opCmp
>
> FWIW, the key is a fixed length array of ubyte, but similar structs have
> differing lengths.   If it's not supported by the system I don't want to
> do something like casting the pieces
> to ulongs and comparing those rather than the bytes.  The added
> complexity isn't worth it.
>

There is std.algorithm.cmp:

import std.algorithm;

struct B24
{
     byte[24] bytes;

     int opCmp(ref const B24 b) const
     {
         return bytes[].cmp(b.bytes[]);
     }
}

void main()
{
     auto a = B24();
     auto b = B24();

     assert(a == b);

     a.bytes[23] = 1;
     assert(a > b);

     b.bytes[22] = 1;
     assert(b > a);
}

Ali



More information about the Digitalmars-d-learn mailing list