@@ -3,6 +3,7 @@ use super::strs::{CStr16, FromSliceWithNulError};
33use crate :: data_types:: strs:: EqStrUntilNul ;
44use crate :: data_types:: UnalignedSlice ;
55use crate :: polyfill:: vec_into_raw_parts;
6+ use alloc:: borrow:: { Borrow , ToOwned } ;
67use alloc:: vec:: Vec ;
78use core:: fmt;
89use 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+
136151impl 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) ]
156171mod 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