From 341be8cbfb35d289a4622b3497d99864fcef14c0 Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Tue, 21 Jul 2015 12:04:26 -0400 Subject: [PATCH] Add number method to every bitflag --- src/lib.rs | 44 +++++++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 68678b6..8f3f01e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -138,23 +138,6 @@ bitflags! { } } -impl Types { - /// Given a bitflag with only a single flag set, returns the event code corresponding to that - /// event. If multiple flags are set, the one with the most significant bit wins. In debug - /// mode, - #[inline(always)] - pub fn number(&self) -> T { - let val = ffs::(self.bits()); - if cfg!(debug_assertions) { - if self.bits() != 1 << val { - panic!("{:?} ought to have only one flag set to be used with .number()", self); - } - } - T::from_u32(val).unwrap() - } -} - - bitflags! { /// Device properties. flags Props: u32 { @@ -375,6 +358,29 @@ bitflags! { } } +macro_rules! impl_number { + ($($t:ident),*) => { + $(impl $t { + /// Given a bitflag with only a single flag set, returns the event code corresponding to that + /// event. If multiple flags are set, the one with the most significant bit wins. In debug + /// mode, + #[inline(always)] + pub fn number(&self) -> T { + if cfg!(debug_assertions) { + let val = ffs(self.bits()); + self.bits() == val; // hack to induce the constraint typeof(self.bits()) = typeof(val) + if self.bits() != 1 << val { + panic!("{:?} ought to have only one flag set to be used with .number()", self); + } + } + T::from_u32(ffs(self.bits())).unwrap() + } + })* + } +} + +impl_number!(Types, Props, RelativeAxis, AbsoluteAxis, Switch, Led, Misc, FFStatus, Repeat, Sound); + #[repr(C)] #[derive(Copy, Clone, Debug)] pub enum Synchronization { @@ -619,8 +625,8 @@ impl Drop for Device { } } -fn ffs(x: u32) -> T { - T::from_u32(31 - x.leading_zeros()).unwrap() +fn ffs(x: U) -> T { + T::from_u32(31 - U::to_u64(&x).unwrap().leading_zeros()).unwrap() } impl Device {