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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use core::fmt;
use std::collections::BTreeSet;

use aws_sdk_dynamodb::{primitives::Blob, types::AttributeValue};

use super::base64;

/// Represents a [DynamoDB binary set][1].
///
/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.SetTypes
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BinarySet(BTreeSet<Vec<u8>>);

impl BinarySet {
    /// Creates a value to use as a [DynamoDB binary set][1].
    ///
    /// It can be created from `IntoIterator<T>` where `T` is `Into<Vec<u8>>`.
    /// Some examples:
    /// ```
    /// use dynamodb_expression::value::BinarySet;
    /// # use pretty_assertions::assert_eq;
    ///
    /// // impl IntoIterator<Item = &str>
    /// assert_eq!(
    ///     r#"["YQ==", "Yg==", "Yw=="]"#,
    ///     BinarySet::new(["a", "b", "c"]).to_string()
    /// );
    ///
    /// // impl IntoIterator<Item = String>
    /// assert_eq!(
    ///     r#"["YQ==", "Yg==", "Yw=="]"#,
    ///     BinarySet::new([String::from("a"), String::from("b"), String::from("c")]).to_string()
    /// );
    ///
    /// // impl IntoIterator<Item = &[u8]>
    /// assert_eq!(
    ///     r#"["YQ==", "Yg==", "Yw=="]"#,
    ///     BinarySet::new([b"a", b"b", b"c"]).to_string()
    /// );
    ///
    /// // impl IntoIterator<Item = Vec<u8>>
    /// assert_eq!(
    ///     r#"["YQ==", "Yg==", "Yw=="]"#,
    ///     BinarySet::new([b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]).to_string()
    /// );
    ///
    /// // impl IntoIterator<Item = impl Iterator<Item = u8>>
    /// assert_eq!(
    ///     r#"["YQ==", "Yg==", "Yw=="]"#,
    ///     BinarySet::new(
    ///         [[b'a'], [b'b'], [b'c']]
    ///             // In this case you need to turn the `Iterator<Item = u8>` items into a `Vec<u8>`.
    ///             // If, one day, `impl<T> From<impl IntoIterator<Item = T>> for Vec<T>` exists, this won't be needed.
    ///             .map(Vec::from_iter)
    ///     )
    ///     .to_string()
    /// );
    /// ```
    ///
    /// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.SetTypes
    pub fn new<T>(set: T) -> Self
    where
        T: Into<BinarySet>,
    {
        set.into()
    }

    // Intentionally not using `impl From<BinarySet> 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::Bs(self.0.into_iter().map(Blob::new).collect())
    }
}

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

impl<I, T> From<I> for BinarySet
where
    I: IntoIterator<Item = T>,
    T: Into<Vec<u8>>,
{
    fn from(values: I) -> Self {
        Self::from_iter(values)
    }
}

impl fmt::Display for BinarySet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.0.iter().map(base64)).finish()
    }
}

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

    use super::BinarySet;
    use crate::Scalar;

    #[test]
    fn from_iter() {
        // impl IntoIterator<Item = &str>
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new(["a", "b", "c"]).to_string()
        );

        // impl IntoIterator<Item = String>
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new([String::from("a"), String::from("b"), String::from("c")]).to_string()
        );

        // impl IntoIterator<Item = &[u8]>
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new([b"a", b"b", b"c"]).to_string()
        );

        // impl IntoIterator<Item = Vec<u8>>
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new([b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]).to_string()
        );

        // impl IntoIterator<Item = impl Iterator<Item = u8>>
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new(
                [[b'a'], [b'b'], [b'c']]
                    // In this case you need to turn the `Iterator<Item = u8>` items into a `Vec<u8>`.
                    // If, one day, `impl<T> From<impl IntoIterator<Item = T>> for Vec<T>` exists, this won't be needed.
                    .map(Vec::from_iter)
            )
            .to_string()
        );
    }

    #[test]
    fn comparable_with_binary() {
        // &str
        assert_eq!(r#""YQ==""#, Scalar::new_binary("a").to_string());
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new(["a", "b", "c"]).to_string()
        );

        // String
        assert_eq!(
            r#""YQ==""#,
            Scalar::new_binary(String::from("a")).to_string()
        );
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new([String::from("a"), String::from("b"), String::from("c")]).to_string()
        );

        // &[u8]
        assert_eq!(r#""YQ==""#, Scalar::new_binary(b"a").to_string());
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new([b"a", b"b", b"c"]).to_string()
        );

        // Vec<u8>
        assert_eq!(r#""YQ==""#, Scalar::new_binary(b"a".to_vec()).to_string());
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new([b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]).to_string()
        );

        // impl Iterator<Item = u8>
        assert_eq!(
            r#""YQ==""#,
            Scalar::new_binary(Vec::from_iter("a".bytes())).to_string()
        );
        assert_eq!(
            r#"["YQ==", "Yg==", "Yw=="]"#,
            BinarySet::new(["a".bytes(), "b".bytes(), "c".bytes()].map(Vec::from_iter)).to_string()
        );
    }
}