In D, trusted functions are used in scenarios where I/O operations or external and systems calls need to be performed while maintaining memory safety. A trusted function is denoted by the @trusted
keyword.
For example, the following code snippet reads data from a file using the file descriptor fd
and saves it into a buffer pointed to by ptr
. The size of the buffer is specified by nBytes
. Here, read
is a system call that will return the number of bytes in the buffer or negative value in case of an error.
ssize_t read(int fd, void* ptr, size_t nBytes);
We use read
to read data in a stack-allocated buffer. However, the following code is not conforming to the memory safety principles:
ubyte[128] buf;auto nread = read(fd, buf.ptr, buf.length);
trusted
attributeAccording to memory safety guidelines, a pointer can only point to a single piece of data, (a single ubyte
) whileread
expects to read multiple bytes in the buffer. Thus writing a safe code using read
will result in a compiler error.
To resolve this issue, D provides a @trusted
attribute that tells the compiler that the code marked with this attribute is trusted, and there is no need to check for memory safety.
The D code that solves the above problem looks like this safeRead
. This is a function that can be used safely in every case. Thus, it can be marked trusted.
auto safeRead(int fd, ubyte[] buf) @trusted{return read(fd, buf.ptr, buf.length);}
Free Resources