@@ -222,6 +222,11 @@ impl VarLenAscii {
222222
223223 #[ inline]
224224 pub fn len ( & self ) -> usize {
225+ if self . ptr . is_null ( ) {
226+ return 0 ;
227+ }
228+ // Safety: Pointer null is checked above.
229+ // Could still have issues if string is missing null termination.
225230 unsafe { libc:: strlen ( self . ptr as * const _ ) }
226231 }
227232
@@ -237,6 +242,11 @@ impl VarLenAscii {
237242
238243 #[ inline]
239244 pub fn as_bytes ( & self ) -> & [ u8 ] {
245+ // Treat null as empty. This could be changed to option
246+ // in the future but would be a breaking change.
247+ if self . ptr . is_null ( ) {
248+ return & [ ] ;
249+ }
240250 unsafe { slice:: from_raw_parts ( self . ptr as * const _ , self . len ( ) ) }
241251 }
242252
@@ -330,6 +340,11 @@ impl VarLenUnicode {
330340
331341 #[ inline]
332342 unsafe fn raw_len ( & self ) -> usize {
343+ if self . ptr . is_null ( ) {
344+ return 0 ;
345+ }
346+ // Safety: Pointer null is checked above.
347+ // Could still have issues if string is missing null termination.
333348 libc:: strlen ( self . ptr as * const _ )
334349 }
335350
@@ -350,6 +365,11 @@ impl VarLenUnicode {
350365
351366 #[ inline]
352367 pub fn as_bytes ( & self ) -> & [ u8 ] {
368+ // Treat null as empty. This could be changed to option
369+ // in the future but would be a breaking change.
370+ if self . ptr . is_null ( ) {
371+ return & [ ] ;
372+ }
353373 unsafe { slice:: from_raw_parts ( self . ptr as * const _ , self . raw_len ( ) ) }
354374 }
355375
@@ -761,4 +781,22 @@ pub mod tests {
761781
762782 test_quickcheck_unicode ! ( test_quickcheck_vu, VU ) ;
763783 test_quickcheck_unicode ! ( test_quickcheck_fu, FU ) ;
784+
785+ #[ test]
786+ fn test_null_pointer_var_len_ascii ( ) {
787+ let ascii = VarLenAscii { ptr : ptr:: null_mut ( ) } ;
788+
789+ assert_eq ! ( ascii. len( ) , 0 ) ;
790+ let string = ascii. as_str ( ) ;
791+ assert_eq ! ( string, "" ) ;
792+
793+ }
794+
795+ #[ test]
796+ fn test_null_pointer_var_len_unicode ( ) {
797+ let unicode = VarLenUnicode { ptr : ptr:: null_mut ( ) } ;
798+ assert_eq ! ( unicode. len( ) , 0 ) ;
799+ let string = unicode. as_str ( ) ;
800+ assert_eq ! ( string, "" ) ;
801+ }
764802}
0 commit comments