Skip to content

uefi: Implement Borrow/ToOwned for CString16/CStr16 #695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
to `ComponentName1` otherwise.
- `FileType`, `FileHandle`, `RegularFile`, and `Directory` now implement `Debug`.
- Added `RuntimeServices::delete_variable()` helper method.
- Implement `Borrow` for `CString16` and `ToOwned` for `CStr16`.

### Changed

Expand Down
33 changes: 33 additions & 0 deletions uefi/src/data_types/owned_strs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use super::strs::{CStr16, FromSliceWithNulError};
use crate::data_types::strs::EqStrUntilNul;
use crate::data_types::UnalignedSlice;
use crate::polyfill::vec_into_raw_parts;
use alloc::borrow::{Borrow, ToOwned};
use alloc::vec::Vec;
use core::fmt;
use core::ops;
Expand Down Expand Up @@ -133,6 +134,20 @@ impl AsRef<CStr16> for CString16 {
}
}

impl Borrow<CStr16> for CString16 {
fn borrow(&self) -> &CStr16 {
self
}
}

impl ToOwned for CStr16 {
type Owned = CString16;

fn to_owned(&self) -> CString16 {
CString16(self.as_slice_with_nul().to_vec())
}
}

impl fmt::Display for CString16 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.as_ref().fmt(f)
Expand All @@ -155,6 +170,7 @@ impl<StrType: AsRef<str> + ?Sized> EqStrUntilNul<StrType> for CString16 {
#[cfg(test)]
mod tests {
use super::*;
use crate::cstr16;
use alloc::string::String;
use alloc::vec;

Expand Down Expand Up @@ -224,4 +240,21 @@ mod tests {
assert!(String::from("test").eq_str_until_nul(&input));
assert!("test".eq_str_until_nul(&input));
}

/// Test the `Borrow` and `ToOwned` impls.
#[test]
fn test_borrow_and_to_owned() {
let s1: &CStr16 = cstr16!("ab");
let owned: CString16 = s1.to_owned();
let s2: &CStr16 = owned.borrow();
assert_eq!(s1, s2);
assert_eq!(
owned.0,
[
Char16::try_from('a').unwrap(),
Char16::try_from('b').unwrap(),
NUL_16
]
);
}
}