bin_proto/impls/
cstr.rs

1use core::ffi::CStr;
2
3use bitstream_io::{BitWrite, Endianness};
4
5use crate::{util, BitEncode, Result};
6
7impl<Ctx> BitEncode<Ctx> for CStr {
8    fn encode<W, E>(&self, write: &mut W, ctx: &mut Ctx, (): ()) -> Result<()>
9    where
10        W: BitWrite,
11        E: Endianness,
12    {
13        util::encode_items::<_, E, _, _>(self.to_bytes_with_nul().iter(), write, ctx)
14    }
15}
16
17#[cfg(feature = "alloc")]
18#[allow(clippy::wildcard_imports)]
19mod decode {
20    use alloc::{boxed::Box, ffi::CString};
21    use bitstream_io::BitRead;
22
23    use crate::BitDecode;
24
25    use super::*;
26
27    impl<Ctx> BitDecode<Ctx> for Box<CStr> {
28        fn decode<R, E>(read: &mut R, ctx: &mut Ctx, tag: ()) -> Result<Self>
29        where
30            R: BitRead,
31            E: Endianness,
32        {
33            CString::decode::<_, E>(read, ctx, tag).map(Into::into)
34        }
35    }
36
37    test_decode!(Box<CStr>; [0x41, 0x42, 0x43, 0] => CString::new("ABC").unwrap().into());
38}
39
40test_encode!(
41    &CStr; CStr::from_bytes_with_nul(&[0x41, 0x42, 0x43, 0]).unwrap() => [0x41, 0x42, 0x43, 0]
42);