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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use std::{fmt::Display, marker::PhantomData};

use serde::{
    de::{self, VariantAccess},
    ser, Serialize,
};
use serde_amqp::{primitives::Binary, Value};

use crate::messaging::{
    AmqpSequence, AmqpValue, Batch, Data, DeserializableBody, FromBody, FromEmptyBody, IntoBody,
    SerializableBody, TransposeOption, __private::BodySection,
};

/// The body consists of one of the following three choices: one or more data sections, one or more
/// amqp-sequence sections, or a single amqp-value section.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Body<T> {
    /// An amqp-value section contains a single AMQP value
    Value(AmqpValue<T>),

    /// One or more data section
    ///
    /// Added since `"0.6.0"`
    Data(Batch<Data>),

    /// One or more sequence section
    ///
    /// Added since `"0.6.0"`
    Sequence(Batch<AmqpSequence<T>>),

    /// There is no body section at all
    ///
    /// The core specification states that **at least one** body section should be present in
    /// the message. However, this is not the way `proton` is implemented, and according to
    /// [PROTON-2574](https://issues.apache.org/jira/browse/PROTON-2574), the wording in the
    /// core specification was an unintended.
    Empty,
}

impl<T> Body<T> {
    /// Whether the body section is a [`Data`]
    pub fn is_data(&self) -> bool {
        matches!(self, Body::Data(_))
    }

    /// Whether the body section is a [`AmqpSequence`]
    pub fn is_sequence(&self) -> bool {
        matches!(self, Body::Sequence(_))
    }

    /// Whether the body section is a [`AmqpValue`]
    pub fn is_value(&self) -> bool {
        matches!(self, Body::Value(_))
    }

    /// Whether the body section is `Nothing`
    #[deprecated(since = "0.5.2", note = "Please use is_empty() instead")]
    pub fn is_nothing(&self) -> bool {
        matches!(self, Body::Empty)
    }

    /// Whether the body section is `Nothing`
    pub fn is_empty(&self) -> bool {
        matches!(self, Body::Empty)
    }

    /// Consume the delivery into the body if the body is an [`AmqpValue`].
    /// An error will be returned if otherwise
    pub fn try_into_value(self) -> Result<T, Self> {
        match self {
            Body::Value(AmqpValue(value)) => Ok(value),
            _ => Err(self),
        }
    }

    /// Consume the delivery into the body if the body is one or more [`Data`].
    /// An error will be returned if otherwise
    pub fn try_into_data(self) -> Result<impl Iterator<Item = Binary>, Self> {
        match self {
            Body::Data(batch) => Ok(batch.into_iter().map(|data| data.0)),
            _ => Err(self),
        }
    }

    /// Consume the delivery into the body if the body is one or more [`AmqpSequence`].
    /// An error will be returned if otherwise
    pub fn try_into_sequence(self) -> Result<impl Iterator<Item = Vec<T>>, Self> {
        match self {
            Body::Sequence(batch) => Ok(batch.into_iter().map(|seq| seq.0)),
            _ => Err(self),
        }
    }

    /// Get a reference to the delivery body if the body is an [`AmqpValue`].
    /// An error will be returned if the body isnot an [`AmqpValue`]
    pub fn try_as_value(&self) -> Result<&T, &Self> {
        match self {
            Body::Value(AmqpValue(value)) => Ok(value),
            _ => Err(self),
        }
    }

    /// Get a reference to the delivery body if the body is one or more [`Data`].
    /// An error will be returned otherwise
    pub fn try_as_data(&self) -> Result<impl Iterator<Item = &Binary>, &Self> {
        match self {
            Body::Data(batch) => Ok(batch.iter().map(|data| &data.0)),
            _ => Err(self),
        }
    }

    /// Get a reference to the delivery body if the body is one or more [`AmqpSequence`].
    /// An error will be returned otherwise
    pub fn try_as_sequence(&self) -> Result<impl Iterator<Item = &Vec<T>>, &Self> {
        match self {
            Body::Sequence(batch) => Ok(batch.iter().map(|seq| &seq.0)),
            _ => Err(self),
        }
    }
}

impl<T> Display for Body<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            Body::Value(val) => write!(f, "{}", val),
            Body::Data(_) => write!(f, "Data"),
            Body::Sequence(_) => write!(f, "Sequence"),
            Body::Empty => write!(f, "Nothing"),
        }
    }
}

impl<T: Serialize> From<T> for Body<T> {
    fn from(value: T) -> Self {
        Self::Value(AmqpValue(value))
    }
}

impl<T: Serialize + Clone, const N: usize> From<[T; N]> for Body<T> {
    fn from(values: [T; N]) -> Self {
        Self::Sequence(Batch::new(vec![AmqpSequence(values.to_vec())]))
    }
}

impl<T> From<AmqpValue<T>> for Body<T> {
    fn from(value: AmqpValue<T>) -> Self {
        Self::Value(value)
    }
}

impl<T> From<AmqpSequence<T>> for Body<T> {
    fn from(val: AmqpSequence<T>) -> Self {
        Self::Sequence(Batch::new(vec![val]))
    }
}

impl From<Data> for Body<Value> {
    fn from(val: Data) -> Self {
        Self::Data(Batch::new(vec![val]))
    }
}

impl<T: Serialize> ser::Serialize for Body<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Body::Data(data) => data.serialize(serializer),
            Body::Sequence(seq) => seq.serialize(serializer),
            Body::Value(val) => val.serialize(serializer),
            Body::Empty => AmqpValue(()).serialize(serializer),
        }
    }
}

struct FieldVisitor {}

#[derive(Debug)]
enum Field {
    Data,
    Sequence,
    Value,
}

impl<'de> de::Visitor<'de> for FieldVisitor {
    type Value = Field;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("Body variant. One of Vec<Data>, Vec<AmqpSequence>, AmqpValue")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        match v {
            "amqp:data:binary" => Ok(Field::Data),
            "amqp:amqp-sequence:list" => Ok(Field::Sequence),
            "amqp:amqp-value:*" => Ok(Field::Value),
            _ => Err(de::Error::custom("Invalid descriptor code")),
        }
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        match v {
            0x0000_0000_0000_0075 => Ok(Field::Data),
            0x0000_0000_0000_0076 => Ok(Field::Sequence),
            0x0000_0000_0000_0077 => Ok(Field::Value),
            _ => Err(de::Error::custom("Invalid descriptor code")),
        }
    }
}

impl<'de> de::Deserialize<'de> for Field {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_identifier(FieldVisitor {})
    }
}

struct Visitor<T> {
    marker: PhantomData<T>,
}

impl<'de, T> de::Visitor<'de> for Visitor<T>
where
    T: de::Deserialize<'de>,
{
    type Value = Body<T>;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("enum Body")
    }

    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
    where
        A: de::EnumAccess<'de>,
    {
        let (val, variant) = data.variant()?;

        match val {
            Field::Data => {
                let data: Batch<Data> = variant.newtype_variant()?;
                Ok(Body::Data(data))
            }
            Field::Sequence => {
                let sequence: Batch<AmqpSequence<_>> = variant.newtype_variant()?;
                Ok(Body::Sequence(sequence))
            }
            Field::Value => {
                let value = variant.newtype_variant()?;
                Ok(Body::Value(value))
            }
        }
    }
}

impl<'de, T> de::Deserialize<'de> for Body<T>
where
    T: de::Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_enum(
            serde_amqp::__constants::UNTAGGED_ENUM,
            &["Data", "Sequence", "Value"],
            Visitor {
                marker: PhantomData,
            },
        )
    }
}

impl<T> BodySection for Body<T> {}

impl<T> SerializableBody for Body<T> where T: ser::Serialize {}

impl<'de, T> DeserializableBody<'de> for Body<T> where T: de::Deserialize<'de> {}

impl<T> IntoBody for Body<T>
where
    T: ser::Serialize,
{
    type Body = Self;

    fn into_body(self) -> Self::Body {
        self
    }
}

impl<'de, T> FromBody<'de> for Body<T>
where
    T: de::Deserialize<'de>,
{
    type Body = Self;

    fn from_body(deserializable: Self::Body) -> Self {
        deserializable
    }
}

impl<T> FromEmptyBody for Body<T> {
    fn from_empty_body() -> Result<Self, serde_amqp::Error> {
        Ok(Self::Empty)
    }
}

impl<'de, T, U> TransposeOption<'de, T> for Body<U>
where
    T: FromBody<'de, Body = Body<U>>,
    U: de::Deserialize<'de>,
{
    type From = Body<Option<U>>;

    fn transpose(src: Self::From) -> Option<T> {
        match src {
            Body::Value(AmqpValue(body)) => {
                body.map(|body| T::from_body(Body::Value(AmqpValue(body))))
            }
            Body::Data(batch) => {
                if batch.is_empty() {
                    // Note that a null value and a zero-length array (with a correct type for its
                    // elements) both describe an absence of a value and MUST be treated as
                    // semantically identical.
                    None
                } else {
                    Some(T::from_body(Body::Data(batch)))
                }
            }
            Body::Sequence(batch) => {
                if batch.is_empty() {
                    // Note that a null value and a zero-length array (with a correct type for its
                    // elements) both describe an absence of a value and MUST be treated as
                    // semantically identical.
                    None
                } else {
                    let batch: Option<Batch<AmqpSequence<U>>> = batch
                        .into_iter()
                        .map(|AmqpSequence(vec)| {
                            let vec: Option<Vec<U>> = vec.into_iter().collect();
                            vec.map(AmqpSequence)
                        })
                        .collect();

                    batch.map(|batch| T::from_body(Body::Sequence(batch)))
                }
            }
            Body::Empty => None,
        }
    }
}

#[cfg(test)]
mod tests {}