File tree 2 files changed +20
-2
lines changed
2 files changed +20
-2
lines changed Original file line number Diff line number Diff line change @@ -613,7 +613,8 @@ impl CString {
613
613
#[ inline]
614
614
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
615
615
pub fn as_bytes ( & self ) -> & [ u8 ] {
616
- & self . inner [ ..self . inner . len ( ) - 1 ]
616
+ // SAFETY: CString has a length at least 1
617
+ unsafe { self . inner . get_unchecked ( ..self . inner . len ( ) - 1 ) }
617
618
}
618
619
619
620
/// Equivalent to [`CString::as_bytes()`] except that the
@@ -1322,7 +1323,8 @@ impl CStr {
1322
1323
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1323
1324
pub fn to_bytes ( & self ) -> & [ u8 ] {
1324
1325
let bytes = self . to_bytes_with_nul ( ) ;
1325
- & bytes[ ..bytes. len ( ) - 1 ]
1326
+ // SAFETY: to_bytes_with_nul returns slice with length at least 1
1327
+ unsafe { bytes. get_unchecked ( ..bytes. len ( ) - 1 ) }
1326
1328
}
1327
1329
1328
1330
/// Converts this C string to a byte slice containing the trailing 0 byte.
Original file line number Diff line number Diff line change @@ -193,3 +193,19 @@ fn cstr_index_from_empty() {
193
193
let cstr = CStr :: from_bytes_with_nul ( original) . unwrap ( ) ;
194
194
let _ = & cstr[ original. len ( ) ..] ;
195
195
}
196
+
197
+ #[ test]
198
+ fn c_string_from_empty_string ( ) {
199
+ let original = "" ;
200
+ let cstring = CString :: new ( original) . unwrap ( ) ;
201
+ assert_eq ! ( original. as_bytes( ) , cstring. as_bytes( ) ) ;
202
+ assert_eq ! ( [ b'\0' ] , cstring. as_bytes_with_nul( ) ) ;
203
+ }
204
+
205
+ #[ test]
206
+ fn c_str_from_empty_string ( ) {
207
+ let original = b"\0 " ;
208
+ let cstr = CStr :: from_bytes_with_nul ( original) . unwrap ( ) ;
209
+ assert_eq ! ( [ ] as [ u8 ; 0 ] , cstr. to_bytes( ) ) ;
210
+ assert_eq ! ( [ b'\0' ] , cstr. to_bytes_with_nul( ) ) ;
211
+ }
You can’t perform that action at this time.
0 commit comments