Skip to content

Commit b75262f

Browse files
authored
Merge pull request rust-osdev#695 from nicholasbishop/bishop-cstr-own-borrow
uefi: Implement Borrow/ToOwned for CString16/CStr16
2 parents 6d3751f + 789b078 commit b75262f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
to `ComponentName1` otherwise.
1010
- `FileType`, `FileHandle`, `RegularFile`, and `Directory` now implement `Debug`.
1111
- Added `RuntimeServices::delete_variable()` helper method.
12+
- Implement `Borrow` for `CString16` and `ToOwned` for `CStr16`.
1213

1314
### Changed
1415

uefi/src/data_types/owned_strs.rs

+33
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use super::strs::{CStr16, FromSliceWithNulError};
33
use crate::data_types::strs::EqStrUntilNul;
44
use crate::data_types::UnalignedSlice;
55
use crate::polyfill::vec_into_raw_parts;
6+
use alloc::borrow::{Borrow, ToOwned};
67
use alloc::vec::Vec;
78
use core::fmt;
89
use core::ops;
@@ -133,6 +134,20 @@ impl AsRef<CStr16> for CString16 {
133134
}
134135
}
135136

137+
impl Borrow<CStr16> for CString16 {
138+
fn borrow(&self) -> &CStr16 {
139+
self
140+
}
141+
}
142+
143+
impl ToOwned for CStr16 {
144+
type Owned = CString16;
145+
146+
fn to_owned(&self) -> CString16 {
147+
CString16(self.as_slice_with_nul().to_vec())
148+
}
149+
}
150+
136151
impl fmt::Display for CString16 {
137152
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138153
self.as_ref().fmt(f)
@@ -155,6 +170,7 @@ impl<StrType: AsRef<str> + ?Sized> EqStrUntilNul<StrType> for CString16 {
155170
#[cfg(test)]
156171
mod tests {
157172
use super::*;
173+
use crate::cstr16;
158174
use alloc::string::String;
159175
use alloc::vec;
160176

@@ -224,4 +240,21 @@ mod tests {
224240
assert!(String::from("test").eq_str_until_nul(&input));
225241
assert!("test".eq_str_until_nul(&input));
226242
}
243+
244+
/// Test the `Borrow` and `ToOwned` impls.
245+
#[test]
246+
fn test_borrow_and_to_owned() {
247+
let s1: &CStr16 = cstr16!("ab");
248+
let owned: CString16 = s1.to_owned();
249+
let s2: &CStr16 = owned.borrow();
250+
assert_eq!(s1, s2);
251+
assert_eq!(
252+
owned.0,
253+
[
254+
Char16::try_from('a').unwrap(),
255+
Char16::try_from('b').unwrap(),
256+
NUL_16
257+
]
258+
);
259+
}
227260
}

0 commit comments

Comments
 (0)