From 1a5078c337bd8d9b2cf4eef8fa35c22cf49cef11 Mon Sep 17 00:00:00 2001 From: James Munns Date: Tue, 4 Feb 2020 01:08:30 +0100 Subject: [PATCH] Seal the DAC trait to prevent UB --- src/dac.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/dac.rs b/src/dac.rs index 27fe965..ddc015f 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -87,25 +87,29 @@ pub trait DacPin { fn enable(&mut self); } -pub trait Pins { - 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 { + type Output; + } } -impl Pins for PA4 { +unsafe impl sealed::Pins for PA4 { type Output = C1; } -impl Pins for PA5 { +unsafe impl sealed::Pins for PA5 { type Output = C2; } -impl Pins for (PA4, PA5) { +unsafe impl sealed::Pins for (PA4, PA5) { type Output = (C1, C2); } pub fn dac(_dac: DAC, _pins: PINS, rcc: &mut Rcc) -> PINS::Output where - PINS: Pins, + PINS: sealed::Pins, { // Enable DAC clocks rcc.regs.apb1enr.modify(|_, w| w.dacen().set_bit()); @@ -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 { @@ -143,13 +147,13 @@ macro_rules! dac { pub trait DacExt { fn constrain(self, pins: PINS, rcc: &mut Rcc) -> PINS::Output where - PINS: Pins; + PINS: sealed::Pins; } impl DacExt for DAC { fn constrain(self, pins: PINS, rcc: &mut Rcc) -> PINS::Output where - PINS: Pins, + PINS: sealed::Pins, { dac(self, pins, rcc) }