@@ -422,6 +422,64 @@ fn test_range_inclusive_folds() {
422422 assert ! ( it. is_empty( ) ) ;
423423 assert_eq ! ( it. try_rfold( 0 , |a, b| Some ( a + b) ) , Some ( 0 ) ) ;
424424 assert ! ( it. is_empty( ) ) ;
425+
426+ // No endless loop.
427+ let mut it = 0u8 ..=u8:: MAX ;
428+ assert_eq ! ( it. try_fold( 0u32 , |a, b| Some ( a + u32 :: from( b) ) ) , Some ( 32640 ) ) ;
429+ assert ! ( it. is_empty( ) ) ;
430+ assert_eq ! ( it. try_fold( 0 , |a, b| Some ( a + b) ) , Some ( 0 ) ) ;
431+ assert ! ( it. is_empty( ) ) ;
432+
433+ // No endless loop.
434+ let mut it = i8:: MIN ..=i8:: MAX ;
435+ assert_eq ! ( it. try_rfold( 0i32 , |a, b| Some ( a + i32 :: from( b) ) ) , Some ( -128 ) ) ;
436+ assert ! ( it. is_empty( ) ) ;
437+ assert_eq ! ( it. try_rfold( 0 , |a, b| Some ( a + b) ) , Some ( 0 ) ) ;
438+ assert ! ( it. is_empty( ) ) ;
439+
440+ // Visit every value exactly once in order.
441+ let mut expected: Option < u8 > = Some ( 0 ) ;
442+ let mut it = 0u8 ..=u8:: MAX ;
443+ it. try_fold ( ( ) , |_, x| {
444+ assert ! ( expected. is_some( ) ) ;
445+ assert_eq ! ( Some ( x) , expected) ;
446+ expected = expected. and_then ( |e| e. checked_add ( 1 ) ) ;
447+ Some ( ( ) )
448+ } ) ;
449+
450+ // Visit every value exactly once in reverse order.
451+ let mut expected: Option < u8 > = Some ( u8:: MAX ) ;
452+ let mut it = 0u8 ..=u8:: MAX ;
453+ it. try_rfold ( ( ) , |_, x| {
454+ assert ! ( expected. is_some( ) ) ;
455+ assert_eq ! ( Some ( x) , expected) ;
456+ expected = expected. and_then ( |e| e. checked_sub ( 1 ) ) ;
457+ Some ( ( ) )
458+ } ) ;
459+
460+ // Early stop updates state correctly.
461+ let mut it = 0 ..=100 ;
462+ it. try_fold ( ( ) , |_, x| ( x < 10 ) . then_some ( ( ) ) ) ;
463+ assert ! ( !it. is_empty( ) ) ;
464+ assert_eq ! ( it. next( ) , Some ( 11 ) ) ;
465+
466+ // Early stop updates state correctly at the end.
467+ let mut it = 0 ..=100 ;
468+ it. try_fold ( ( ) , |_, x| ( x < 100 ) . then_some ( ( ) ) ) ;
469+ assert ! ( it. is_empty( ) ) ;
470+ assert_eq ! ( it. next( ) , None ) ;
471+
472+ // Early stop updates state correctly.
473+ let mut it = 0 ..=100 ;
474+ it. try_rfold ( ( ) , |_, x| ( x > 10 ) . then_some ( ( ) ) ) ;
475+ assert ! ( !it. is_empty( ) ) ;
476+ assert_eq ! ( it. next_back( ) , Some ( 9 ) ) ;
477+
478+ // Early stop updates state correctly at the end.
479+ let mut it = 0 ..=100 ;
480+ it. try_rfold ( ( ) , |_, x| ( x != 0 ) . then_some ( ( ) ) ) ;
481+ assert ! ( it. is_empty( ) ) ;
482+ assert_eq ! ( it. next( ) , None ) ;
425483}
426484
427485#[ test]
0 commit comments