comparison libpam-sys/src/structs.rs @ 117:20f7712a6857

Neaten up libpam-sys BinaryPayload buffer management.
author Paul Fisher <paul@pfish.zone>
date Sun, 29 Jun 2025 18:48:14 -0400
parents bb465393621f
children 39760dfc9b3b
comparison
equal deleted inserted replaced
116:a12706e42c9d 117:20f7712a6857
32 me.total_bytes_u32be = u32::to_be_bytes(buf.len() as u32); 32 me.total_bytes_u32be = u32::to_be_bytes(buf.len() as u32);
33 me.data_type = data_type; 33 me.data_type = data_type;
34 buf[5..].copy_from_slice(data) 34 buf[5..].copy_from_slice(data)
35 } 35 }
36 36
37 /// The size of the message contained in the buffer.
38 fn len(&self) -> usize {
39 self.total_bytes().saturating_sub(5)
40 }
41
42 /// The total storage needed for the message, including header. 37 /// The total storage needed for the message, including header.
43 pub fn total_bytes(&self) -> usize { 38 pub fn total_bytes(&self) -> usize {
44 u32::from_be_bytes(self.total_bytes_u32be) as usize 39 u32::from_be_bytes(self.total_bytes_u32be) as usize
45 } 40 }
46 41
47 /// Gets the contents of the BinaryMessage stored at the given pointer. 42 /// Gets the total byte buffer of the BinaryMessage stored at the pointer.
48 /// 43 ///
49 /// The returned data slice is borrowed from where the pointer points to. 44 /// The returned data slice is borrowed from where the pointer points to.
50 /// 45 ///
51 /// # Safety 46 /// # Safety
52 /// 47 ///
53 /// - The pointer must point to a valid `BinaryPayload`. 48 /// - The pointer must point to a valid `BinaryPayload`.
54 /// - The borrowed data must not outlive the validity of this pointer. 49 /// - The borrowed data must not outlive the pointer's validity.
50 pub unsafe fn buffer_of<'a>(ptr: *const Self) -> &'a [u8] {
51 let header: &Self = ptr.as_ref().unwrap_unchecked();
52 slice::from_raw_parts(ptr.cast(), header.total_bytes().max(5))
53 }
54
55 /// Gets the contents of the BinaryMessage stored at the given pointer.
56 ///
57 /// The returned data slice is borrowed from where the pointer points to.
58 /// This is a cheap operation and doesn't do *any* copying.
59 ///
60 /// We don't take a `&self` reference here because accessing beyond
61 /// the range of the `Self` data (i.e., beyond the 5 bytes of `self`)
62 /// is undefined behavior. Instead, you have to pass a raw pointer
63 /// directly to the data.
64 ///
65 /// # Safety
66 ///
67 /// - The pointer must point to a valid `BinaryPayload`.
68 /// - The borrowed data must not outlive the pointer's validity.
55 pub unsafe fn contents<'a>(ptr: *const Self) -> (u8, &'a [u8]) { 69 pub unsafe fn contents<'a>(ptr: *const Self) -> (u8, &'a [u8]) {
56 let header: &Self = ptr.as_ref().unwrap_unchecked(); 70 let header: &Self = ptr.as_ref().unwrap_unchecked();
57 let typ = header.data_type;
58 ( 71 (
59 typ, 72 header.data_type,
60 slice::from_raw_parts(ptr.cast::<u8>().offset(5), header.len()), 73 &Self::buffer_of(ptr)[5..]
61 ) 74 )
62 } 75 }
63 } 76 }