Skip to content

Instantly share code, notes, and snippets.

@computermouth
Created February 21, 2024 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save computermouth/d57928c6af7ea6ea054c2aaffe7ef10a to your computer and use it in GitHub Desktop.
Save computermouth/d57928c6af7ea6ea054c2aaffe7ef10a to your computer and use it in GitHub Desktop.
#[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