← Back to context

Comment by weebull

2 months ago

So if you're writing a device driver in rust...

- Hardware access is unsafe - Kernel interface is unsafe

How much remains in the layer in-between that's actually safe?

All logic, all state management, all per-device state machines, all command parsing and translation, all data queues, etc. Look at the examples people posted in other comments.

  • Yep. Its kind of remarkable just how little unsafe code you often need in cases like this.

    I ported a C skip list implementation to rust a few years ago. Skip lists are like linked lists, but where instead of a single "next" pointer, each node contains an array of them. As you can imagine, the C code is packed full of fiddly pointer manipulation.

    The rust port certainly makes use of a fair bit of unsafe code. But the unsafe blocks still make up a surprisingly small minority of the code.

    Porting this package was one of my first experiences working with rust, and it was a big "aha!" moment for me. Debugging the C implementation was a nightmare, because a lot of bugs caused obscure memory corruption problems. They're always a headache to track down. When I first ported the C code to rust, one of my tests segfaulted. At first I was confused - rust doesn't segfault! Then I realised it could only segfault from a bug in an unsafe block. There were only two unsafe functions it could be, and one obvious candidate. I had a read of the code, and spotted the error nearly immediately. The same bug would probably have taken me hours to fix in C because it could have been anywhere. But in rust I found and fixed the problem in a few minutes.