effers/examples/main.rs

85 lines
1.7 KiB
Rust
Raw Permalink Normal View History

2022-01-19 20:56:39 +00:00
use effers::program;
2022-01-21 13:16:03 +00:00
#[program(MyCoolProgram =>
Printer(print(&self) as p, available as printer_available),
Logger(debug(&mut self), info(self))
)]
fn my_program(val: u8) -> u8 {
if printer_available() {
p("hey hi hello");
}
2022-01-19 20:56:39 +00:00
debug("this is a debug-level log");
info("this is a info-level log");
val + 3
}
#[program(Printer(print(&self) as p))]
2022-01-21 10:40:23 +00:00
fn other_program() {
p("hey hi hello");
}
2022-01-19 20:56:39 +00:00
fn main() {
// call the first program twice
2022-01-21 13:16:03 +00:00
let result: u8 = MyCoolProgram.add(IoPrinter).add(FileLogger).run(3);
2022-01-19 20:56:39 +00:00
assert_eq!(result, 6);
2022-01-21 13:16:03 +00:00
let other_result: u8 = MyCoolProgram
2022-01-19 20:56:39 +00:00
.add(IoPrinter)
.add(NetworkLogger {
credentials: "secret password".to_string(),
})
.run(8);
assert_eq!(other_result, 11);
// other program
2022-01-21 10:40:23 +00:00
OtherProgram.add(IoPrinter).run();
2022-01-19 20:56:39 +00:00
}
trait Printer {
fn print(&self, s: &str);
2022-01-21 13:16:03 +00:00
fn available() -> bool;
2022-01-19 20:56:39 +00:00
}
trait Logger {
fn debug(&mut self, s: &str);
fn info(self, s: &str);
2022-01-19 20:56:39 +00:00
}
struct IoPrinter;
impl Printer for IoPrinter {
fn print(&self, s: &str) {
2022-01-19 20:56:39 +00:00
println!("{}", s)
}
2022-01-21 13:16:03 +00:00
fn available() -> bool {
true
}
2022-01-19 20:56:39 +00:00
}
struct FileLogger;
impl Logger for FileLogger {
fn debug(&mut self, s: &str) {
println!("debug: {}", s)
}
fn info(self, s: &str) {
2022-01-19 20:56:39 +00:00
println!("info: {}", s)
}
}
struct NetworkLogger {
credentials: String,
}
impl Logger for NetworkLogger {
fn debug(&mut self, s: &str) {
println!(
"debug through network: {}; with password {}",
s, self.credentials
)
}
fn info(self, s: &str) {
2022-01-19 20:56:39 +00:00
println!(
"info through network: {}; with password {}",
s, self.credentials
)
}
}