Last active
August 24, 2023 17:49
-
-
Save OMGasm/d9942d89ca96063c9c2e2ebf5f31d2b3 to your computer and use it in GitHub Desktop.
intentionally bad code to work through some of the progression going from hardcoded everything to better design patterns i guess, v wip but it works! (now with enums!)
This file contains 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
use anyhow::{anyhow, Result}; | |
struct Service { | |
op: Box<dyn Op>, | |
} | |
trait Op { | |
fn exec(&self, b: i32) -> i32; | |
} | |
impl<T> From<T> for Box<dyn Op> | |
where | |
T: Op + Sized + 'static, | |
{ | |
fn from(value: T) -> Self { | |
Box::new(value) | |
} | |
} | |
struct Add { | |
a: i32, | |
} | |
struct Mul { | |
a: i32, | |
} | |
impl Add { | |
fn new(a: i32) -> Self { | |
Self { a } | |
} | |
fn exec(&self, b: i32) -> i32 { | |
self.a + b | |
} | |
} | |
impl Op for Add { | |
fn exec(&self, b: i32) -> i32 { | |
self.exec(b) | |
} | |
} | |
impl Mul { | |
fn new(a: i32) -> Self { | |
Self { a } | |
} | |
fn exec(&self, b: i32) -> i32 { | |
self.a * b | |
} | |
} | |
impl Op for Mul { | |
fn exec(&self, b: i32) -> i32 { | |
self.exec(b) | |
} | |
} | |
enum Status { | |
Ok(Ope), | |
Exit, | |
} | |
enum Ope { | |
Add, | |
Mul, | |
} | |
impl Ope { | |
fn donk(&self) -> Box<dyn Op> { | |
match self { | |
Self::Add => Add::new(5).into(), | |
Self::Mul => Mul::new(4).into(), | |
} | |
} | |
} | |
impl From<Ope> for Box<dyn Op> { | |
fn from(value: Ope) -> Self { | |
value.into() | |
} | |
} | |
impl TryFrom<&str> for Status { | |
type Error = anyhow::Error; | |
fn try_from(value: &str) -> Result<Status> { | |
match value { | |
"add" => Ok(Status::Ok(Ope::Add)), | |
"mul" => Ok(Status::Ok(Ope::Mul)), | |
"" | "q" | "quit" | "exit" => Ok(Status::Exit), | |
s => Err(anyhow!("invalid operation! \"{s}\"")), | |
} | |
} | |
} | |
impl Service { | |
fn exec(&self) -> Result<()> { | |
println!("{}", self.op.exec(6)); | |
Ok(()) | |
} | |
fn new(op: Ope) -> Self { | |
Self { op: op.donk() } | |
} | |
} | |
fn main() -> Result<()> { | |
loop { | |
let mut line = String::new(); | |
std::io::stdin().read_line(&mut line)?; | |
let status: Result<Status> = line.trim().try_into(); | |
match status { | |
Ok(Status::Ok(op)) => Service::new(op).exec()?, | |
Err(e) => println!("{e}"), | |
Ok(Status::Exit) => break, | |
}; | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment