Why is three safety levels need in D?

Jesse Phillips via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 17 10:12:19 PST 2016


On Thursday, 17 November 2016 at 17:18:27 UTC, Nordlöw wrote:
> Why does D need both `@safe`, `@trusted` and `@system` when 
> Rust seems to get by with only safe (default) and `unsafe`?
>
> https://dlang.org/spec/memory-safe-d.html
> http://dlang.org/safed.html

D makes it illegal for @safe code to call @system code. I assume 
Rust gets by with only two levels because it does not create this 
restriction.

D doesn't allow @safe to call @system because @system code is 
intended to be marked as such because if you call it incorrectly 
it could cause memory corruption and sometimes the API should 
allow for that. D then requires a safe interface to the @system 
code to be wrapped with @trusted. The theory is that you can 
review @system code to check it isn't doing something completely 
wrong, and then you can check @trusted code to make sure it can't 
be called in such a way that it will call @system code and 
corrupt memory.

@system void setPointerValue(T)(T* a, T v) {
     *a = v;
}

@trusted void setArrayValue(T)(T[] a, T v, size_t index) {
     if(index > a.length || index < 0)
         return;

      setPointerValue(&a[index], v);
}

Completely pointless code, but reading the @trusted code we can 
see it performs the needed validation to prevent corrupting 
memory when calling setPointerValue.


More information about the Digitalmars-d-learn mailing list