1 //! The credit contract of `.f0rge/wiki/docs/protocol.md`.2 3 use inf3r_proto::credit::{Credit, CreditError, credit_limited};4 use inf3r_proto::frame::Kind;5 6 #[test]7 fn a_new_stream_may_send_its_whole_window() {8 let c = Credit::new(1024);9 assert_eq!(c.may_send(), 1024);10 assert_eq!(c.sent(), 0);11 assert_eq!(c.limit(), 1024);12 }13 14 #[test]15 fn taking_bytes_moves_the_send_position() {16 let mut c = Credit::new(1024);17 c.take(24).unwrap();18 assert_eq!(c.sent(), 24);19 assert_eq!(c.may_send(), 1000);20 c.take(1000).unwrap();21 assert_eq!(c.may_send(), 0);22 }23 24 #[test]25 fn an_overdraft_is_refused_and_changes_nothing() {26 let mut c = Credit::new(10);27 c.take(4).unwrap();28 assert_eq!(29 c.take(7).unwrap_err(),30 CreditError::Overdraft { want: 7, have: 6 }31 );32 assert_eq!(c.sent(), 4);33 assert_eq!(c.may_send(), 6);34 }35 36 #[test]37 fn a_window_is_absolute_not_a_delta() {38 let mut c = Credit::new(0);39 c.grant(100).unwrap();40 assert_eq!(c.may_send(), 100);41 c.grant(100).unwrap();42 assert_eq!(c.may_send(), 100, "the same watermark changes nothing");43 c.grant(140).unwrap();44 assert_eq!(c.may_send(), 140);45 }46 47 #[test]48 fn a_watermark_below_the_granted_limit_is_a_protocol_error() {49 let mut c = Credit::new(100);50 c.take(30).unwrap();51 // 29 is below the limit even though it is also below the send position.52 assert_eq!(53 c.grant(29).unwrap_err(),54 CreditError::BelowLimit {55 window: 29,56 limit: 10057 }58 );59 // So is 60: it is above what was sent, but it shrinks the window.60 assert_eq!(61 c.grant(60).unwrap_err(),62 CreditError::BelowLimit {63 window: 60,64 limit: 10065 }66 );67 c.grant(100).unwrap();68 assert_eq!(c.may_send(), 70);69 c.grant(140).unwrap();70 assert_eq!(c.may_send(), 110);71 }72 73 #[test]74 fn credit_saturates_at_the_window_and_never_wraps() {75 let mut c = Credit::new(u64::MAX);76 c.take(u64::MAX).unwrap();77 assert_eq!(c.may_send(), 0);78 assert_eq!(79 c.take(1).unwrap_err(),80 CreditError::Overdraft { want: 1, have: 0 }81 );82 }83 84 #[test]85 fn session_frames_are_not_limited() {86 for kind in Kind::ALL[..10].iter().copied() {87 assert!(!credit_limited(kind, 0), "{kind:?} on stream 0");88 assert!(!credit_limited(kind, 7), "{kind:?} on stream 7");89 }90 }91 92 #[test]93 fn only_events_are_credit_limited() {94 assert!(credit_limited(Kind::Event, 1));95 for kind in [96 Kind::Open,97 Kind::Accept,98 Kind::Cancel,99 Kind::Done,100 Kind::Reject,101 Kind::Fatal,102 Kind::Window,103 ] {104 assert!(!credit_limited(kind, 1), "{kind:?} is control");105 }106 assert!(!credit_limited(Kind::Event, 0), "stream 0 has no events");107 }