Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

trusted functions

What are trusted functions in D?

Tahreem Yasir

What are trusted functions?

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 fdand 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);
Signature of read in D

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);
Reading file data in Buffer

The trusted attribute

According 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 readwill 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);

Best Practices

  • Before making a function trusted, it must be ensured that the external function is memory safe.
  • Evaluation of memory safety of trusted functions reduces only to verify the safety of external functions.
  • Adding trusted functions gives programmer flexibility to call external functions but trusted code must be kept small to verify memory safety.
  • A compiler cannot determine that a trusted function is safe because it does not have access to the body of external functions.


trusted functions

View all Courses

Keep Exploring