Skip to main content

kcp/
kcp.rs

1//! KCP
2
3use std::cmp;
4use std::cmp::Ordering;
5use std::collections::VecDeque;
6use std::io::{self, Cursor, Read, Write};
7
8use bytes::{Buf, BufMut, BytesMut};
9use crate::{KcpResult, error::Error};
10
11#[cfg(feature = "byte-check")]
12use std::convert::TryInto;
13
14#[cfg(feature = "tokio")]
15use tokio::io::{AsyncWrite, AsyncWriteExt};
16#[cfg(feature = "tokio")]
17use std::{pin::Pin, task::{Context, Poll}};
18
19//const KCP_RTO_NDL: u32 = 30;
20const KCP_RTO_NDL: u32 = 20;
21const KCP_RTO_MIN: u32 = 100;
22const KCP_RTO_DEF: u32 = 200;
23const KCP_RTO_MAX: u32 = 60000;
24
25const KCP_CMD_PUSH: u8 = 81;
26const KCP_CMD_ACK: u8 = 82;
27const KCP_CMD_WASK: u8 = 83;
28const KCP_CMD_WINS: u8 = 84;
29
30const KCP_ASK_SEND: u32 = 1;
31const KCP_ASK_TELL: u32 = 2;
32
33const KCP_WND_SND: u16 = 32;
34//const KCP_WND_RCV: u16 = 128;
35const KCP_WND_RCV: u16 = 256;
36
37pub const KCP_MTU_DEF: usize = 1400;
38// const KCP_ACK_FAST: u32 = 3;
39
40const KCP_INTERVAL: u32 = 100;
41//pub const KCP_OVERHEAD: usize = 24;
42//pub const KCP_OVERHEAD: usize = 28;
43
44#[cfg(feature = "byte-check")]
45pub const DEFAULT_KCP_OVERHEAD: usize = 28;
46#[cfg(feature = "byte-check")]
47pub const MAX_KCP_OVERHEAD: usize = 32;
48
49#[cfg(not(feature = "byte-check"))]
50pub const KCP_OVERHEAD: usize = 28;
51
52const KCP_DEADLINK: u32 = 20;
53
54const KCP_THRESH_INIT: u16 = 2;
55const KCP_THRESH_MIN: u16 = 2;
56
57const KCP_PROBE_INIT: u32 = 7000;
58const KCP_PROBE_LIMIT: u32 = 120000;
59
60/// Read `conv` from raw buffer
61pub fn get_conv(buf: &[u8]) -> u32 {
62    #[cfg(feature = "byte-check")]
63    {
64        assert!(buf.len() >= DEFAULT_KCP_OVERHEAD);
65    }
66
67    u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]])
68}
69
70/// Read `token` from raw buffer
71pub fn get_token(buf: &[u8]) -> u32 {
72    #[cfg(feature = "byte-check")]
73    {
74        assert!(buf.len() >= DEFAULT_KCP_OVERHEAD);
75    }
76
77    u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]])
78}
79
80#[inline]
81#[cfg(feature = "byte-check")]
82pub fn compute_hash(data: &[u8]) -> u32 {
83    let hash = xxhash_rust::xxh3::xxh3_64(data);
84    match (hash & 0xFFFFFFFF).try_into() {
85        Ok(v) => v,
86        Err(_) => unreachable!(),
87    }
88}
89
90#[inline]
91fn bound(lower: u32, v: u32, upper: u32) -> u32 {
92    cmp::min(cmp::max(lower, v), upper)
93}
94
95#[inline]
96fn timediff(later: u32, earlier: u32) -> i32 {
97    later as i32 - earlier as i32
98}
99
100#[derive(Default, Clone, Debug)]
101struct KcpSegment {
102    #[cfg(feature = "byte-check")]
103    overhead: usize,
104
105    conv: u32,
106    token: u32,
107    cmd: u8,
108    frg: u8,
109    wnd: u16,
110    ts: u32,
111    sn: u32,
112    una: u32,
113    resendts: u32,
114    rto: u32,
115    fastack: u32,
116    xmit: u32,
117    
118    #[cfg(feature = "byte-check")]
119    byte_check_code: u32,
120    
121    data: BytesMut,
122}
123
124impl KcpSegment {
125    #[cfg(not(feature = "byte-check"))]
126    fn new_with_data(data: BytesMut) -> Self {
127        KcpSegment {
128            conv: 0,
129            token: 0,
130            cmd: 0,
131            frg: 0,
132            wnd: 0,
133            ts: 0,
134            sn: 0,
135            una: 0,
136            resendts: 0,
137            rto: 0,
138            fastack: 0,
139            xmit: 0,
140            
141            #[cfg(feature = "byte-check")]
142            byte_check_code: 0,
143            
144            data,
145        }
146    }
147
148    #[cfg(feature = "byte-check")]
149    fn new_with_data(data: BytesMut, overhead: usize) -> Self {
150        KcpSegment {
151            overhead,
152
153            conv: 0,
154            token: 0,
155            cmd: 0,
156            frg: 0,
157            wnd: 0,
158            ts: 0,
159            sn: 0,
160            una: 0,
161            resendts: 0,
162            rto: 0,
163            fastack: 0,
164            xmit: 0,
165
166            #[cfg(feature = "byte-check")]
167            byte_check_code: 0,
168
169            data,
170        }
171    }
172
173    fn encode(&self, buf: &mut BytesMut) {
174        let overhead = {
175            #[cfg(feature = "byte-check")]
176            {
177                self.overhead
178            }
179
180            #[cfg(not(feature = "byte-check"))]
181            {
182                KCP_OVERHEAD
183            }
184        };
185
186        if buf.remaining_mut() < overhead {
187            panic!(
188                "REMAIN {} encoded {} {:?}",
189                buf.remaining_mut(),
190                overhead,
191                self
192            );
193        }
194
195        buf.put_u32_le(self.conv);
196        buf.put_u32_le(self.token);
197        buf.put_u8(self.cmd);
198        buf.put_u8(self.frg);
199        buf.put_u16_le(self.wnd);
200        buf.put_u32_le(self.ts);
201        buf.put_u32_le(self.sn);
202        buf.put_u32_le(self.una);
203        buf.put_u32_le(self.data.len() as u32);
204        // BEG PATCH: miHoYo proprietary
205        #[cfg(feature = "byte-check")]
206        if self.overhead > DEFAULT_KCP_OVERHEAD {
207            buf.put_u32_le(self.byte_check_code);
208        }
209        // END PATCH: miHoYo proprietary
210        buf.put_slice(&self.data);
211    }
212
213    #[allow(dead_code)]
214    #[cfg(not(feature = "byte-check"))]
215    fn encoded_len(&self) -> usize {
216        KCP_OVERHEAD + self.data.len()
217    }
218
219    #[allow(dead_code)]
220    #[cfg(feature = "byte-check")]
221    fn encoded_len(&self) -> usize {
222        self.overhead + self.data.len()
223    }
224}
225
226#[derive(Default)]
227pub struct KcpOutput<O>(pub O);
228
229impl<O: Write> Write for KcpOutput<O> {
230    #[inline]
231    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
232        trace!("[RO] {} bytes", data.len());
233        self.0.write(data)
234    }
235
236    #[inline]
237    fn flush(&mut self) -> io::Result<()> {
238        self.0.flush()
239    }
240}
241
242#[cfg(feature = "tokio")]
243impl<O: AsyncWrite + Unpin> AsyncWrite for KcpOutput<O> {
244    fn poll_write(
245        mut self: Pin<&mut Self>,
246        cx: &mut Context<'_>,
247        buf: &[u8],
248    ) -> Poll<Result<usize, io::Error>> {
249        Pin::new(&mut self.0).poll_write(cx, buf)
250    }
251
252    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
253        Pin::new(&mut self.0).poll_flush(cx)
254    }
255
256    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
257        Pin::new(&mut self.0).poll_shutdown(cx)
258    }
259
260    fn poll_write_vectored(
261        mut self: Pin<&mut Self>,
262        cx: &mut Context<'_>,
263        bufs: &[io::IoSlice<'_>],
264    ) -> Poll<Result<usize, io::Error>> {
265        Pin::new(&mut self.0).poll_write_vectored(cx, bufs)
266    }
267
268    fn is_write_vectored(&self) -> bool {
269        self.0.is_write_vectored()
270    }
271}
272
273/// KCP control
274#[derive(Default)]
275pub struct Kcp<Output> {
276    #[cfg(feature = "byte-check")]
277    overhead: usize,
278
279    /// Conversation ID
280    conv: u32,
281    /// Maximun Transmission Unit
282    mtu: usize,
283    /// Maximum Segment Size
284    mss: u32,
285    /// Connection state
286    state: i32,
287
288    /// User token
289    token: u32,
290
291    /// First unacknowledged packet
292    snd_una: u32,
293    /// Next packet
294    snd_nxt: u32,
295    /// Next packet to be received
296    rcv_nxt: u32,
297
298    /// Congetion window threshole
299    ssthresh: u16,
300
301    /// ACK receive variable RTT
302    rx_rttval: u32,
303    /// ACK receive static RTT
304    rx_srtt: u32,
305    /// Resend time (calculated by ACK delay time)
306    rx_rto: u32,
307    /// Minimal resend timeout
308    rx_minrto: u32,
309
310    /// Send window
311    snd_wnd: u16,
312    /// Receive window
313    rcv_wnd: u16,
314    /// Remote receive window
315    rmt_wnd: u16,
316    /// Congetion window
317    cwnd: u16,
318    /// Check window
319    /// - IKCP_ASK_TELL, telling window size to remote
320    /// - IKCP_ASK_SEND, ask remote for window size
321    probe: u32,
322
323    /// Last update time
324    current: u32,
325    /// Flush interval
326    interval: u32,
327    /// Next flush interval
328    ts_flush: u32,
329    xmit: u32,
330
331    /// Enable nodelay
332    nodelay: bool,
333    /// Updated has been called or not
334    updated: bool,
335
336    /// Next check window timestamp
337    ts_probe: u32,
338    /// Check window wait time
339    probe_wait: u32,
340
341    /// Maximum resend time
342    dead_link: u32,
343    /// Maximum payload size
344    incr: u32,
345
346    snd_queue: VecDeque<KcpSegment>,
347    rcv_queue: VecDeque<KcpSegment>,
348    snd_buf: VecDeque<KcpSegment>,
349    rcv_buf: VecDeque<KcpSegment>,
350
351    /// Pending ACK
352    acklist: VecDeque<(u32, u32)>,
353    buf: BytesMut,
354
355    /// ACK number to trigger fast resend
356    fastresend: u32,
357    /// Disable congetion control
358    nocwnd: bool,
359    /// Enable stream mode
360    stream: bool,
361
362    /// Get conv from the next input call
363    input_conv: bool,
364
365    pub output: KcpOutput<Output>,
366}
367
368impl<Output> Kcp<Output> {
369    /// Creates a KCP control object, `conv` must be equal in both endpoints in one connection.
370    /// `output` is the callback object for writing.
371    ///
372    /// `conv` represents conversation.
373    pub fn new(conv: u32, token: u32, output: Output) -> Self {
374        Kcp::construct(conv, token, output, false)
375    }
376
377    /// Creates a KCP control object in stream mode, `conv` must be equal in both endpoints in one connection.
378    /// `output` is the callback object for writing.
379    ///
380    /// `conv` represents conversation.
381    pub fn new_stream(conv: u32, token: u32, output: Output) -> Self {
382        Kcp::construct(conv, token, output, true)
383    }
384
385    #[cfg(not(feature = "byte-check"))]
386    fn construct(conv: u32, token: u32, output: Output, stream: bool) -> Self {
387        Kcp {
388            conv,
389            snd_una: 0,
390            snd_nxt: 0,
391            rcv_nxt: 0,
392            token,
393            rx_rttval: 0,
394            rx_srtt: 0,
395            state: 0,
396            cwnd: 0,
397            probe: 0,
398            current: 0,
399            xmit: 0,
400            nodelay: false,
401            updated: false,
402            ts_probe: 0,
403            probe_wait: 0,
404            dead_link: KCP_DEADLINK,
405            incr: 0,
406            fastresend: 0,
407            nocwnd: false,
408            stream,
409            snd_wnd: KCP_WND_SND,
410            rcv_wnd: KCP_WND_RCV,
411            rmt_wnd: KCP_WND_RCV,
412            mtu: KCP_MTU_DEF,
413            mss: (KCP_MTU_DEF - KCP_OVERHEAD) as u32,
414            buf: BytesMut::with_capacity((KCP_MTU_DEF + KCP_OVERHEAD) * 3),
415            snd_queue: VecDeque::new(),
416            rcv_queue: VecDeque::new(),
417            snd_buf: VecDeque::new(),
418            rcv_buf: VecDeque::new(),
419            acklist: VecDeque::new(),
420            rx_rto: KCP_RTO_DEF,
421            rx_minrto: KCP_RTO_MIN,
422            interval: KCP_INTERVAL,
423            ts_flush: KCP_INTERVAL,
424            ssthresh: KCP_THRESH_INIT,
425            input_conv: false,
426            output: KcpOutput(output),
427        }
428    }
429
430    #[cfg(feature = "byte-check")]
431    fn construct(conv: u32, token: u32, output: Output, stream: bool) -> Self {
432        Kcp {
433            overhead: DEFAULT_KCP_OVERHEAD,
434            conv,
435            snd_una: 0,
436            snd_nxt: 0,
437            rcv_nxt: 0,
438            token,
439            rx_rttval: 0,
440            rx_srtt: 0,
441            state: 0,
442            cwnd: 0,
443            probe: 0,
444            current: 0,
445            xmit: 0,
446            nodelay: false,
447            updated: false,
448            ts_probe: 0,
449            probe_wait: 0,
450            dead_link: KCP_DEADLINK,
451            incr: 0,
452            fastresend: 0,
453            nocwnd: false,
454            stream,
455            snd_wnd: KCP_WND_SND,
456            rcv_wnd: KCP_WND_RCV,
457            rmt_wnd: KCP_WND_RCV,
458            mtu: KCP_MTU_DEF,
459            mss: (KCP_MTU_DEF - DEFAULT_KCP_OVERHEAD) as u32,
460            buf: BytesMut::with_capacity((KCP_MTU_DEF + MAX_KCP_OVERHEAD) * 3),
461            snd_queue: VecDeque::new(),
462            rcv_queue: VecDeque::new(),
463            snd_buf: VecDeque::new(),
464            rcv_buf: VecDeque::new(),
465            acklist: VecDeque::new(),
466            rx_rto: KCP_RTO_DEF,
467            rx_minrto: KCP_RTO_MIN,
468            interval: KCP_INTERVAL,
469            ts_flush: KCP_INTERVAL,
470            ssthresh: KCP_THRESH_INIT,
471            input_conv: false,
472            output: KcpOutput(output),
473        }
474    }
475
476    /// Check buffer size without actually consuming it
477    pub fn peeksize(&self) -> KcpResult<usize> {
478        match self.rcv_queue.front() {
479            Some(segment) => {
480                if segment.frg == 0 {
481                    return Ok(segment.data.len());
482                }
483
484                if self.rcv_queue.len() < (segment.frg + 1) as usize {
485                    return Err(Error::ExpectingFragment);
486                }
487
488                let mut len = 0;
489
490                for segment in &self.rcv_queue {
491                    len += segment.data.len();
492                    if segment.frg == 0 {
493                        break;
494                    }
495                }
496
497                Ok(len)
498            }
499            None => Err(Error::RecvQueueEmpty),
500        }
501    }
502
503    // move available data from rcv_buf -> rcv_queue
504    pub fn move_buf(&mut self) {
505        while !self.rcv_buf.is_empty() {
506            let nrcv_que = self.rcv_queue.len();
507            {
508                let seg = &self.rcv_buf[0];
509                if seg.sn == self.rcv_nxt && nrcv_que < self.rcv_wnd as usize {
510                    self.rcv_nxt += 1;
511                } else {
512                    break;
513                }
514            }
515
516            let seg = self.rcv_buf.pop_front().unwrap();
517            self.rcv_queue.push_back(seg);
518        }
519    }
520
521    /// Receive data from buffer
522    pub fn recv(&mut self, buf: &mut [u8]) -> KcpResult<usize> {
523        if self.rcv_queue.is_empty() {
524            return Err(Error::RecvQueueEmpty);
525        }
526
527        let peeksize = self.peeksize()?;
528
529        if peeksize > buf.len() {
530            debug!("recv peeksize={} bufsize={} too small", peeksize, buf.len());
531            return Err(Error::UserBufTooSmall);
532        }
533
534        let recover = self.rcv_queue.len() >= self.rcv_wnd as usize;
535
536        // Merge fragment
537        let mut cur = Cursor::new(buf);
538        while let Some(seg) = self.rcv_queue.pop_front() {
539            Write::write_all(&mut cur, &seg.data)?;
540
541            trace!("recv sn={}", seg.sn);
542
543            if seg.frg == 0 {
544                break;
545            }
546        }
547        assert_eq!(cur.position() as usize, peeksize);
548
549        self.move_buf();
550
551        // fast recover
552        if self.rcv_queue.len() < self.rcv_wnd as usize && recover {
553            // ready to send back IKCP_CMD_WINS in ikcp_flush
554            // tell remote my window size
555            self.probe |= KCP_ASK_TELL;
556        }
557
558        Ok(cur.position() as usize)
559    }
560
561    /// Send bytes into buffer
562    pub fn send(&mut self, mut buf: &[u8]) -> KcpResult<usize> {
563        let mut sent_size = 0;
564
565        assert!(self.mss > 0);
566
567        // append to previous segment in streaming mode (if possible)
568        if self.stream {
569            if let Some(old) = self.snd_queue.back_mut() {
570                let l = old.data.len();
571                if l < self.mss as usize {
572                    let capacity = self.mss as usize - l;
573                    let extend = cmp::min(buf.len(), capacity);
574
575                    trace!(
576                        "send stream mss={} last length={} extend={}",
577                        self.mss,
578                        l,
579                        extend
580                    );
581
582                    let (lf, rt) = buf.split_at(extend);
583                    old.data.extend_from_slice(lf);
584                    buf = rt;
585
586                    old.frg = 0;
587                    sent_size += extend;
588                }
589
590                if buf.is_empty() {
591                    return Ok(sent_size);
592                }
593            }
594        }
595
596        let count = if buf.len() <= self.mss as usize {
597            1
598        } else {
599            (buf.len() + self.mss as usize - 1) / self.mss as usize
600        };
601
602        if count >= KCP_WND_RCV as usize {
603            debug!("send bufsize={} mss={} too large", buf.len(), self.mss);
604            return Err(Error::UserBufTooBig);
605        }
606        assert!(count > 0);
607
608        // let count = cmp::max(1, count);
609
610        for i in 0..count {
611            let size = cmp::min(self.mss as usize, buf.len());
612
613            let (lf, rt) = buf.split_at(size);
614
615            let mut new_segment = {
616                #[cfg(feature = "byte-check")]
617                {
618                    KcpSegment::new_with_data(BytesMut::with_capacity(size), self.overhead)
619                }
620
621                #[cfg(not(feature = "byte-check"))]
622                {
623                    KcpSegment::new_with_data(BytesMut::with_capacity(size))
624                }
625            };
626            new_segment.data.extend_from_slice(lf);
627            buf = rt;
628
629            new_segment.frg = if self.stream {
630                0
631            } else {
632                (count - i - 1) as u8
633            };
634
635            self.snd_queue.push_back(new_segment);
636            sent_size += size;
637        }
638
639        Ok(sent_size)
640    }
641
642    fn update_ack(&mut self, rtt: u32) {
643        if self.rx_srtt == 0 {
644            self.rx_srtt = rtt;
645            self.rx_rttval = rtt / 2;
646        } else {
647            let delta = if rtt > self.rx_srtt {
648                rtt - self.rx_srtt
649            } else {
650                self.rx_srtt - rtt
651            };
652            self.rx_rttval = (3 * self.rx_rttval + delta) / 4;
653            self.rx_srtt = ((7 * (self.rx_srtt as u64) + (rtt as u64)) / 8) as u32;
654            if self.rx_srtt < 1 {
655                self.rx_srtt = 1;
656            }
657        }
658        let rto = self.rx_srtt + cmp::max(self.interval, 4 * self.rx_rttval);
659        self.rx_rto = bound(self.rx_minrto, rto, KCP_RTO_MAX);
660    }
661
662    #[inline]
663    fn shrink_buf(&mut self) {
664        self.snd_una = match self.snd_buf.front() {
665            Some(seg) => seg.sn,
666            None => self.snd_nxt,
667        };
668    }
669
670    fn parse_ack(&mut self, sn: u32) {
671        if timediff(sn, self.snd_una) < 0 || timediff(sn, self.snd_nxt) >= 0 {
672            return;
673        }
674
675        for i in (0..self.snd_buf.len()).rev() {
676            match sn.cmp(&self.snd_buf[i].sn) {
677                Ordering::Equal => {
678                    self.snd_buf.remove(i);
679                }
680                Ordering::Less => break,
681                _ => (),
682            }
683        }
684    }
685
686    fn parse_una(&mut self, una: u32) {
687        while !self.snd_buf.is_empty() {
688            if timediff(una, self.snd_buf[0].sn) > 0 {
689                // self.snd_buf.remove(0);
690                self.snd_buf.pop_front();
691            } else {
692                break;
693            }
694        }
695    }
696
697    fn parse_fastack(&mut self, sn: u32) {
698        if timediff(sn, self.snd_una) < 0 || timediff(sn, self.snd_nxt) >= 0 {
699            return;
700        }
701
702        for seg in &mut self.snd_buf {
703            if timediff(sn, seg.sn) < 0 {
704                break;
705            } else if sn != seg.sn {
706                seg.fastack += 1;
707            }
708        }
709    }
710
711    #[inline]
712    fn ack_push(&mut self, sn: u32, ts: u32) {
713        self.acklist.push_back((sn, ts));
714    }
715
716    fn parse_data(&mut self, new_segment: KcpSegment) {
717        let sn = new_segment.sn;
718
719        if timediff(sn, self.rcv_nxt + self.rcv_wnd as u32) >= 0 || timediff(sn, self.rcv_nxt) < 0 {
720            return;
721        }
722
723        let mut repeat = false;
724        let mut new_index = self.rcv_buf.len();
725
726        for segment in self.rcv_buf.iter().rev() {
727            if segment.sn == sn {
728                repeat = true;
729                break;
730            } else if timediff(sn, segment.sn) > 0 {
731                break;
732            }
733            new_index -= 1;
734        }
735
736        if !repeat {
737            self.rcv_buf.insert(new_index, new_segment);
738        }
739
740        // move available data from rcv_buf -> rcv_queue
741        self.move_buf();
742    }
743
744    /// Get `conv` from the next `input` call
745    #[inline]
746    pub fn input_conv(&mut self) {
747        self.input_conv = true;
748    }
749
750    /// Check if Kcp is waiting for the next input
751    #[inline]
752    pub fn waiting_conv(&self) -> bool {
753        self.input_conv
754    }
755
756    /// Set `conv` value
757    #[inline]
758    pub fn set_conv(&mut self, conv: u32) {
759        self.conv = conv;
760    }
761
762    /// Get `conv`
763    #[inline]
764    pub fn conv(&self) -> u32 {
765        self.conv
766    }
767
768    /// Set `token` value
769    #[inline]
770    pub fn set_token(&mut self, token: u32) {
771        self.token = token;
772    }
773
774    /// Get `token`
775    #[inline]
776    pub fn token(&self) -> u32 {
777        self.token
778    }
779
780    /// Call this when you received a packet from raw connection
781    pub fn input(&mut self, buf: &[u8]) -> KcpResult<usize> {
782        let input_size = buf.len();
783
784        trace!("[RI] {} bytes", buf.len());
785
786        if buf.len() < self.header_len() {
787            debug!(
788                "input bufsize={} too small, at least {}",
789                buf.len(),
790                self.header_len()
791            );
792            return Err(Error::InvalidSegmentSize(buf.len()));
793        }
794
795        let mut flag = false;
796        let mut max_ack = 0;
797        let old_una = self.snd_una;
798
799        let mut buf = Cursor::new(buf);
800        while buf.remaining() >= self.header_len() as usize {
801            let conv = buf.get_u32_le();
802            if conv != self.conv {
803                // This allows getting conv from this call, which allows us to allocate
804                // conv from the server side.
805                if self.input_conv {
806                    debug!("input conv={} updated, original conv={}", conv, self.conv);
807                    self.conv = conv;
808                    self.input_conv = false;
809                } else {
810                    debug!("input conv={} expected conv={} not match", conv, self.conv);
811                    return Err(Error::ConvInconsistent(self.conv, conv));
812                }
813            }
814
815            let token = buf.get_u32_le();
816
817            let cmd = buf.get_u8();
818            let frg = buf.get_u8();
819            let wnd = buf.get_u16_le();
820            let ts = buf.get_u32_le();
821            let sn = buf.get_u32_le();
822            let una = buf.get_u32_le();
823            let len = buf.get_u32_le() as usize;
824
825            #[cfg(feature = "byte-check")]
826            let byte_check_code = if self.overhead > DEFAULT_KCP_OVERHEAD {
827                buf.get_u32_le()
828            } else {
829                0
830            };
831
832            if buf.remaining() < len as usize {
833                debug!(
834                    "input bufsize={} payload length={} remaining={} not match",
835                    input_size,
836                    len,
837                    buf.remaining()
838                );
839                return Err(Error::InvalidSegmentDataSize(len, buf.remaining()));
840            }
841
842            match cmd {
843                KCP_CMD_PUSH | KCP_CMD_ACK | KCP_CMD_WASK | KCP_CMD_WINS => {}
844                _ => {
845                    debug!("input cmd={} unrecognized", cmd);
846                    return Err(Error::UnsupportedCmd(cmd));
847                }
848            }
849
850            if token != self.token {
851                return Err(Error::TokenMismatch(token, self.token));
852            }
853
854            self.rmt_wnd = wnd;
855
856            self.parse_una(una);
857            self.shrink_buf();
858
859            let mut has_read_data = false;
860
861            match cmd {
862                KCP_CMD_ACK => {
863                    let rtt = timediff(self.current, ts);
864                    if rtt >= 0 {
865                        self.update_ack(rtt as u32);
866                    }
867                    self.parse_ack(sn);
868                    self.shrink_buf();
869
870                    if !flag {
871                        max_ack = sn;
872                        flag = true;
873                    } else if timediff(sn, max_ack) > 0 {
874                        max_ack = sn;
875                    }
876
877                    trace!(
878                        "input ack: sn={} rtt={} rto={}",
879                        sn,
880                        timediff(self.current, ts),
881                        self.rx_rto
882                    );
883                }
884                KCP_CMD_PUSH => {
885                    trace!("input psh: sn={} ts={}", sn, ts);
886
887                    if timediff(sn, self.rcv_nxt + self.rcv_wnd as u32) < 0 {
888                        self.ack_push(sn, ts);
889                        if timediff(sn, self.rcv_nxt) >= 0 {
890                            let mut sbuf = BytesMut::with_capacity(len as usize);
891                            unsafe {
892                                sbuf.set_len(len as usize);
893                            }
894                            buf.read_exact(&mut sbuf).unwrap();
895                            has_read_data = true;
896
897                            let mut segment = {
898                                #[cfg(feature = "byte-check")]
899                                {
900                                    KcpSegment::new_with_data(sbuf, self.overhead)
901                                }
902
903                                #[cfg(not(feature = "byte-check"))]
904                                {
905                                    KcpSegment::new_with_data(sbuf)
906                                }
907                            };
908
909                            segment.conv = conv;
910                            segment.token = token;
911                            segment.cmd = cmd;
912                            segment.frg = frg;
913                            segment.wnd = wnd;
914                            segment.ts = ts;
915                            segment.sn = sn;
916                            segment.una = una;
917
918                            #[cfg(feature = "byte-check")]
919                            {
920                                segment.byte_check_code = byte_check_code;
921                            }
922
923                            self.parse_data(segment);
924                        }
925                    }
926                }
927                KCP_CMD_WASK => {
928                    trace!("input probe");
929                    self.probe |= KCP_ASK_TELL;
930                }
931                KCP_CMD_WINS => {
932                    // Do nothing
933                    trace!("input wins: {}", wnd);
934                }
935                _ => unreachable!(),
936            }
937
938            // Force skip unread data
939            if !has_read_data {
940                let next_pos = buf.position() + len as u64;
941                buf.set_position(next_pos);
942            }
943        }
944
945        if flag {
946            self.parse_fastack(max_ack);
947        }
948
949        if self.snd_una > old_una && self.cwnd < self.rmt_wnd {
950            let mss = self.mss;
951            if self.cwnd < self.ssthresh {
952                self.cwnd += 1;
953                self.incr += mss;
954            } else {
955                if self.incr < mss {
956                    self.incr = mss;
957                }
958                self.incr += (mss * mss) / self.incr + (mss / 16);
959                if (self.cwnd + 1) as u32 * mss <= self.incr {
960                    self.cwnd += 1;
961                }
962            }
963            if self.cwnd > self.rmt_wnd {
964                self.cwnd = self.rmt_wnd;
965                self.incr = self.rmt_wnd as u32 * mss;
966            }
967        }
968
969        Ok(buf.position() as usize)
970    }
971
972    fn wnd_unused(&self) -> u16 {
973        if self.rcv_queue.len() < self.rcv_wnd as usize {
974            self.rcv_wnd - self.rcv_queue.len() as u16
975        } else {
976            0
977        }
978    }
979
980    fn probe_wnd_size(&mut self) {
981        // probe window size (if remote window size equals zero)
982        if self.rmt_wnd == 0 {
983            if self.probe_wait == 0 {
984                self.probe_wait = KCP_PROBE_INIT;
985                self.ts_probe = self.current + self.probe_wait;
986            } else {
987                if timediff(self.current, self.ts_probe) >= 0 && self.probe_wait < KCP_PROBE_INIT {
988                    self.probe_wait = KCP_PROBE_INIT;
989                }
990                self.probe_wait += self.probe_wait / 2;
991                if self.probe_wait > KCP_PROBE_LIMIT {
992                    self.probe_wait = KCP_PROBE_LIMIT;
993                }
994                self.ts_probe = self.current + self.probe_wait;
995                self.probe |= KCP_ASK_SEND;
996            }
997        } else {
998            self.ts_probe = 0;
999            self.probe_wait = 0;
1000        }
1001    }
1002
1003    /// Determine when you should call `update`.
1004    /// Return when you should invoke `update` in millisec, if there is no `input`/`send` calling.
1005    /// You can call `update` in that time without calling it repeatly.
1006    pub fn check(&self, current: u32) -> u32 {
1007        if !self.updated {
1008            return 0;
1009        }
1010
1011        let mut ts_flush = self.ts_flush;
1012        let mut tm_packet = u32::max_value();
1013
1014        if timediff(current, ts_flush) >= 10000 || timediff(current, ts_flush) < -10000 {
1015            ts_flush = current;
1016        }
1017
1018        if timediff(current, ts_flush) >= 0 {
1019            // return self.interval;
1020            return 0;
1021        }
1022
1023        let tm_flush = timediff(ts_flush, current) as u32;
1024        for seg in &self.snd_buf {
1025            let diff = timediff(seg.resendts, current);
1026            if diff <= 0 {
1027                // return self.interval;
1028                return 0;
1029            }
1030            if (diff as u32) < tm_packet {
1031                tm_packet = diff as u32;
1032            }
1033        }
1034
1035        cmp::min(cmp::min(tm_packet, tm_flush), self.interval)
1036    }
1037
1038    /// Change MTU size, default is 1400
1039    ///
1040    /// MTU = Maximum Transmission Unit
1041    pub fn set_mtu(&mut self, mtu: usize) -> KcpResult<()> {
1042        if mtu < 50 || mtu < self.header_len() {
1043            debug!("set_mtu mtu={} invalid", mtu);
1044            return Err(Error::InvalidMtu(mtu));
1045        }
1046
1047        self.mtu = mtu;
1048        self.mss = (self.mtu - self.header_len()) as u32;
1049
1050        let additional = ((mtu + self.header_len()) * 3) as isize - self.buf.capacity() as isize;
1051        if additional > 0 {
1052            self.buf.reserve(additional as usize);
1053        }
1054
1055        Ok(())
1056    }
1057
1058    /// Get MTU
1059    pub fn mtu(&self) -> usize {
1060        self.mtu
1061    }
1062
1063    /// Set check interval
1064    pub fn set_interval(&mut self, mut interval: u32) {
1065        if interval > 5000 {
1066            interval = 5000;
1067        } else if interval < 10 {
1068            interval = 10;
1069        }
1070        self.interval = interval;
1071    }
1072
1073    /// Set nodelay
1074    ///
1075    /// fastest config: nodelay(true, 20, 2, true)
1076    ///
1077    /// `nodelay`: default is disable (false)
1078    /// `interval`: internal update timer interval in millisec, default is 100ms
1079    /// `resend`: 0:disable fast resend(default), 1:enable fast resend
1080    /// `nc`: `false`: normal congestion control(default), `true`: disable congestion control
1081    pub fn set_nodelay(&mut self, nodelay: bool, interval: i32, resend: i32, nc: bool) {
1082        if nodelay {
1083            self.nodelay = true;
1084            self.rx_minrto = KCP_RTO_NDL;
1085        } else {
1086            self.nodelay = false;
1087            self.rx_minrto = KCP_RTO_MIN;
1088        }
1089
1090        match interval {
1091            interval if interval < 10 => self.interval = 10,
1092            interval if interval > 5000 => self.interval = 5000,
1093            _ => self.interval = interval as u32,
1094        }
1095
1096        if resend >= 0 {
1097            self.fastresend = resend as u32;
1098        }
1099
1100        self.nocwnd = nc;
1101    }
1102
1103    /// Set `wndsize`
1104    /// set maximum window size: `sndwnd=32`, `rcvwnd=32` by default
1105    pub fn set_wndsize(&mut self, sndwnd: u16, rcvwnd: u16) {
1106        if sndwnd > 0 {
1107            self.snd_wnd = sndwnd as u16;
1108        }
1109
1110        if rcvwnd > 0 {
1111            self.rcv_wnd = cmp::max(rcvwnd, KCP_WND_RCV) as u16;
1112        }
1113    }
1114
1115    /// `snd_wnd` Send window
1116    pub fn snd_wnd(&self) -> u16 {
1117        self.snd_wnd
1118    }
1119
1120    /// `rcv_wnd` Receive window
1121    pub fn rcv_wnd(&self) -> u16 {
1122        self.rcv_wnd
1123    }
1124
1125    /// Get `waitsnd`, how many packet is waiting to be sent
1126    pub fn wait_snd(&self) -> usize {
1127        self.snd_buf.len() + self.snd_queue.len()
1128    }
1129
1130    /// Set `rx_minrto`
1131    pub fn set_rx_minrto(&mut self, rto: u32) {
1132        self.rx_minrto = rto;
1133    }
1134
1135    /// Set `fastresend`
1136    pub fn set_fast_resend(&mut self, fr: u32) {
1137        self.fastresend = fr;
1138    }
1139
1140    /// KCP header size
1141    #[cfg(not(feature = "byte-check"))]
1142    pub fn header_len(&self) -> usize {
1143        KCP_OVERHEAD as usize
1144    }
1145
1146    /// KCP header size
1147    #[cfg(feature = "byte-check")]
1148    pub fn header_len(&self) -> usize {
1149        self.overhead
1150    }
1151
1152    /// Sets the KCP instance's overhead/header length.
1153    #[cfg(feature = "byte-check")]
1154    pub fn set_header_len(&mut self, overhead: usize) {
1155        self.overhead = overhead;
1156
1157        // Update the maximum segment size which is dependent on the overhead
1158        self.mss = (KCP_MTU_DEF - overhead) as u32;
1159    }
1160
1161    /// Enabled stream or not
1162    pub fn is_stream(&self) -> bool {
1163        self.stream
1164    }
1165
1166    /// Maximum Segment Size
1167    pub fn mss(&self) -> u32 {
1168        self.mss
1169    }
1170
1171    /// Set maximum resend times
1172    pub fn set_maximum_resend_times(&mut self, dead_link: u32) {
1173        self.dead_link = dead_link;
1174    }
1175
1176    /// Check if KCP connection is dead (resend times excceeded)
1177    pub fn is_dead_link(&self) -> bool {
1178        self.state != 0
1179    }
1180}
1181
1182impl<Output: Write> Kcp<Output> {
1183    fn _flush_ack(&mut self, segment: &mut KcpSegment) -> KcpResult<()> {
1184        // flush acknowledges
1185        // while let Some((sn, ts)) = self.acklist.pop_front() {
1186        for &(sn, ts) in &self.acklist {
1187            if self.buf.len() + self.header_len() > self.mtu as usize {
1188                self.output.write_all(&self.buf)?;
1189                self.buf.clear();
1190            }
1191            segment.sn = sn;
1192            segment.ts = ts;
1193            segment.encode(&mut self.buf);
1194        }
1195        self.acklist.clear();
1196
1197        Ok(())
1198    }
1199
1200    fn _flush_probe_commands(&mut self, cmd: u8, segment: &mut KcpSegment) -> KcpResult<()> {
1201        segment.cmd = cmd;
1202        if self.buf.len() + self.header_len() > self.mtu as usize {
1203            self.output.write_all(&self.buf)?;
1204            self.buf.clear();
1205        }
1206        segment.encode(&mut self.buf);
1207        Ok(())
1208    }
1209
1210    fn flush_probe_commands(&mut self, segment: &mut KcpSegment) -> KcpResult<()> {
1211        // flush window probing commands
1212        if (self.probe & KCP_ASK_SEND) != 0 {
1213            self._flush_probe_commands(KCP_CMD_WASK, segment)?;
1214        }
1215
1216        // flush window probing commands
1217        if (self.probe & KCP_ASK_TELL) != 0 {
1218            self._flush_probe_commands(KCP_CMD_WINS, segment)?;
1219        }
1220        self.probe = 0;
1221        Ok(())
1222    }
1223
1224    /// Flush pending ACKs
1225    pub fn flush_ack(&mut self) -> KcpResult<()> {
1226        if !self.updated {
1227            debug!("flush updated() must be called at least once");
1228            return Err(Error::NeedUpdate);
1229        }
1230
1231        let mut segment = KcpSegment {
1232            conv: self.conv,
1233            cmd: KCP_CMD_ACK,
1234            wnd: self.wnd_unused(),
1235            una: self.rcv_nxt,
1236            ..Default::default()
1237        };
1238
1239        self._flush_ack(&mut segment)
1240    }
1241
1242    /// Flush pending data in buffer.
1243    pub fn flush(&mut self) -> KcpResult<()> {
1244        if !self.updated {
1245            debug!("flush updated() must be called at least once");
1246            return Err(Error::NeedUpdate);
1247        }
1248
1249        let mut segment = KcpSegment {
1250            conv: self.conv,
1251            token: self.token,
1252            cmd: KCP_CMD_ACK,
1253            wnd: self.wnd_unused(),
1254            una: self.rcv_nxt,
1255            ..Default::default()
1256        };
1257
1258        self._flush_ack(&mut segment)?;
1259        self.probe_wnd_size();
1260        self.flush_probe_commands(&mut segment)?;
1261
1262        // println!("SNDBUF size {}", self.snd_buf.len());
1263
1264        // calculate window size
1265        let mut cwnd = cmp::min(self.snd_wnd, self.rmt_wnd);
1266        if !self.nocwnd {
1267            cwnd = cmp::min(self.cwnd, cwnd);
1268        }
1269
1270        // move data from snd_queue to snd_buf
1271        while timediff(self.snd_nxt, self.snd_una + cwnd as u32) < 0 {
1272            match self.snd_queue.pop_front() {
1273                Some(mut new_segment) => {
1274                    new_segment.conv = self.conv;
1275                    new_segment.token = self.token;
1276                    new_segment.cmd = KCP_CMD_PUSH;
1277                    new_segment.wnd = segment.wnd;
1278                    new_segment.ts = self.current;
1279                    new_segment.sn = self.snd_nxt;
1280                    self.snd_nxt += 1;
1281                    new_segment.una = self.rcv_nxt;
1282                    new_segment.resendts = self.current;
1283                    new_segment.rto = self.rx_rto;
1284                    new_segment.fastack = 0;
1285                    new_segment.xmit = 0;
1286
1287                    #[cfg(feature = "byte-check")]
1288                    {
1289                        new_segment.byte_check_code = compute_hash(&new_segment.data);
1290                    }
1291                    
1292                    self.snd_buf.push_back(new_segment);
1293                }
1294                None => break,
1295            }
1296        }
1297
1298        // calculate resent
1299        let resent = if self.fastresend > 0 {
1300            self.fastresend
1301        } else {
1302            u32::max_value()
1303        };
1304
1305        let rtomin = if !self.nodelay { self.rx_rto >> 3 } else { 0 };
1306
1307        let mut lost = false;
1308        let mut change = 0;
1309
1310        for snd_segment in &mut self.snd_buf {
1311            let mut need_send = false;
1312
1313            if snd_segment.xmit == 0 {
1314                need_send = true;
1315                snd_segment.xmit += 1;
1316                snd_segment.rto = self.rx_rto;
1317                snd_segment.resendts = self.current + snd_segment.rto + rtomin;
1318            } else if timediff(self.current, snd_segment.resendts) >= 0 {
1319                need_send = true;
1320                snd_segment.xmit += 1;
1321                self.xmit += 1;
1322                if !self.nodelay {
1323                    snd_segment.rto += self.rx_rto;
1324                } else {
1325                    snd_segment.rto += self.rx_rto / 2;
1326                }
1327                snd_segment.resendts = self.current + snd_segment.rto;
1328                lost = true;
1329            } else if snd_segment.fastack >= resent {
1330                need_send = true;
1331                snd_segment.xmit += 1;
1332                snd_segment.fastack = 0;
1333                snd_segment.resendts = self.current + snd_segment.rto;
1334                change += 1;
1335            }
1336
1337            if need_send {
1338                snd_segment.ts = self.current;
1339                snd_segment.wnd = segment.wnd;
1340                snd_segment.una = self.rcv_nxt;
1341
1342                let overhead = {
1343                    #[cfg(feature = "byte-check")]
1344                    {
1345                        self.overhead
1346                    }
1347
1348                    #[cfg(not(feature = "byte-check"))]
1349                    {
1350                        KCP_OVERHEAD
1351                    }
1352                };
1353                let need = overhead + snd_segment.data.len();
1354
1355                if self.buf.len() + need > self.mtu as usize {
1356                    self.output.write_all(&self.buf)?;
1357                    self.buf.clear();
1358                }
1359
1360                snd_segment.encode(&mut self.buf);
1361
1362                if snd_segment.xmit >= self.dead_link {
1363                    self.state = -1;
1364                }
1365            }
1366        }
1367
1368        // Flush all data in buffer
1369        if !self.buf.is_empty() {
1370            self.output.write_all(&self.buf)?;
1371            self.buf.clear();
1372        }
1373
1374        // update ssthresh
1375        if change > 0 {
1376            let inflight = self.snd_nxt - self.snd_una;
1377            self.ssthresh = inflight as u16 / 2;
1378            if self.ssthresh < KCP_THRESH_MIN {
1379                self.ssthresh = KCP_THRESH_MIN;
1380            }
1381            self.cwnd = self.ssthresh + resent as u16;
1382            self.incr = self.cwnd as u32 * self.mss;
1383        }
1384
1385        if lost {
1386            self.ssthresh = cwnd / 2;
1387            if self.ssthresh < KCP_THRESH_MIN {
1388                self.ssthresh = KCP_THRESH_MIN;
1389            }
1390            self.cwnd = 1;
1391            self.incr = self.mss;
1392        }
1393
1394        if self.cwnd < 1 {
1395            self.cwnd = 1;
1396            self.incr = self.mss;
1397        }
1398
1399        Ok(())
1400    }
1401
1402    /// Update state every 10ms ~ 100ms.
1403    ///
1404    /// Or you can ask `check` when to call this again.
1405    pub fn update(&mut self, current: u32) -> KcpResult<()> {
1406        self.current = current;
1407
1408        if !self.updated {
1409            self.updated = true;
1410            self.ts_flush = self.current;
1411        }
1412
1413        let mut slap = timediff(self.current, self.ts_flush);
1414
1415        if slap >= 10000 || slap < -10000 {
1416            self.ts_flush = self.current;
1417            slap = 0;
1418        }
1419
1420        if slap >= 0 {
1421            self.ts_flush += self.interval;
1422            if timediff(self.current, self.ts_flush) >= 0 {
1423                self.ts_flush = self.current + self.interval;
1424            }
1425            self.flush()?;
1426        }
1427
1428        Ok(())
1429    }
1430}
1431
1432#[cfg(feature = "tokio")]
1433impl<Output: AsyncWrite + Unpin + Send> Kcp<Output> {
1434    async fn _async_flush_ack(&mut self, segment: &mut KcpSegment) -> KcpResult<()> {
1435        // flush acknowledges
1436        // while let Some((sn, ts)) = self.acklist.pop_front() {
1437        for &(sn, ts) in &self.acklist {
1438            if self.buf.len() + self.header_len() > self.mtu {
1439                self.output.write_all(&self.buf).await?;
1440                self.buf.clear();
1441            }
1442            segment.sn = sn;
1443            segment.ts = ts;
1444            segment.encode(&mut self.buf);
1445        }
1446        self.acklist.clear();
1447
1448        Ok(())
1449    }
1450
1451    async fn _async_flush_probe_commands(
1452        &mut self,
1453        cmd: u8,
1454        segment: &mut KcpSegment,
1455    ) -> KcpResult<()> {
1456        segment.cmd = cmd;
1457        if self.buf.len() + self.header_len() > self.mtu {
1458            self.output.write_all(&self.buf).await?;
1459            self.buf.clear();
1460        }
1461        segment.encode(&mut self.buf);
1462        Ok(())
1463    }
1464
1465    async fn async_flush_probe_commands(&mut self, segment: &mut KcpSegment) -> KcpResult<()> {
1466        // flush window probing commands
1467        if (self.probe & KCP_ASK_SEND) != 0 {
1468            self._async_flush_probe_commands(KCP_CMD_WASK, segment)
1469                .await?;
1470        }
1471
1472        // flush window probing commands
1473        if (self.probe & KCP_ASK_TELL) != 0 {
1474            self._async_flush_probe_commands(KCP_CMD_WINS, segment)
1475                .await?;
1476        }
1477        self.probe = 0;
1478        Ok(())
1479    }
1480
1481    /// Flush pending ACKs
1482    pub async fn async_flush_ack(&mut self) -> KcpResult<()> {
1483        if !self.updated {
1484            debug!("flush updated() must be called at least once");
1485            return Err(Error::NeedUpdate);
1486        }
1487
1488        let mut segment = KcpSegment {
1489            conv: self.conv,
1490            token: self.token,
1491            cmd: KCP_CMD_ACK,
1492            wnd: self.wnd_unused(),
1493            una: self.rcv_nxt,
1494            ..Default::default()
1495        };
1496
1497        self._async_flush_ack(&mut segment).await
1498    }
1499
1500    /// Flush pending data in buffer.
1501    pub async fn async_flush(&mut self) -> KcpResult<()> {
1502        if !self.updated {
1503            debug!("flush updated() must be called at least once");
1504            return Err(Error::NeedUpdate);
1505        }
1506
1507        let mut segment = KcpSegment {
1508            conv: self.conv,
1509            token: self.token,
1510            cmd: KCP_CMD_ACK,
1511            wnd: self.wnd_unused(),
1512            una: self.rcv_nxt,
1513            ..Default::default()
1514        };
1515
1516        self._async_flush_ack(&mut segment).await?;
1517        self.probe_wnd_size();
1518        self.async_flush_probe_commands(&mut segment).await?;
1519
1520        // calculate window size
1521        let mut cwnd = cmp::min(self.snd_wnd, self.rmt_wnd);
1522        if !self.nocwnd {
1523            cwnd = cmp::min(self.cwnd, cwnd);
1524        }
1525
1526        // move data from snd_queue to snd_buf
1527        while timediff(self.snd_nxt, self.snd_una + u32::from(cwnd)) < 0 {
1528            match self.snd_queue.pop_front() {
1529                Some(mut new_segment) => {
1530                    new_segment.conv = self.conv;
1531                    new_segment.token = self.token;
1532                    new_segment.cmd = KCP_CMD_PUSH;
1533                    new_segment.wnd = segment.wnd;
1534                    new_segment.ts = self.current;
1535                    new_segment.sn = self.snd_nxt;
1536                    self.snd_nxt += 1;
1537                    new_segment.una = self.rcv_nxt;
1538                    new_segment.resendts = self.current;
1539                    new_segment.rto = self.rx_rto;
1540                    new_segment.fastack = 0;
1541                    new_segment.xmit = 0;
1542                    
1543                    #[cfg(feature = "byte-check")]
1544                    {
1545                        new_segment.byte_check_code = compute_hash(&new_segment.data);
1546                    }
1547                    
1548                    self.snd_buf.push_back(new_segment);
1549                }
1550                None => break,
1551            }
1552        }
1553
1554        // calculate resent
1555        let resent = if self.fastresend > 0 {
1556            self.fastresend
1557        } else {
1558            u32::max_value()
1559        };
1560
1561        let rtomin = if !self.nodelay { self.rx_rto >> 3 } else { 0 };
1562
1563        let mut lost = false;
1564        let mut change = 0;
1565
1566        for snd_segment in &mut self.snd_buf {
1567            let mut need_send = false;
1568
1569            if snd_segment.xmit == 0 {
1570                need_send = true;
1571                snd_segment.xmit += 1;
1572                snd_segment.rto = self.rx_rto;
1573                snd_segment.resendts = self.current + snd_segment.rto + rtomin;
1574            } else if timediff(self.current, snd_segment.resendts) >= 0 {
1575                need_send = true;
1576                snd_segment.xmit += 1;
1577                self.xmit += 1;
1578                if !self.nodelay {
1579                    snd_segment.rto += cmp::max(snd_segment.rto, self.rx_rto);
1580                } else {
1581                    let step = snd_segment.rto; // (kcp->nodelay < 2) ? ((IINT32)(segment->rto)) : kcp->rx_rto;
1582                    snd_segment.rto += step / 2;
1583                }
1584                snd_segment.resendts = self.current + snd_segment.rto;
1585                lost = true;
1586            } else if snd_segment.fastack >= resent {
1587                need_send = true;
1588                snd_segment.xmit += 1;
1589                snd_segment.fastack = 0;
1590                snd_segment.resendts = self.current + snd_segment.rto;
1591                change += 1;
1592            }
1593
1594            if need_send {
1595                snd_segment.ts = self.current;
1596                snd_segment.wnd = segment.wnd;
1597                snd_segment.una = self.rcv_nxt;
1598
1599                let overhead = {
1600                    #[cfg(feature = "byte-check")]
1601                    {
1602                        self.overhead
1603                    }
1604
1605                    #[cfg(not(feature = "byte-check"))]
1606                    {
1607                        KCP_OVERHEAD
1608                    }
1609                };
1610                let need = overhead + snd_segment.data.len();
1611
1612                if self.buf.len() + need > self.mtu {
1613                    self.output.write_all(&self.buf).await?;
1614                    self.buf.clear();
1615                }
1616
1617                snd_segment.encode(&mut self.buf);
1618
1619                if snd_segment.xmit >= self.dead_link {
1620                    self.state = -1; // (IUINT32)-1
1621                }
1622            }
1623        }
1624
1625        // Flush all data in buffer
1626        if !self.buf.is_empty() {
1627            self.output.write_all(&self.buf).await?;
1628            self.buf.clear();
1629        }
1630
1631        // update ssthresh
1632        if change > 0 {
1633            let inflight = self.snd_nxt - self.snd_una;
1634            self.ssthresh = inflight as u16 / 2;
1635            if self.ssthresh < KCP_THRESH_MIN {
1636                self.ssthresh = KCP_THRESH_MIN;
1637            }
1638            self.cwnd = self.ssthresh + resent as u16;
1639            self.incr = self.cwnd as u32 * self.mss;
1640        }
1641
1642        if lost {
1643            self.ssthresh = cwnd / 2;
1644            if self.ssthresh < KCP_THRESH_MIN {
1645                self.ssthresh = KCP_THRESH_MIN;
1646            }
1647            self.cwnd = 1;
1648            self.incr = self.mss;
1649        }
1650
1651        if self.cwnd < 1 {
1652            self.cwnd = 1;
1653            self.incr = self.mss;
1654        }
1655
1656        Ok(())
1657    }
1658
1659    /// Update state every 10ms ~ 100ms.
1660    ///
1661    /// Or you can ask `check` when to call this again.
1662    pub async fn async_update(&mut self, current: u32) -> KcpResult<()> {
1663        self.current = current;
1664
1665        if !self.updated {
1666            self.updated = true;
1667            self.ts_flush = self.current;
1668        }
1669
1670        let mut slap = timediff(self.current, self.ts_flush);
1671
1672        if !(-10000..10000).contains(&slap) {
1673            self.ts_flush = self.current;
1674            slap = 0;
1675        }
1676
1677        if slap >= 0 {
1678            self.ts_flush += self.interval;
1679            if timediff(self.current, self.ts_flush) >= 0 {
1680                self.ts_flush = self.current + self.interval;
1681            }
1682            self.async_flush().await?;
1683        }
1684
1685        Ok(())
1686    }
1687}