@@ -3,6 +3,7 @@ use super::strs::{CStr16, FromSliceWithNulError};
3
3
use crate :: data_types:: strs:: EqStrUntilNul ;
4
4
use crate :: data_types:: UnalignedSlice ;
5
5
use crate :: polyfill:: vec_into_raw_parts;
6
+ use alloc:: borrow:: { Borrow , ToOwned } ;
6
7
use alloc:: vec:: Vec ;
7
8
use core:: fmt;
8
9
use core:: ops;
@@ -133,6 +134,20 @@ impl AsRef<CStr16> for CString16 {
133
134
}
134
135
}
135
136
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
+
136
151
impl fmt:: Display for CString16 {
137
152
fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
138
153
self . as_ref ( ) . fmt ( f)
@@ -155,6 +170,7 @@ impl<StrType: AsRef<str> + ?Sized> EqStrUntilNul<StrType> for CString16 {
155
170
#[ cfg( test) ]
156
171
mod tests {
157
172
use super :: * ;
173
+ use crate :: cstr16;
158
174
use alloc:: string:: String ;
159
175
use alloc:: vec;
160
176
@@ -224,4 +240,21 @@ mod tests {
224
240
assert ! ( String :: from( "test" ) . eq_str_until_nul( & input) ) ;
225
241
assert ! ( "test" . eq_str_until_nul( & input) ) ;
226
242
}
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
+ }
227
260
}
0 commit comments