Skip to content

Commit aa03b83

Browse files
committed
cstr16: add method to get the underlying bytes
1 parent ec9ffa3 commit aa03b83

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
- `From<&CStr16>` for `String`
2121
- `From<&CString16>` for `String`
2222
- Added `RuntimeServices::get_variable_boxed` (requires the `alloc` feature).
23+
- Added `CStr16::to_bytes` and `CStr16::to_bytes_with_nul` as well as
24+
`AsRef<[u8]>` and `Borrow<[u8]>` for `CStr16`.
25+
- Added `AsRef<[u8]>` and `Borrow<[u8]>` for `CStr16`.
2326

2427
### Changed
2528

uefi/src/data_types/strs.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use super::chars::{Char16, Char8, NUL_16, NUL_8};
22
use super::UnalignedSlice;
33
use crate::polyfill::maybe_uninit_slice_assume_init_ref;
4+
use core::borrow::Borrow;
45
use core::ffi::CStr;
56
use core::iter::Iterator;
67
use core::mem::MaybeUninit;
@@ -147,6 +148,18 @@ impl fmt::Display for CStr8 {
147148
}
148149
}
149150

151+
impl AsRef<[u8]> for CStr8 {
152+
fn as_ref(&self) -> &[u8] {
153+
self.to_bytes_with_nul()
154+
}
155+
}
156+
157+
impl Borrow<[u8]> for CStr8 {
158+
fn borrow(&self) -> &[u8] {
159+
self.to_bytes_with_nul()
160+
}
161+
}
162+
150163
impl<StrType: AsRef<str> + ?Sized> EqStrUntilNul<StrType> for CStr8 {
151164
fn eq_str_until_nul(&self, other: &StrType) -> bool {
152165
let other = other.as_ref();
@@ -389,6 +402,32 @@ impl CStr16 {
389402
}
390403
Ok(())
391404
}
405+
406+
/// Like [`to_bytes_with_nul`] but without the terminating null character.
407+
#[must_use]
408+
pub fn to_bytes(&self) -> &[u8] {
409+
let slice = self.to_bytes_with_nul();
410+
&slice[..slice.len() - 1]
411+
}
412+
413+
/// Returns the underlying bytes as slice including the terminating null
414+
/// character.
415+
#[must_use]
416+
pub fn to_bytes_with_nul(&self) -> &[u8] {
417+
unsafe { &*(slice::from_raw_parts(self.0.as_ptr().cast(), self.num_bytes())) }
418+
}
419+
}
420+
421+
impl AsRef<[u8]> for CStr16 {
422+
fn as_ref(&self) -> &[u8] {
423+
self.to_bytes_with_nul()
424+
}
425+
}
426+
427+
impl Borrow<[u8]> for CStr16 {
428+
fn borrow(&self) -> &[u8] {
429+
self.to_bytes_with_nul()
430+
}
392431
}
393432

394433
#[cfg(feature = "alloc")]
@@ -615,6 +654,7 @@ mod tests {
615654
string.as_slice_with_nul(),
616655
&[Char16::try_from('a').unwrap(), NUL_16]
617656
);
657+
assert_eq!(string.to_bytes(), &[b'a', 0, 0, 0])
618658
}
619659

620660
// Code generation helper for the compare tests of our CStrX types against "str" and "String"

0 commit comments

Comments
 (0)