@trusted assumptions about @safe code

ag0aep6g anonymous at example.com
Wed May 27 13:11:12 UTC 2020


On 27.05.20 14:48, Steven Schveighoffer wrote:
> On 5/27/20 2:36 AM, ag0aep6g wrote:
[...]
>> But oh no, `my_strlen` is @safe. That means `f` cannot assume that the 
>> returned value is in bounds. It now has to verify that. Somehow, it's 
>> harder to call the @safe function correctly than the @system one.
> 
> I think this is not the way to view it. @safe code still should do what 
> it's supposed to do. It's not any harder *or any easier* to call @safe 
> code.
> 
> You are going to have to trust that whatever functions you call 
> (@trusted, @safe, or @system) are following their spec. @safe has 
> additional restrictions, so you can assume more. But the semantic 
> meaning of things cannot be checked by the compiler, and those are the 
> interesting things that cause bugs.
> 
> A more realistic example, and one that gets me all the time is something 
> like indexOf. Does it return input.length or -1 if the item isn't found? 
> Using the wrong expectation can lead to bad consequences. So it's 
> important, no matter the safety of the indexOf function, to know what 
> it's supposed to do, and base your review of trusted code on that 
> knowledge.
> 
> Of course, with something like that, one could be extra cautious, and 
> assert the value is within bounds if it's not the sentinel. You could be 
> even more cautious and check that the index found has the sought-after 
> element. And that's probably the right defensive way to do this. But 
> who's going to do that? Most people will work under the assumption that 
> indexOf does what it says it's going to do, and not worry about 
> unittesting it on every call.

Just to be clear: I agree with you. Requiring @trusted to be so 
super-defensive doesn't seem viable.


More information about the Digitalmars-d mailing list