@@ -300,6 +300,36 @@ mod tests {
300300 assert_eq ! ( decoded, bytes) ;
301301 }
302302
303+ #[ test]
304+ fn test_decode_corrupted_stream_dead_end ( ) {
305+ // Create a dictionary with three symbols to ensure a deeper tree.
306+ // This makes hitting a dead-end (None pointer) easier.
307+ let freq = vec ! [ ( b'a' , 1 ) , ( b'b' , 1 ) , ( b'c' , 1 ) ] ;
308+ let bytes = b"ab" ;
309+ let dict = HuffmanDictionary :: new ( & freq) . unwrap ( ) ;
310+
311+ let encoded = dict. encode ( bytes) ;
312+
313+ // Manually corrupt the stream to stop mid-symbol.
314+ // We will truncate num_bits by a small amount (e.g., 1 bit).
315+ // This forces the loop to stop on an *intermediate* node.
316+ let corrupted_encoding = HuffmanEncoding {
317+ data : encoded. data ,
318+ // Shorten the bit count by one. The total length of the 'ab' stream
319+ // is likely 4 or 5 bits. This forces the loop to end one bit early,
320+ // leaving the state on an internal node.
321+ num_bits : encoded
322+ . num_bits
323+ . checked_sub ( 1 )
324+ . expect ( "Encoding should be > 0 bits" ) ,
325+ } ;
326+
327+ // Assert that the decode fails gracefully.
328+ // The loop finishes, the final 'if self.num_bits > 0' executes,
329+ // and result.push(state.symbol?) fails because state.symbol is None.
330+ assert_eq ! ( corrupted_encoding. decode( & dict) , None ) ;
331+ }
332+
303333 #[ test]
304334 fn small_text ( ) {
305335 let text = "Hello world" ;
0 commit comments