Is there a way to slice non-array type in @safe?

Patrick Schluter Patrick.Schluter at bbox.fr
Fri Jul 12 08:10:52 UTC 2019


On Thursday, 11 July 2019 at 19:35:50 UTC, Stefanos Baziotis 
wrote:
> On Thursday, 11 July 2019 at 18:46:57 UTC, Paul Backus wrote:
>>
>> Casting from one type of pointer to another and slicing a 
>> pointer are both @system, by design.
>
> Yes, I'm aware, there are no pointers in the code. The pointer 
> was used
> here because it was the only way to solve the problem (but not 
> in @safe).
>
>> What's the actual problem you're trying to solve? There may be 
>> a different way to do it that's @safe.
>
> I want to make an array of bytes that has the bytes of the 
> value passed.
> For example, if T = int, then I want an array of 4 bytes that 
> has the 4
> individual bytes of `s1` let's say. For long, an array of 8 
> bytes etc.
> Ideally, that would work with `ref` (i.e. the bytes of where 
> the ref points to).

imho this cannot be safe on 1st principle basis. You gain access 
to the machine representation of variable, which means you bypass 
the "control" the compiler has on its data. Alone the endianness 
issue is enough to have different behaviour of your program on 
different implementations. While in practice big endian is nearly 
an extinct species (, it is still enough to show why that 
operation is inherently @system and should not be considered 
@safe.
Of course, a @trusted function can be written to take care of 
that, but that's in fact exactly the case as it should be.


More information about the Digitalmars-d-learn mailing list