From 789b078bba950d8390285ea1c6b38761bfdd5da5 Mon Sep 17 00:00:00 2001 From: Nicholas Bishop Date: Sun, 12 Mar 2023 12:52:37 -0400 Subject: [PATCH] uefi: Implement Borrow/ToOwned for CString16/CStr16 `CString16` can be borrowed as `&CStr16`, and `CStr16` can be converted to `CString16` with `to_owned()`. --- CHANGELOG.md | 1 + uefi/src/data_types/owned_strs.rs | 33 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e89ea091..893cdfa6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/uefi/src/data_types/owned_strs.rs b/uefi/src/data_types/owned_strs.rs index c8d5f5fa4..3b5aa5a3b 100644 --- a/uefi/src/data_types/owned_strs.rs +++ b/uefi/src/data_types/owned_strs.rs @@ -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; @@ -133,6 +134,20 @@ impl AsRef for CString16 { } } +impl Borrow 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) @@ -155,6 +170,7 @@ impl + ?Sized> EqStrUntilNul for CString16 { #[cfg(test)] mod tests { use super::*; + use crate::cstr16; use alloc::string::String; use alloc::vec; @@ -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 + ] + ); + } }