Safe cast of arrays

Era Scarecrow via Digitalmars-d digitalmars-d at puremagic.com
Wed Feb 10 01:20:01 PST 2016


On Wednesday, 10 February 2016 at 08:49:21 UTC, w0rp wrote:
> I think this should be addressed, as if you can't cast between 
> pointer types, you shouldn't be allowed to cast between slice 
> types either. Because slices are just a pointer plus a length. 
> Another way to demonstrate the problem is like this.

  void is a typeless-type as i see it. It stands for a 'block of 
something'. Naturally void has to be converted to something 
before it can use it at all, even if it's a byte.

  The only reason i can see converting between arrays is allowed 
is because the size is known, so we won't accidentally throw 
segfaults after converting the type, while a pointer without the 
size attached to it literally only knows a location potentially 
of 0 bytes big; Whereas if you cost something 100 bytes of void, 
to a struct 10 bytes big...


  Should you be allowed to cast from one type to another? Depends. 
If they are nearly the same (signed vs unsigned) maybe it should 
be allowed. Completely different types (or of different lengths)? 
I'd say not with @safe declared; But still there's many many many 
low level tricks and bypasses we have to do to get code to work 
sometimes. Maybe pointers shouldn't be allowed to be passed 
around with @safe code either. Both of these would heavily reduce 
the problems presented.


  A while back i was thinking that perhaps the array type should 
have a third member (of flags and tests) for debugging and 
catching these types of problems, which isn't compiled into 
release mode. It would include information like if it's a static, 
stack or heap allocated array, if it's been converted from it's 
original type, was immutable/const, exists only for the calling 
function, was assigned/postblit'd, if the ptr was passed 
bypassing the security features, etc. Then during debugging or 
runtime the flags could/would be checked for validity. The 
runtime could throw red flags when these are identified and you 
could find these types of bugs easier, even identify 
problems/bugs with library code you previously thought was just 
fine.


More information about the Digitalmars-d mailing list