datagram_builder/serialize.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::{DatagramBuilder, DatagramError};
6use flood_rs::{out_stream::OutOctetStream, Serialize};
7use log::trace;
8use std::fmt::Debug;
9use std::io;
10use std::io::ErrorKind;
11
12/// Serializes a list of items into datagrams.
13///
14/// Each datagram is constructed using the provided [`DatagramBuilder`]. Items are serialized
15/// and packed into datagrams without exceeding the `max_packet_size`.
16///
17/// # Arguments
18///
19/// * `items` - A slice of items to serialize.
20/// * `max_packet_size` - The maximum size of each packet.
21/// * `builder` - A mutable reference to an implementation of `DatagramBuilder`.
22///
23/// # Returns
24///
25/// * `io::Result<Vec<Vec<u8>>>` - A vector of serialized datagrams.
26///
27/// # Errors
28///
29/// Returns an `io::Error` if any item is too large to fit in a packet or if serialization fails.
30pub fn serialize_datagrams<T, I>(
31 items: I,
32 builder: &mut impl DatagramBuilder,
33) -> io::Result<Vec<Vec<u8>>>
34where
35 T: Serialize + Debug,
36 I: AsRef<[T]>,
37{
38 let mut packets = Vec::new();
39
40 builder.clear()?;
41
42 for item in items.as_ref() {
43 trace!("serializing item {item:?}");
44
45 // Serialize the item into the buffer
46 let mut item_stream = OutOctetStream::new();
47 item.serialize(&mut item_stream)?;
48 let item_octets = item_stream.octets_ref();
49 let item_len = item_octets.len();
50
51 if item_len == 0 {
52 return Err(io::Error::new(
53 io::ErrorKind::InvalidInput,
54 "zero item length is illegal for serialization",
55 ));
56 }
57
58 match builder.push(item_octets) {
59 Err(DatagramError::BufferFull) => {
60 packets.push(builder.finalize()?.to_vec());
61 builder.clear()?;
62 builder
63 .push(item_octets)
64 .map_err(|err| io::Error::new(ErrorKind::InvalidData, err))?;
65 }
66 Err(DatagramError::IoError(io_err)) => {
67 return Err(io_err);
68 }
69 Err(err) => {
70 // Handle any unexpected errors or provide a default error handling
71 // Optionally, you can log or return an error here if needed
72 return Err(io::Error::new(ErrorKind::InvalidData, err));
73 }
74 Ok(_) => {}
75 }
76 }
77
78 if !builder.is_empty() {
79 packets.push(builder.finalize()?.to_vec());
80 }
81
82 Ok(packets)
83}