Simplification of @trusted

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Thu Jun 17 20:25:22 UTC 2021


On Thursday, 17 June 2021 at 19:06:31 UTC, Paul Backus wrote:
> In order for `get` to have a safe interface, it must not be 
> possible to call it from `@safe` code with an instance that has 
> `offset >= 2`. Because of the bug in `size`, it *is* possible 
> for `@safe` code to call `get` with such an instance. 
> Therefore, `get` does not have a safe interface.

Yes, but if I make size() @trusted and fix the bug then interface 
is provably safe?

```
class A {

     this() @trusted {
         ptr = &buffer[0];
         offset = 0;
     }

     int get() @trusted { return ptr[offset]; }
     void set(int i) @trusted { this.offset = i&1; }
     int size() @trusted { return 2;}
private:
     int[2] buffer;
     int* ptr;
     int offset;
}



   Also, if I do this, it is probably safe, because of the 
invariant that is checked?

```
class A {

     this() @trusted {
         ptr = &buffer[0];
         offset = 0;
     }

     int get() @trusted { return ptr[offset]; }
     void set(int i) @trusted { this.offset = i&1; }
     int size()@safe{ offset=2; return 2;}
     invariant{ assert(0<= offset && offset <=1 ); }
private:
     int[2] buffer;
     int* ptr;
     int offset;
}


```


More information about the Digitalmars-d mailing list