Skip to main content

cu29_logstream/
copper.rs

1use crate::record::{RECORD_HEADER_LEN, encode_record_header};
2use crate::{Error, RecordKind, Result};
3use alloc::{string::ToString, vec::Vec};
4use cu29_runtime::copperlist::CopperList;
5use cu29_traits::CopperListTuple;
6
7/// Serializes the generated CopperList view selected by its application codec.
8///
9/// Generated codecs retain metadata for every slot while omitting payload bytes
10/// excluded from the selected view, so the result may be a partial CopperList.
11pub fn encode_copperlist<P: CopperListTuple>(copperlist: &CopperList<P>) -> Result<Vec<u8>> {
12    bincode::encode_to_vec(copperlist, bincode::config::standard())
13        .map_err(|error| Error::Codec(error.to_string()))
14}
15
16/// Serializes and frames one CopperList directly into reusable caller-owned storage.
17pub fn encode_copperlist_record_into<P: CopperListTuple>(
18    copperlist: &CopperList<P>,
19    output: &mut [u8],
20) -> Result<usize> {
21    if output.len() < RECORD_HEADER_LEN {
22        return Err(Error::BufferTooSmall {
23            needed: RECORD_HEADER_LEN,
24            available: output.len(),
25        });
26    }
27    let (header, payload) = output.split_at_mut(RECORD_HEADER_LEN);
28    let payload_len = bincode::encode_into_slice(copperlist, payload, bincode::config::standard())
29        .map_err(|error| Error::Codec(error.to_string()))?;
30    encode_record_header(
31        RecordKind::CopperList,
32        copperlist.id,
33        &payload[..payload_len],
34        header,
35    )?;
36    Ok(RECORD_HEADER_LEN + payload_len)
37}
38
39/// Decodes one application-typed full or partial CopperList.
40pub fn decode_copperlist<P: CopperListTuple>(payload: &[u8]) -> Result<CopperList<P>> {
41    let (copperlist, consumed) = bincode::decode_from_slice(payload, bincode::config::standard())
42        .map_err(|error| Error::Codec(error.to_string()))?;
43    if consumed != payload.len() {
44        return Err(Error::Codec("CopperList has trailing bytes".into()));
45    }
46    Ok(copperlist)
47}