|
1 | 1 | use super::chars::{Char16, Char8, NUL_16, NUL_8};
|
2 | 2 | use super::UnalignedSlice;
|
3 | 3 | use crate::polyfill::maybe_uninit_slice_assume_init_ref;
|
| 4 | +use core::borrow::Borrow; |
4 | 5 | use core::ffi::CStr;
|
5 | 6 | use core::iter::Iterator;
|
6 | 7 | use core::mem::MaybeUninit;
|
@@ -147,6 +148,18 @@ impl fmt::Display for CStr8 {
|
147 | 148 | }
|
148 | 149 | }
|
149 | 150 |
|
| 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 | + |
150 | 163 | impl<StrType: AsRef<str> + ?Sized> EqStrUntilNul<StrType> for CStr8 {
|
151 | 164 | fn eq_str_until_nul(&self, other: &StrType) -> bool {
|
152 | 165 | let other = other.as_ref();
|
@@ -389,6 +402,32 @@ impl CStr16 {
|
389 | 402 | }
|
390 | 403 | Ok(())
|
391 | 404 | }
|
| 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 | + } |
392 | 431 | }
|
393 | 432 |
|
394 | 433 | #[cfg(feature = "alloc")]
|
@@ -615,6 +654,7 @@ mod tests {
|
615 | 654 | string.as_slice_with_nul(),
|
616 | 655 | &[Char16::try_from('a').unwrap(), NUL_16]
|
617 | 656 | );
|
| 657 | + assert_eq!(string.to_bytes(), &[b'a', 0, 0, 0]) |
618 | 658 | }
|
619 | 659 |
|
620 | 660 | // Code generation helper for the compare tests of our CStrX types against "str" and "String"
|
|
0 commit comments