Discussion Thread: DIP 1035-- at system Variables--Community Review Round 2

Walter Bright newshound2 at digitalmars.com
Fri Feb 26 09:49:40 UTC 2021


 > Example: User-Defined Slice

Since ptr and length are private, they are only accessible to member functions 
of IntSlice. I don't think there is any way to prove memory safety of the 
implementation of this.

 >  Instead, every function that touches ptr and length, including the @safe 
constructor, must be manually checked.

Right. So the idea is to minimize access to .ptr/.length for member functions of 
IntSlice. This can be done with:

   struct IntSlice
   {
     private static struct Slice
     {
         private int* ptr;
         private size_t length;

       @trusted:

         this(int[] src)
         {
              ptr = src.ptr;
              length = src.length;
         }

         int[] opSlice()
         {
              return ptr[0 .. length];
         }
      }

      // Now, the only access is via @trusted functions

    @safe:

     private Slice slice;

     this(int[] src)
     {
         slice = Slice(src);
     }

     ref int opIndex(size_t i)
     {
         return slice[][i]; // note no assert(i < length) needed
     }

     // ... every function goes here ...
   }

So, the general idea is to restrict access to `@system` fields by encapsulating 
them separately, and providing a minimized @trusted interface to them.


More information about the Digitalmars-d mailing list