bin_proto/impls/
cstring.rs

1#![cfg(feature = "alloc")]
2
3use alloc::{ffi::CString, vec::Vec};
4use bitstream_io::{BitRead, BitWrite, Endianness};
5
6use crate::{util, BitDecode, BitEncode, Result};
7
8impl<Ctx> BitDecode<Ctx> for CString {
9    fn decode<R, E>(read: &mut R, ctx: &mut Ctx, tag: ()) -> Result<Self>
10    where
11        R: BitRead,
12        E: Endianness,
13    {
14        let mut result = Vec::new();
15        loop {
16            let c: u8 = BitDecode::decode::<_, E>(read, ctx, tag)?;
17            if c == 0x00 {
18                return Ok(Self::new(result)?);
19            }
20            result.push(c);
21        }
22    }
23}
24
25impl<Ctx> BitEncode<Ctx> for CString {
26    fn encode<W, E>(&self, write: &mut W, ctx: &mut Ctx, (): ()) -> Result<()>
27    where
28        W: BitWrite,
29        E: Endianness,
30    {
31        util::encode_items::<_, E, _, _>(self.to_bytes_with_nul().iter(), write, ctx)
32    }
33}
34
35test_codec!(CString; CString::new("ABC").unwrap() => [0x41, 0x42, 0x43, 0]);
36test_roundtrip!(CString);