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

Nathan S. no.public.email at example.com
Thu Jul 11 19:37:38 UTC 2019


On Thursday, 11 July 2019 at 16:31:58 UTC, Stefanos Baziotis 
wrote:
> I searched the forum but did not find something.
>
> I want to do this:
>
> int foo(T)(ref T s1, ref T s2)
> {
>     const byte[] s1b = (cast(const(byte)*)&s1)[0 .. T.sizeof];
>     const byte[] s2b = (cast(const(byte)*)&s2)[0 .. T.sizeof];
> }
>
> Which is to create a byte array from the bytes of the value 
> given, no matter
> the type. The above works, but it's not @safe.
>
> Thanks,
> Stefanos

If you know that what you're doing cannot result in memory 
corruption but the compiler cannot automatically infer @safe, it 
is appropriate to use @trusted. (For this case make sure you're 
not returning the byte slices, since if the arguments were 
allocated on the stack you could end up with a pointer to an 
invalid stack frame. If it's the caller's responsibility to 
ensure the slice doesn't outlive the struct then it is the caller 
that should be @trusted or not.)


More information about the Digitalmars-d-learn mailing list