1 use anyhow::{anyhow, Result}; 2 use format_buf::format; 3 4 use std::any::Any; 5 6 use super::{as_arguments_0, as_arguments_1, FormatSpecifier, Type, Value}; 7 8 impl<T: 'static + Value + Clone> Value for Option<T> { call(&self, func: &str, args: &[Box<dyn Value>]) -> Result<Box<dyn Value>>9 fn call(&self, func: &str, args: &[Box<dyn Value>]) -> Result<Box<dyn Value>> { 10 match func { 11 "is_none" => { 12 as_arguments_0(args)?; 13 Ok(Box::new(self.is_none())) 14 } 15 "is_some" => { 16 as_arguments_0(args)?; 17 Ok(Box::new(self.is_some())) 18 } 19 "expect" => { 20 let (message,) = as_arguments_1::<String>(args)?; 21 self 22 .clone() 23 .map(|value| Box::new(value) as Box<dyn Value>) 24 .ok_or_else(|| { 25 anyhow!("Could not unwrap Option (object does not contain a value)").context(message.to_string()) 26 }) 27 } 28 "unwrap" => { 29 as_arguments_0(args)?; 30 self 31 .clone() 32 .map(|value| Box::new(value) as Box<dyn Value>) 33 .ok_or_else(|| anyhow!("Could not unwrap Option (object does not contain a value)")) 34 } 35 "?" => { 36 as_arguments_0(args)?; 37 self 38 .clone() 39 .map(|value| Box::new(value) as Box<dyn Value>) 40 .ok_or_else(|| anyhow!("Could not unwrap Option (object does not contain a value)")) 41 } 42 _ => self.call_base(func, args), 43 } 44 } 45 get_type(&self) -> Type46 fn get_type(&self) -> Type { 47 Type::Option 48 } 49 as_any(&self) -> &dyn Any50 fn as_any(&self) -> &dyn Any { 51 self 52 } 53 format(&self, buffer: &mut String, spec: FormatSpecifier)54 fn format(&self, buffer: &mut String, spec: FormatSpecifier) { 55 match spec { 56 FormatSpecifier::Default => match self { 57 Some(value) => value.format(buffer, spec), 58 None => *buffer += "None", 59 }, 60 FormatSpecifier::Debug => format!(buffer, "{:?}", self), 61 FormatSpecifier::DebugAlt => format!(buffer, "{:#?}", self), 62 } 63 } 64 } 65