46 ms·
Is it not possible to write a 100% safe TCP/IP stack in Rust? Why is there a need for 76 lines of unsafe code?
by MuffinFlavored 7y ago
Is it not possible to write a 100% safe TCP/IP stack in Rust? Why is there a need for 76 lines of unsafe code?
- cesarb 7y ago> Why is there a need for 76 lines of unsafe code? I took a quick look, and all of them seem to be for calling functions from the C library. Moreover, nearly all of these seem to be system calls (open, close, select, ioctl...). Since the Rust compiler can't verify that these calls are safe (for an obvious example: the "read" call can write to arbitrary memory), it requires an "unsafe" block for them - signalling that it's the programmer's responsibility to make sure it's safe (in the "read" example, receiving a "&mut [u8]" from outside the "unsafe" block, and passing that slice's pointer and length as the parameters to the "read" call, would be safe).
- Arnavion 7y agoThe unsafe code uses libc API. All FFI functions are unsafe because they do not have compiler-enforced memory safety and other invariants (by definition of not being written in Rust themselves). It is the onus of the caller to read their docs and ensure that their Rust calling code does maintain those invariants before exiting the unsafe block. The crate also has a nice design decision to have a dedicated module for using these FFI functions, and unsafe is only allowed in this module. The rest of the crate errors if it has any unsafe code.