convert ubyte[k..k + 1] to int

Artur Skawina art.08.09 at gmail.com
Thu May 17 02:36:24 PDT 2012


On 05/17/12 10:47, Roman D. Boiko wrote:
> On Thursday, 17 May 2012 at 08:39:21 UTC, Artur Skawina wrote:
>> On 05/17/12 10:15, Roman D. Boiko wrote:
>>> I mean, is it safe (assuming that we are allowed to mutate blob, and its length is a multiple of C.sizeof)?
>>>
>>> I do casting from ubyte[] to C[].
>>
>> Only if C.ptr ends up properly aligned. There are also aliasing
>> issues, which i don't think are sufficiently defined for D (for
>> C, it would be legal only because char* is allowed to alias anything).
>>
>> artur
> 
> Is it possible to ensure? In my case blob is created as
>     auto blob = cast(ubyte[]) read(fileName);
> I assume that alignment is safe.
> 
> But what should I do to be safe in a general case?

Well, you have to assume any /new/ buffers returned are sufficiently aligned;
still, slicing the buffers and appending in place can result in arrays that
have a legal length (so won't trigger a cast failure at runtime), but are not
properly aligned and accessing the elements will fail in different ways (crash,
data corruption etc).

   assert(cast(size_t)data.ptr%data.alignof==0);

This assert can be easily triggered eg by doing
   
   blob[1..$-4]; blob.assumeSafeAppend(); ++blob.length;
   auto data = cast(C[]) blob;

artur


More information about the Digitalmars-d-learn mailing list