Created
February 21, 2024 17:38
-
-
Save computermouth/d57928c6af7ea6ea054c2aaffe7ef10a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(PartialEq)] | |
#[repr(u16)] | |
enum Methods { | |
ALL = 0, | |
GET = 1 << 0, | |
HEAD = 1 << 1, | |
POST = 1 << 2, | |
PUT = 1 << 3, | |
DELETE = 1 << 4, | |
CONNECT = 1 << 5, | |
OPTIONS = 1 << 6, | |
TRACE = 1 << 7, | |
PATCH = 1 << 8, | |
} | |
struct MethodCombo{ | |
val: u16 | |
} | |
impl std::ops::BitOr for Methods { | |
type Output = MethodCombo; | |
fn bitor(self, rhs: Self) -> Self::Output { | |
if self == Methods::ALL || rhs == Methods::ALL { | |
return MethodCombo{ val: self as u16}; | |
} | |
MethodCombo { val: (self as u16 | rhs as u16) } | |
} | |
} | |
impl Into<MethodCombo> for Methods { | |
fn into(self) -> MethodCombo { | |
MethodCombo {val: self as u16} | |
} | |
} | |
trait Methodable { | |
fn as_u16(&self) -> u16; | |
fn is_all(&self) -> bool; | |
} | |
impl Methodable for MethodCombo { | |
fn as_u16(&self) -> u16 { | |
self.val | |
} | |
fn is_all(&self) -> bool { | |
self.val == Methods::ALL as u16 | |
} | |
} | |
impl Methodable for Methods { | |
fn as_u16(&self) -> u16 { | |
*self as u16 | |
} | |
fn is_all(&self) -> bool { | |
*self == Methods::ALL | |
} | |
} | |
impl std::ops::BitOr for Box<dyn Methodable> { | |
type Output = MethodCombo; | |
fn bitor(self, rhs: Self) -> Self::Output { | |
if self.is_all() || rhs.is_all() { | |
return MethodCombo{ val: self.as_u16()}; | |
} | |
MethodCombo { val: (self.as_u16() | rhs.as_u16()) } | |
} | |
} | |
fn pass_as_usize<T: Into<MethodCombo>>(u: T) -> u16 { | |
u.into().val | |
} | |
fn pass_as_methodable<T: Methodable>(m: T) -> u16 { | |
m.as_u16() | |
} | |
fn main() { | |
println!("Hello, {}!", pass_as_usize(Methods::ALL)); | |
println!("Hello, {}!", pass_as_usize(Methods::GET | Methods::PUT)); | |
println!("Hello, {}!", pass_as_usize(Methods::GET | Methods::PUT | Methods::DELETE)); | |
println!("Hello, {}!", pass_as_methodable(Methods::GET | Methods::PUT)); | |
println!("Hello, {}!", pass_as_methodable(Box::new(Methods::GET) | Box::new(Methods::PUT) | Box::new(Methods::DELETE))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment