@@ -162,17 +162,25 @@ impl CString {
162
162
}
163
163
164
164
/// Converts the CString into a `&str` without copying.
165
- /// Returns None if the CString is not UTF-8 or is null.
165
+ /// Returns None if the CString is not UTF-8.
166
+ ///
167
+ /// # Failure
168
+ ///
169
+ /// Fails if the CString is null.
166
170
#[ inline]
167
171
pub fn as_str < ' a > ( & ' a self ) -> Option < & ' a str > {
168
- if self . buf . is_null ( ) { return None ; }
169
172
let buf = self . as_bytes ( ) ;
170
173
let buf = buf. slice_to ( buf. len ( ) -1 ) ; // chop off the trailing NUL
171
174
str:: from_utf8 ( buf)
172
175
}
173
176
174
177
/// Return a CString iterator.
178
+ ///
179
+ /// # Failure
180
+ ///
181
+ /// Fails if the CString is null.
175
182
pub fn iter < ' a > ( & ' a self ) -> CChars < ' a > {
183
+ if self . buf . is_null ( ) { fail ! ( "CString is null!" ) ; }
176
184
CChars {
177
185
ptr : self . buf ,
178
186
marker : marker:: ContravariantLifetime ,
@@ -191,8 +199,14 @@ impl Drop for CString {
191
199
}
192
200
193
201
impl Container for CString {
202
+ /// Return the number of bytes in the CString (not including the NUL terminator).
203
+ ///
204
+ /// # Failure
205
+ ///
206
+ /// Fails if the CString is null.
194
207
#[ inline]
195
208
fn len ( & self ) -> uint {
209
+ if self . buf . is_null ( ) { fail ! ( "CString is null!" ) ; }
196
210
unsafe {
197
211
ptr:: position ( self . buf , |c| * c == 0 )
198
212
}
@@ -562,8 +576,27 @@ mod tests {
562
576
assert_eq ! ( c_str. as_str( ) , Some ( "" ) ) ;
563
577
let c_str = bytes ! ( "foo" , 0xff ) . to_c_str ( ) ;
564
578
assert_eq ! ( c_str. as_str( ) , None ) ;
579
+ }
580
+
581
+ #[ test]
582
+ #[ should_fail]
583
+ fn test_as_str_fail ( ) {
565
584
let c_str = unsafe { CString :: new ( ptr:: null ( ) , false ) } ;
566
- assert_eq ! ( c_str. as_str( ) , None ) ;
585
+ c_str. as_str ( ) ;
586
+ }
587
+
588
+ #[ test]
589
+ #[ should_fail]
590
+ fn test_len_fail ( ) {
591
+ let c_str = unsafe { CString :: new ( ptr:: null ( ) , false ) } ;
592
+ c_str. len ( ) ;
593
+ }
594
+
595
+ #[ test]
596
+ #[ should_fail]
597
+ fn test_iter_fail ( ) {
598
+ let c_str = unsafe { CString :: new ( ptr:: null ( ) , false ) } ;
599
+ c_str. iter ( ) ;
567
600
}
568
601
}
569
602
0 commit comments