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

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Jul 12 01:24:06 UTC 2019


On Thursday, July 11, 2019 1:44:51 PM MDT Stefanos Baziotis via Digitalmars-
d-learn wrote:
> On Thursday, 11 July 2019 at 19:37:38 UTC, Nathan S. wrote:
> > 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.)
>
> Yes, @trusted is an option. I mean it's a good solution, but from
> the standpoint of the language user, it seems unfortunate that
> for the case static types
> @trusted has to be used while the array one can be @safe:
>
> int memcmp(T)(const T[] s1, const T[] s2) @safe
> {
>      const byte[] s1b = (cast(const(byte[]))s1)[0 .. s1.length *
> T.sizeof];
>      const byte[] s2b = (cast(const(byte[]))s2)[0 .. s2.length *
> T.sizeof];
> }

The compiler would have to have a deeper understanding of what you're doing
in order to know that it's @safe, and it's just not that smart. That's why
@trusted is needed in general. Just because something is obvious to the
programmer doesn't mean that it's at all obvious to the compiler. In some
cases, the compiler could be improved, but in many, it really just comes
down to the programmer verifying that the code is doing the correct thing
and using @trusted.

BTW, if you're implementing memcmp, why are you using byte instead of ubyte?
byte is signed. Unless you're explicitly trying to do arithmetic on integral
values from -127 to 127, odds are, you shouldn't be using byte. If you're
doing something like breaking an integer into its 8-bit parts, then ubyte is
what's appropriate, not byte.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list