Does the following construct hold water?

version(LittleEndian)
{
/// interpret an array of one type as an array of a different type.
   /// if the array has odd length, the highest elements are
   /// not accessible, at worst an empty slice is returned
   inout ref T[] arrayOf(T, V: U[])(inout ref V a)
      pure @safe nothrow
      if(isUnsigned!T && isUnsigned!U)
   {
      return (cast(T*)a.ptr)[0 .. a.length * U.sizeof / T.sizeof];
   }

   unittest
   {
      ubyte a[5] = { 1, 2, 3, 4, 5 };
      auto b = a.arrayOf!uint;
      assert(typeof(b) == uint[]);
      assert(b.length == 1);
      assert(b[0] == 0x04030201);
      assert(&b[0] == &a[0]); // b is a slice of a
      b[0] = 0x0a0b0c0d; // this will change a
      assert(a == { 13, 12, 11, 10, 5 });

      ushort c[2] = { 257, 512 };
      auto d = c.arrayOf!ubyte;
      assert(d.length == 4);
      assert(d[0] == 1);
      assert(d[1] == 1);
      assert(d[2] == 0);
      assert(d[3] == 2);
   }
}

I assume taking a slice of a pointer uses the GC, so this cannot be @nogc, am I right? And I assume it is @save, because if I would increase the length of the returned value, the GC will automatically re-allocate, but then of course the adress is no more the same, yes?

Reply via email to