|
| 1 | +//! This is a working version of the example in the crate-level documentation of `remote-trait-object` |
| 2 | +
|
| 3 | +use remote_trait_object::*; |
| 4 | + |
| 5 | +#[service] |
| 6 | +pub trait CreditCard: Service { |
| 7 | + fn pay(&mut self, ammount: u64) -> Result<(), ()>; |
| 8 | +} |
| 9 | +struct SomeCreditCard { |
| 10 | + money: u64, |
| 11 | +} |
| 12 | +impl Service for SomeCreditCard {} |
| 13 | +impl CreditCard for SomeCreditCard { |
| 14 | + fn pay(&mut self, ammount: u64) -> Result<(), ()> { |
| 15 | + if ammount <= self.money { |
| 16 | + self.money -= ammount; |
| 17 | + Ok(()) |
| 18 | + } else { |
| 19 | + Err(()) |
| 20 | + } |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +#[service] |
| 25 | +pub trait PizzaStore: Service { |
| 26 | + fn order_pizza(&self, credit_card: ServiceRef<dyn CreditCard>) -> Result<String, ()>; |
| 27 | +} |
| 28 | +struct SomePizzaStore; |
| 29 | +impl Service for SomePizzaStore {} |
| 30 | +impl PizzaStore for SomePizzaStore { |
| 31 | + fn order_pizza(&self, credit_card: ServiceRef<dyn CreditCard>) -> Result<String, ()> { |
| 32 | + let mut credit_card_proxy: Box<dyn CreditCard> = credit_card.unwrap_import().into_proxy(); |
| 33 | + credit_card_proxy.pay(10)?; |
| 34 | + Ok("Tasty Pizza".to_owned()) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +#[test] |
| 39 | +fn test() { |
| 40 | + let crate::transport::TransportEnds { |
| 41 | + recv1, |
| 42 | + send1, |
| 43 | + recv2, |
| 44 | + send2, |
| 45 | + } = crate::transport::create(); |
| 46 | + |
| 47 | + let _context_pizza_town = Context::with_initial_service_export( |
| 48 | + Config::default_setup(), |
| 49 | + send1, |
| 50 | + recv1, |
| 51 | + ServiceToExport::new(Box::new(SomePizzaStore) as Box<dyn PizzaStore>), |
| 52 | + ); |
| 53 | + |
| 54 | + let (_context_customer, pizza_store): (_, ServiceToImport<dyn PizzaStore>) = |
| 55 | + Context::with_initial_service_import(Config::default_setup(), send2, recv2); |
| 56 | + let pizza_store_proxy: Box<dyn PizzaStore> = pizza_store.into_proxy(); |
| 57 | + |
| 58 | + let my_credit_card = Box::new(SomeCreditCard { |
| 59 | + money: 11, |
| 60 | + }) as Box<dyn CreditCard>; |
| 61 | + assert_eq!(pizza_store_proxy.order_pizza(ServiceRef::create_export(my_credit_card)).unwrap(), "Tasty Pizza"); |
| 62 | + |
| 63 | + let my_credit_card = Box::new(SomeCreditCard { |
| 64 | + money: 9, |
| 65 | + }) as Box<dyn CreditCard>; |
| 66 | + assert!(pizza_store_proxy.order_pizza(ServiceRef::create_export(my_credit_card)).is_err()); |
| 67 | +} |
0 commit comments