Hacker News new | ask | show | jobs
by davidhyde 1090 days ago
> “and the ownership of resources by the device (which Rust doesn't solve for) are correct.”

For embedded software, the underlying code basically reads and writes a bunch of registers. Unsafe memory access with side effects. The benefit of using rust here is that you can easily model these access patterns to make an api that cannot be abused. So the driver reads and writes addresses and the user code operates through the driver with all the benefits of ownership at hand to avoid race conditions and other foot-guns.

So, in this way rust does indeed “solve for” ownership of devices. You can’t have two threads (or interrupt handlers) mutating the same device without satisfying the ownership rules.

1 comments

>You can’t have two threads (or interrupt handlers) mutating the same device without satisfying the ownership rules.

The trouble with this is that abstract 'devices' don't necessarily map neatly to the underlying hardware. Configuring peripherals on a typical microcontroller typically requires setting flags in a bunch of random registers which don't necessarily have neatly separated responsibilities.

Take PWM as an example. Is there a PWM 'device'? Is there a PWM setting for each port, according to some abstract representation of ports? What about the timer used to generate the PWM output? Does the PWM device own the timer, or does the timer own the PWM device? Any such abstractions cause more problems than they solve. You really just need to think carefully about how you are manipulating the underlying hardware.

In my experience a decent way to solve this is by two layers of abstractions. I will take any better design ideas!

First layer gives you safe access to the hardware registers. For example, ensure atomic/synchronized access, forbid invalid/reserved values. Name the flags/bits to reduce human mistakes (reg |= Prescaler::Div8.

You can still miss-configure the PWM/Timer settings of course.

The second layer gives you a safe driver interface. Giving you all the options to configure a timer for a some PWM settings for example.