Issue with template function

Charles via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 7 12:29:41 PST 2015


On Saturday, 7 February 2015 at 12:04:12 UTC, Nicholas Wilson 
wrote:
> Are you wanting to to convert each element in arr to a byte 
> thus truncating and losing data (when T.sizeof != 1)?
> as in
>     toBytes([1,2,3, 42, 500 /*this will be truncated to 244 
> */]);// T  == int here
> or are you wanting to convert each element to a ubyte array and 
> then concatenate it to the result.
> as is
>      ubyte[] toBytes(T)(T[] arr)
>      {
>          ubyte[T.sizeof] buf;
>          if (arr is null)
>          {
>              return null;
>          }
>
>          ubyte[] result = new ubyte[arr.length * T.sizeof];
>
>          foreach (i, val; arr)
>          {
>              buf[] = cast(ubyte[T.sizeof])&(arr[i])[0 .. 
> T.sizeof]
>              result ~= buf;
>          }
>
>          return result;
>      }
> ?

The original code I was using was written in Java, and only had a 
method for strings. This is closer to what I wanted. My unit 
tests were just going back and forth with readString function, so 
I was completely missing this for other types. Nice catch!

There were a couple issues with your code so I've included the 
corrected version:

     ubyte[] toUbytes(T)(T[] arr)
     {
         if (arr is null)
         {
             return null;
         }

         ubyte[T.sizeof] buffer;
         ubyte[] result = new ubyte[arr.length * T.sizeof];

         foreach (i, val; arr)
         {
             buffer[] = cast(ubyte[T.sizeof])(&(arr[i]))[0 .. 
T.sizeof]; // Parenthesis and missing semicolon
             result[i * T.sizeof .. (i * T.sizeof) + T.sizeof] = 
buffer; // Specify appropriate slice for buffer to be inserted 
into
         }

         return result;
     }


More information about the Digitalmars-d-learn mailing list