proteus/actions/
len.rs

1use crate::action::Action;
2use crate::errors::Error;
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5use std::borrow::Cow;
6use std::ops::Deref;
7
8/// This type represents an [Action](../action/trait.Action.html) which returns the length of a
9/// String, Array or Object..
10#[derive(Debug, Serialize, Deserialize)]
11pub struct Len {
12    action: Box<dyn Action>,
13}
14
15impl Len {
16    pub fn new(action: Box<dyn Action>) -> Self {
17        Len { action }
18    }
19}
20
21#[typetag::serde]
22impl Action for Len {
23    fn apply<'a>(
24        &'a self,
25        source: &'a Value,
26        destination: &mut Value,
27    ) -> Result<Option<Cow<'a, Value>>, Error> {
28        match self.action.apply(source, destination)? {
29            Some(v) => match v.deref() {
30                Value::String(s) => Ok(Some(Cow::Owned(Value::Number(s.len().into())))),
31                Value::Array(arr) => Ok(Some(Cow::Owned(Value::Number(arr.len().into())))),
32                Value::Object(o) => Ok(Some(Cow::Owned(Value::Number(o.len().into())))),
33                _ => Ok(None),
34            },
35            None => Ok(None),
36        }
37    }
38}