embedded-hal icon indicating copy to clipboard operation
embedded-hal copied to clipboard

Implement all I2C traits for `&RefCell`

Open GrantM11235 opened this issue 3 years ago • 1 comments
trafficstars

This allows an I2C bus to safely be shared between device drivers. Note that it does not allow the bus to be shared between threads/interrupts because RefCell is not Sync and therefore &RefCell is not Send.

Alternatives

Third party crate

This could be implemented in a third party crate via a wrapper type, but I don't want to maintain an entire crate that is almost entirely boilerplate.

Use RefCell::try_borrow_mut

This could also be implemented using RefCell::try_borrow_mut, but that would require a new error enum:

pub enum I2cRefCellError<E> {
	I2c(E),
	RefCell(core::cell::BorrowMutError)
}

The RefCell borrow will only fail if the user has manually borrowed from it (an obvious bug that should be caught immediately during development), so I don't think that it is worth the extra complexity to avoid a panic in that case.

GrantM11235 avatar Dec 02 '21 01:12 GrantM11235

r? @therealprof

(rust-highfive has picked a reviewer for you, use r? to override)

rust-highfive avatar Dec 02 '21 01:12 rust-highfive

See https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal-bus/src/i2c/refcell.rs

Dominaezzz avatar Sep 09 '23 12:09 Dominaezzz

yes. I propose closing this, now that we have embedded-hal-bus, unless somebody has an objection.

Dirbaio avatar Sep 10 '23 20:09 Dirbaio

I think that this direct impl on '&RefCell' is slightly more convenient than the wrapper type in embedded-hal-bus, but I don't have strong feelings either way

GrantM11235 avatar Sep 12 '23 04:09 GrantM11235

On second thought, it makes more sense for the refcell impl to stay next to the mutex and critical-section impls in embedded-hal-bus

GrantM11235 avatar Sep 12 '23 19:09 GrantM11235