|
1 | 1 | use super::chars::{Char16, Char8, NUL_16, NUL_8};
|
2 | 2 | use super::UnalignedSlice;
|
| 3 | +use core::ffi::CStr; |
3 | 4 | use core::fmt;
|
4 | 5 | use core::iter::Iterator;
|
5 | 6 | use core::mem::MaybeUninit;
|
@@ -58,6 +59,11 @@ pub enum FromStrWithBufError {
|
58 | 59 | /// This type is largely inspired by [`core::ffi::CStr`] with the exception that all characters are
|
59 | 60 | /// guaranteed to be 8 bit long.
|
60 | 61 | ///
|
| 62 | +/// A [`CStr8`] can be constructed from a [`core::ffi::CStr`] via a `try_from` call: |
| 63 | +/// ```ignore |
| 64 | +/// let cstr8: &CStr8 = TryFrom::try_from(cstr).unwrap(); |
| 65 | +/// ``` |
| 66 | +/// |
61 | 67 | /// For convenience, a [`CStr8`] is comparable with [`core::str`] and
|
62 | 68 | /// `alloc::string::String` from the standard library through the trait [`EqStrUntilNul`].
|
63 | 69 | #[repr(transparent)]
|
@@ -156,6 +162,14 @@ impl<StrType: AsRef<str> + ?Sized> EqStrUntilNul<StrType> for CStr8 {
|
156 | 162 | }
|
157 | 163 | }
|
158 | 164 |
|
| 165 | +impl<'a> TryFrom<&'a CStr> for &'a CStr8 { |
| 166 | + type Error = FromSliceWithNulError; |
| 167 | + |
| 168 | + fn try_from(cstr: &'a CStr) -> Result<Self, Self::Error> { |
| 169 | + CStr8::from_bytes_with_nul(cstr.to_bytes_with_nul()) |
| 170 | + } |
| 171 | +} |
| 172 | + |
159 | 173 | /// An UCS-2 null-terminated string.
|
160 | 174 | ///
|
161 | 175 | /// This type is largely inspired by [`core::ffi::CStr`] with the exception that all characters are
|
@@ -453,6 +467,16 @@ mod tests {
|
453 | 467 | use crate::alloc::string::String;
|
454 | 468 | use uefi_macros::{cstr16, cstr8};
|
455 | 469 |
|
| 470 | + // Tests if our CStr8 type can be constructed from a valid core::ffi::CStr |
| 471 | + #[test] |
| 472 | + fn test_cstr8_from_cstr() { |
| 473 | + let msg = "hello world\0"; |
| 474 | + let cstr = unsafe { CStr::from_ptr(msg.as_ptr().cast()) }; |
| 475 | + let cstr8: &CStr8 = TryFrom::try_from(cstr).unwrap(); |
| 476 | + assert!(cstr8.eq_str_until_nul(msg)); |
| 477 | + assert!(msg.eq_str_until_nul(cstr8)); |
| 478 | + } |
| 479 | + |
456 | 480 | #[test]
|
457 | 481 | fn test_cstr16_num_bytes() {
|
458 | 482 | let s = CStr16::from_u16_with_nul(&[65, 66, 67, 0]).unwrap();
|
|
0 commit comments