DIP1028 - Rationale for accepting as is

Adam D. Ruppe destructionator at gmail.com
Fri May 22 17:26:03 UTC 2020


On Friday, 22 May 2020 at 17:07:37 UTC, Atila Neves wrote:
> And so I was convinced that everything being @safe is actually 
> ok, especially because in real life, most C/C++ APIs aren't 
> going to secretly corrupt your code.

I wrote up a thing about this earlier then deleted it because I 
didn't want to yell into the void, but now I kinda wish I kept it.

Short version of my thoughts is yes, most C functions are 
implicitly trusted, but this depends heavily on using correct 
arguments and that's what @trusted wrappers are supposed to 
ensure.

Consider:

char[16] buffer;
snprintf(&buffer[0], buffer.length, "%s", data);

btw fix this https://issues.dlang.org/show_bug.cgi?id=20853


But it is fair to say that usage is safe/trusted. However, you 
can just as well write:

snprintf(&buffer[12], buffer.length......

or

snprintf(&buffer[0], 156, ....); // oops my finger was misaligned 
on the keyboard and hit 56 without realizing it. or the size 
changed and this didn't etc



This is what a @trusted wrapper is supposed to be about - 
providing an interface that cannot be misused.

int snprintf(char[] buf, const char* fmt, ...) {
    return c.snprintf(buf.ptr, buf.length, fmt, ...);
}

Well, lol, that's not exactly *correct* thanks to the possibility 
of format string mismatch, but it bounds checks both sides of the 
slice and becomes more appropriately trusted due to the 
parameters being checked too.

We now actually have a trusted implementation with a safe 
interface - which is what @trusted is SUPPOSED to mean.


More information about the Digitalmars-d-announce mailing list