opCmp on a struct keyed by an array of bytes

Charles Hixson charleshixsn at earthlink.net
Tue Nov 12 16:25:55 PST 2013


On 11/12/2013 01:38 PM, Ali Çehreli wrote:
> 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
Thank you.  That's exactly the answer I was looking for.  (

I had tried "return bytes.cmp(b.bytes);" , but it didn't occur to me 
that the error meant I should have used a copy?  Does this syntax mean 
that what's being compared is a dynamic array copy of the original 
static array?  Even if it is, that's the answer I wanted.


-- 
Charles Hixson



More information about the Digitalmars-d-learn mailing list