datagram_builder/
deserialize.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/nimble-rust/nimble
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5use datagram::DatagramParser;
6use flood_rs::{in_stream::InOctetStream, Deserialize, ReadOctetStream};
7use std::io;
8
9/// Deserializes a collection of datagrams into a vector of items.
10///
11/// Each datagram is parsed to extract its payload, and the payload is then
12/// deserialized into items of type `T`. All successfully deserialized items
13/// are aggregated into a single vector.
14///
15/// # Arguments
16///
17/// * `datagrams` - An iterable collection of byte slices, each representing a serialized datagram.
18/// * `parser` - A mutable reference to an implementation of `DatagramParser`.
19///
20/// # Returns
21///
22/// * `io::Result<Vec<T>>` - A vector of deserialized items.
23///
24/// # Errors
25///
26/// Returns an `io::Error` if parsing any datagram or deserializing any item fails.
27pub fn deserialize_datagrams<T, I>(
28    datagrams: I,
29    parser: &mut impl DatagramParser,
30) -> io::Result<Vec<T>>
31where
32    T: Deserialize,
33    I: IntoIterator<Item = Vec<u8>>,
34{
35    let mut items = Vec::new();
36
37    for datagram in datagrams.into_iter() {
38        let payload_slice = parser.parse(&datagram)?;
39
40        let mut in_stream = InOctetStream::new(payload_slice);
41        while !in_stream.has_reached_end() {
42            let item = T::deserialize(&mut in_stream)?;
43            items.push(item);
44        }
45    }
46
47    Ok(items)
48}