logo
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
use std::borrow::Cow;

use serde_json::Value;

use crate::{
    registry::{MetaSchema, MetaSchemaRef, Registry},
    types::{ParseError, ParseFromJSON, ParseFromParameter, ParseResult, ToJSON, Type},
};

impl<T: Type, const LEN: usize> Type for [T; LEN] {
    const IS_REQUIRED: bool = true;

    type RawValueType = Self;

    type RawElementValueType = T::RawValueType;

    fn name() -> Cow<'static, str> {
        format!("[{}]", T::name()).into()
    }

    fn schema_ref() -> MetaSchemaRef {
        MetaSchemaRef::Inline(Box::new(MetaSchema {
            items: Some(Box::new(T::schema_ref())),
            max_length: Some(LEN),
            min_length: Some(LEN),
            ..MetaSchema::new("array")
        }))
    }

    fn register(registry: &mut Registry) {
        T::register(registry);
    }

    fn as_raw_value(&self) -> Option<&Self::RawValueType> {
        Some(self)
    }

    fn raw_element_iter<'a>(
        &'a self,
    ) -> Box<dyn Iterator<Item = &'a Self::RawElementValueType> + 'a> {
        Box::new(self.iter().map(|item| item.as_raw_value()).flatten())
    }
}

impl<T: ParseFromJSON, const LEN: usize> ParseFromJSON for [T; LEN] {
    fn parse_from_json(value: Value) -> ParseResult<Self> {
        match value {
            Value::Array(values) => {
                if values.len() != LEN {
                    return Err(ParseError::custom(format!(
                        "the length of the list must be `{}`.",
                        LEN
                    )));
                }

                let mut res = Vec::with_capacity(values.len());
                for value in values {
                    res.push(T::parse_from_json(value).map_err(ParseError::propagate)?);
                }

                Ok(res.try_into().ok().unwrap())
            }
            _ => Err(ParseError::expected_type(value)),
        }
    }
}

impl<T: ParseFromParameter, const LEN: usize> ParseFromParameter for [T; LEN] {
    fn parse_from_parameter(_value: &str) -> ParseResult<Self> {
        unreachable!()
    }

    fn parse_from_parameters<I: IntoIterator<Item = A>, A: AsRef<str>>(
        iter: I,
    ) -> ParseResult<Self> {
        let mut values = Vec::new();

        for s in iter {
            values.push(
                T::parse_from_parameters(std::iter::once(s.as_ref()))
                    .map_err(ParseError::propagate)?,
            );
        }

        if values.len() != LEN {
            return Err(ParseError::custom(format!(
                "the length of the list must be `{}`.",
                LEN
            )));
        }

        Ok(values.try_into().ok().unwrap())
    }
}

impl<T: ToJSON, const LEN: usize> ToJSON for [T; LEN] {
    fn to_json(&self) -> Value {
        let mut values = Vec::with_capacity(self.len());
        for item in self {
            values.push(item.to_json());
        }
        Value::Array(values)
    }
}