Discussion Thread: DIP 1035-- at system Variables--Community Review Round 2
Timon Gehr
timon.gehr at gmx.ch
Fri Feb 26 10:53:02 UTC 2021
On 26.02.21 10:49, Walter Bright wrote:
> > 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.
Yes, that's the idea, but this is a convention. It's not possible now to
make the compiler check your convention. @system fields address this
limitation.
More information about the Digitalmars-d
mailing list