Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Seal the DAC trait to prevent UB #94

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions src/dac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,25 +87,29 @@ pub trait DacPin {
fn enable(&mut self);
}

pub trait Pins<DAC> {
type Output;
mod sealed {
// This trait is unsafe and sealed because we use MaybeUninit to
// return an instance of the type, and should only be used on ZSTs.
pub unsafe trait Pins<DAC> {
type Output;
}
}

impl Pins<DAC> for PA4<Analog> {
unsafe impl sealed::Pins<DAC> for PA4<Analog> {
type Output = C1;
}

impl Pins<DAC> for PA5<Analog> {
unsafe impl sealed::Pins<DAC> for PA5<Analog> {
type Output = C2;
}

impl Pins<DAC> for (PA4<Analog>, PA5<Analog>) {
unsafe impl sealed::Pins<DAC> for (PA4<Analog>, PA5<Analog>) {
type Output = (C1, C2);
}

pub fn dac<PINS>(_dac: DAC, _pins: PINS, rcc: &mut Rcc) -> PINS::Output
where
PINS: Pins<DAC>,
PINS: sealed::Pins<DAC>,
{
// Enable DAC clocks
rcc.regs.apb1enr.modify(|_, w| w.dacen().set_bit());
Expand All @@ -114,7 +118,7 @@ where
rcc.regs.apb1rstr.modify(|_, w| w.dacrst().set_bit());
rcc.regs.apb1rstr.modify(|_, w| w.dacrst().clear_bit());

unsafe { mem::uninitialized() }
unsafe { mem::MaybeUninit::uninit().assume_init() }
}

macro_rules! dac {
Expand Down Expand Up @@ -143,13 +147,13 @@ macro_rules! dac {
pub trait DacExt {
fn constrain<PINS>(self, pins: PINS, rcc: &mut Rcc) -> PINS::Output
where
PINS: Pins<DAC>;
PINS: sealed::Pins<DAC>;
}

impl DacExt for DAC {
fn constrain<PINS>(self, pins: PINS, rcc: &mut Rcc) -> PINS::Output
where
PINS: Pins<DAC>,
PINS: sealed::Pins<DAC>,
{
dac(self, pins, rcc)
}
Expand Down