|
| 1 | +use std::sync::{Arc, RwLock}; |
| 2 | + |
| 3 | +use minijinja::{ErrorKind, value::DynObject}; |
| 4 | + |
| 5 | +pub(crate) fn new_mut_list() -> DynObject { |
| 6 | + DynObject::new(Arc::new(MutList(RwLock::new(vec![])))) |
| 7 | +} |
| 8 | + |
| 9 | +impl minijinja::value::Object for MutList { |
| 10 | + fn repr(self: &Arc<Self>) -> minijinja::value::ObjectRepr { |
| 11 | + minijinja::value::ObjectRepr::Iterable |
| 12 | + } |
| 13 | + |
| 14 | + fn call_method( |
| 15 | + self: &Arc<Self>, |
| 16 | + _state: &minijinja::State<'_, '_>, |
| 17 | + method: &str, |
| 18 | + args: &[minijinja::Value], |
| 19 | + ) -> Result<minijinja::Value, minijinja::Error> { |
| 20 | + match method { |
| 21 | + "append" => self.append(args), |
| 22 | + _ => Err(minijinja::Error::new( |
| 23 | + ErrorKind::UnknownMethod, |
| 24 | + format!("Unexpected method {method}"), |
| 25 | + )), |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + fn enumerate(self: &Arc<Self>) -> minijinja::value::Enumerator { |
| 30 | + let vals = self |
| 31 | + .0 |
| 32 | + .read() |
| 33 | + .expect("Unable to read from MutList, RwLock was poisoned") |
| 34 | + .iter() |
| 35 | + .map(|s| s.to_owned()) |
| 36 | + .collect::<Vec<_>>(); |
| 37 | + minijinja::value::Enumerator::Iter(Box::new(vals.into_iter())) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +#[derive(Debug)] |
| 42 | +/// list of minijinja::Value, a work-around the minijinja mutability limitations. |
| 43 | +struct MutList(RwLock<Vec<minijinja::Value>>); |
| 44 | + |
| 45 | +impl MutList { |
| 46 | + fn append( |
| 47 | + self: &Arc<Self>, |
| 48 | + args: &[minijinja::Value], |
| 49 | + ) -> Result<minijinja::Value, minijinja::Error> { |
| 50 | + ensure_n_args("append", 1, args)?; |
| 51 | + { |
| 52 | + let mut a = self |
| 53 | + .0 |
| 54 | + .try_write() |
| 55 | + .map_err(|e| minijinja::Error::new(ErrorKind::InvalidOperation, e.to_string()))?; |
| 56 | + a.push(args[0].clone()); |
| 57 | + } |
| 58 | + Ok(minijinja::Value::UNDEFINED) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +fn ensure_n_args( |
| 63 | + method: &str, |
| 64 | + n: usize, |
| 65 | + args: &[minijinja::Value], |
| 66 | +) -> Result<(), minijinja::Error> { |
| 67 | + let err = |kind| -> Result<(), minijinja::Error> { |
| 68 | + Err(minijinja::Error::new( |
| 69 | + kind, |
| 70 | + format!( |
| 71 | + "{method} | Expected: {n} args, got {} arguments", |
| 72 | + args.len() |
| 73 | + ), |
| 74 | + )) |
| 75 | + }; |
| 76 | + |
| 77 | + match args.len().cmp(&n) { |
| 78 | + std::cmp::Ordering::Less => err(ErrorKind::MissingArgument), |
| 79 | + std::cmp::Ordering::Greater => err(ErrorKind::TooManyArguments), |
| 80 | + std::cmp::Ordering::Equal => Ok(()), |
| 81 | + } |
| 82 | +} |
0 commit comments