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
use core::fmt::{self, Write};

use aws_sdk_dynamodb::types::AttributeValue;

use super::{Scalar, Value};

/// A collection of DynamoDB values that may not all be of the same type.
///
/// <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.Document.List>
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct List {
    list: Vec<Value>,
}

impl List {
    pub fn new<T>(list: T) -> Self
    where
        T: Into<List>,
    {
        list.into()
    }

    // Intentionally not using `impl From<ScalarValue> for AttributeValue` because
    // I don't want to make this a public API people rely on. The purpose of this
    // crate is not to make creating `AttributeValues` easier. They should try
    // `serde_dynamo`.
    pub(super) fn into_attribute_value(self) -> AttributeValue {
        AttributeValue::L(
            self.list
                .into_iter()
                .map(Value::into_attribute_value)
                .collect(),
        )
    }
}

impl fmt::Display for List {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_char('[')?;

        let mut first = true;
        self.list.iter().try_for_each(|v| {
            if first {
                first = false;
            } else {
                f.write_str(", ")?;
            }

            if let Value::Scalar(Scalar::String(s)) = v {
                serde_json::to_string(s).unwrap().fmt(f)
            } else {
                v.fmt(f)
            }
        })?;

        f.write_char(']')
    }
}

impl<T> FromIterator<T> for List
where
    T: Into<Value>,
{
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        List {
            list: iter.into_iter().map(Into::into).collect(),
        }
    }
}

impl<I, T> From<I> for List
where
    I: IntoIterator<Item = T>,
    T: Into<Value>,
{
    fn from(iter: I) -> Self {
        Self::from_iter(iter)
    }
}

#[cfg(test)]
mod test {
    use pretty_assertions::assert_str_eq;

    use super::List;
    use crate::value::Value;

    #[test]
    fn display() {
        let list = List::from(["a"]);
        assert_str_eq!(r#"["a"]"#, list.to_string());

        let list = List::from([Value::new_string("a"), Value::new_num(42)]);
        assert_str_eq!(r#"["a", 42]"#, list.to_string());
    }
}