libadb 0.8.0

Low-level ADB protocol library for direct TCP and USB communication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
use alloc::collections::BTreeSet;
use bytes::{Buf, Bytes, BytesMut};
use core::future::Future;

use super::error::{Error, ProtocolError, RxOverflow};
use super::protocol::command::Command;
use super::protocol::Packet;
use super::session::Session;

/// AOSP's adbd always sends the 4-byte credit; when a peer omits it,
/// the operation that received the packet fails with
/// [`ProtocolError::ShortReadyPayload`] — deliberate strictness over
/// guessing a budget.
pub(crate) fn parse_ready_credit(payload: &[u8]) -> Result<u32, ProtocolError> {
    if payload.len() >= 4 {
        Ok(u32::from_le_bytes([
            payload[0], payload[1], payload[2], payload[3],
        ]))
    } else {
        Err(ProtocolError::ShortReadyPayload)
    }
}

/// Whether an inbound WRTE is acknowledged now or once it is read.
pub(crate) enum AckDecision {
    Now {
        local_id: u32,
        remote_id: u32,
        len: usize,
    },
    Hold,
}

pub(crate) enum DispatchOutcome {
    /// A WRTE was buffered and has to be acknowledged now.
    AckWrite {
        #[allow(dead_code)] // read only by split::Reader, to wake readers
        idx: usize,
        local_id: u32,
        remote_id: u32,
        len: usize,
    },
    /// An OKAY refilled the slot's send budget: one writer can proceed.
    CreditGranted {
        #[allow(dead_code)] // read only by split::Reader, to wake writers
        idx: usize,
    },
    /// A CLSE closed the slot: every waiter has to see the error.
    SlotClosed {
        #[allow(dead_code)] // read only by split::Reader, to wake writers
        idx: usize,
    },
    /// A WRTE was buffered with its acknowledgement held back until it
    /// is read.
    DataBuffered {
        #[allow(dead_code)] // read only by split::Reader, to wake readers
        idx: usize,
    },
    /// The device opened a channel toward the host (`adb reverse`).
    /// The host queues it for [`accept_incoming`] and answers READY on
    /// accept or CLSE on refusal.
    ///
    /// [`accept_incoming`]: super::connection::Connection::accept_incoming
    IncomingOpen {
        remote_id: u32,
        /// The device's receive credit from OPEN `arg1`; our send
        /// budget once accepted, meaningful only with delayed ack.
        credit: u32,
        destination: Bytes,
    },
    /// The device gave up on an OPEN it had sent — a CLSE that names
    /// no local id. Drop the matching pending entry if still queued.
    CancelPendingOpen {
        remote_id: u32,
    },
    /// A READY for no channel of ours: the device accepted an OPEN its
    /// opener gave up on before the answer. Answer CLSE with both ids —
    /// adbd ignores one that does not name its own — or the device's
    /// end stays open.
    StrayReady {
        local_id: u32,
        remote_id: u32,
    },
    /// A packet broke this slot's channel alone. The slot is not
    /// closed: whoever dispatched decides what the fault costs.
    ChannelFault {
        #[allow(dead_code)] // read only by split::Reader::run, to close the channel
        idx: usize,
        #[allow(dead_code)] // read only by split::Reader::run, to close the channel
        local_id: u32,
        #[allow(dead_code)] // read only by split::Reader::run, to close the channel
        remote_id: u32,
        /// The slot was waiting for the device's answer to its OPEN.
        #[allow(dead_code)] // read only by split::Reader, to fail the open
        opening: bool,
        fault: ChannelFault,
    },
    Unmatched,
}

/// What breaks one channel without breaking the connection: the packet
/// was read whole, so the stream stays in step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ChannelFault {
    /// A WRTE did not fit the channel's receive buffer.
    RxOverflow,
    /// A READY the channel cannot take, such as one without its
    /// delayed-ACK credit.
    Protocol(ProtocolError),
}

impl ChannelFault {
    pub fn error<E>(self) -> Error<E> {
        match self {
            Self::RxOverflow => Error::ChannelRxOverflow,
            Self::Protocol(e) => Error::Protocol(e),
        }
    }
}

/// A device-initiated OPEN waiting for the application's verdict.
#[derive(Debug)]
pub(crate) struct PendingOpen {
    pub remote_id: u32,
    pub credit: u32,
    pub destination: Bytes,
}

/// Does a CLSE with these args close the channel `(local_id,
/// remote_id)`? The ordinary form names our id in `arg1`; a
/// zero-`arg1` withdrawal whose OPEN we already accepted — it crossed
/// our READY in flight — names the device's id in `arg0`.
pub(crate) fn clse_closes(arg0: u32, arg1: u32, local_id: u32, remote_id: u32) -> bool {
    arg1 == local_id || (arg1 == 0 && arg0 == remote_id)
}

/// `rx_cap` bounds how much unread data a single channel may accumulate;
/// a WRTE that would push it past the cap is a
/// [`ChannelFault::RxOverflow`] instead of growing the buffer.
pub(crate) fn dispatch_packet(
    channels: &mut [Option<ChannelSlot>],
    pkt: &Packet,
    delayed_ack: bool,
    rx_cap: usize,
    watermark: usize,
) -> DispatchOutcome {
    // The handshake is over, so a device that opens it again, or asks
    // for TLS now, is out of turn. It is dropped like any packet nobody
    // claims, but said in the log, since nothing else will mention it.
    if matches!(
        pkt.command,
        Command::Connect | Command::Auth | Command::StartTls
    ) {
        log::warn!(
            "dropping {:?} from the device after the handshake",
            pkt.command
        );
        return DispatchOutcome::Unmatched;
    }
    if pkt.command == Command::Open {
        return DispatchOutcome::IncomingOpen {
            remote_id: pkt.arg0,
            credit: pkt.arg1,
            destination: pkt.data.clone(),
        };
    }
    if pkt.command == Command::Close && pkt.arg1 == 0 {
        // The withdrawal may have crossed our READY in flight: the
        // request is then no longer queued but an accepted slot, and
        // has to close like any remote CLSE — the cancel handlers only
        // reach requests still awaiting a verdict.
        if pkt.arg0 != 0 {
            for (idx, slot_opt) in channels.iter_mut().enumerate() {
                let Some(slot) = slot_opt else { continue };
                if slot.remote_id == pkt.arg0 {
                    slot.apply_close();
                    return DispatchOutcome::SlotClosed { idx };
                }
            }
        }
        return DispatchOutcome::CancelPendingOpen {
            remote_id: pkt.arg0,
        };
    }
    for (idx, slot_opt) in channels.iter_mut().enumerate() {
        let Some(slot) = slot_opt else { continue };
        match pkt.command {
            // A channel closed for a fault takes nothing more: data that
            // was still in flight would read as if no gap came before it.
            Command::Write | Command::Ready
                if pkt.arg1 == slot.local_id && slot.failed.is_some() =>
            {
                return DispatchOutcome::Unmatched;
            }
            Command::Write if pkt.arg1 == slot.local_id => {
                return match slot.apply_write(&pkt.data, rx_cap, delayed_ack, watermark) {
                    Ok(AckDecision::Now {
                        local_id,
                        remote_id,
                        len,
                    }) => DispatchOutcome::AckWrite {
                        idx,
                        local_id,
                        remote_id,
                        len,
                    },
                    Ok(AckDecision::Hold) => DispatchOutcome::DataBuffered { idx },
                    Err(RxOverflow) => slot.fault(idx, pkt.arg0, ChannelFault::RxOverflow),
                };
            }
            Command::Ready if pkt.arg1 == slot.local_id => {
                let granted = if slot.state == ChannelState::Opening {
                    slot.accept_open_ready(pkt.arg0, &pkt.data, delayed_ack)
                } else {
                    slot.apply_ready(&pkt.data, delayed_ack)
                };
                return match granted {
                    Ok(()) => DispatchOutcome::CreditGranted { idx },
                    Err(e) => slot.fault(idx, pkt.arg0, ChannelFault::Protocol(e)),
                };
            }
            Command::Close if pkt.arg1 == slot.local_id => {
                slot.apply_close();
                return DispatchOutcome::SlotClosed { idx };
            }
            _ => {}
        }
    }
    if pkt.command == Command::Ready && pkt.arg0 != 0 && pkt.arg1 != 0 {
        return DispatchOutcome::StrayReady {
            local_id: pkt.arg1,
            remote_id: pkt.arg0,
        };
    }
    DispatchOutcome::Unmatched
}

/// Result of [`Channel::select`] / [`Session::select_channel`].
#[derive(Debug)]
pub enum SelectResult<T> {
    /// The channel produced data — value is the number of bytes read.
    Data(usize),
    /// The interrupt future completed with this value before channel data
    /// arrived. The channel state is unchanged and the next read will
    /// pick up where this one left off.
    Interrupted(T),
}

/// Opaque handle to an open ADB channel.
///
/// Used with [`Session::open_channel`], [`read_channel`](Session::read_channel),
/// [`write_channel`](Session::write_channel), [`close_channel`](Session::close_channel),
/// and the same methods on [`Connection`](crate::Connection) and the split
/// [`Writer`](crate::Writer).
/// A stale handle from a closed channel never aliases a later reopened
/// one — it returns [`Error::ChannelClosed`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ChannelId {
    pub(crate) slot: usize,
    pub(crate) local_id: u32,
}

impl ChannelId {
    /// Build a `ChannelId` from raw `(slot, local_id)`. Intended for
    /// FFI bridges that round-trip a handle through an opaque integer;
    /// ordinary Rust callers should use the `ChannelId` returned by
    /// [`Session::open_channel`] directly.
    pub fn from_raw(slot: usize, local_id: u32) -> Self {
        Self { slot, local_id }
    }

    /// Slot index in the connection's channel table.
    pub fn slot(self) -> usize {
        self.slot
    }

    /// ADB wire `local_id` for this channel — unique per OPEN.
    pub fn local_id(self) -> u32 {
        self.local_id
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ChannelState {
    Opening,
    Open,
    Closed,
}

pub(crate) struct ChannelSlot {
    pub local_id: u32,
    pub remote_id: u32,
    pub state: ChannelState,
    pub rx_buf: BytesMut,
    pub wrte_acked: bool,
    pub send_budget: i64,
    /// Bytes received for this channel that the peer has not been
    /// acknowledged for yet — the backpressure the device feels.
    pub unacked: usize,
    /// Send-queue place currently allowed to reserve credit. The queue
    /// keeps concurrent `split::Writer`s in arrival order: places are
    /// handed out by [`send_enqueue`](Self::send_enqueue) and only the
    /// holder of `send_q_head` may take budget.
    pub send_q_head: u64,
    pub send_q_tail: u64,
    /// Places whose writer left the queue unserved; skipped when the
    /// head reaches them. Bounded: a hole is only recorded below a
    /// place still occupied — a leaving tail reclaims itself and any
    /// holes adjacent to it — so cancellation churn cannot grow this
    /// past the caller's own peak of concurrent writers.
    pub send_q_gone: BTreeSet<u64>,
    /// What broke this channel, once [`fail`](Self::fail) closed it for
    /// that: its calls then fail with this rather than `ChannelClosed`.
    pub failed: Option<ChannelFault>,
}

impl ChannelSlot {
    pub fn new(local_id: u32) -> Self {
        Self {
            local_id,
            remote_id: 0,
            state: ChannelState::Opening,
            rx_buf: BytesMut::new(),
            wrte_acked: true,
            send_budget: 0,
            unacked: 0,
            send_q_head: 0,
            send_q_tail: 0,
            send_q_gone: BTreeSet::new(),
            failed: None,
        }
    }

    pub fn channel_ids(&self) -> (u32, u32) {
        (self.local_id, self.remote_id)
    }

    pub fn is_closed(&self) -> bool {
        self.state == ChannelState::Closed
    }

    /// The error a call on this channel fails with once it is closed.
    pub fn closed_error<E>(&self) -> Error<E> {
        self.failed
            .map_or(Error::ChannelClosed, ChannelFault::error)
    }

    /// Close this channel for `fault`. Nothing is acknowledged after
    /// it, so the device gets no OKAY for a channel we are closing.
    #[allow(dead_code)] // used only by split::Reader::run
    pub fn fail(&mut self, fault: ChannelFault) {
        self.failed = Some(fault);
        self.state = ChannelState::Closed;
        self.unacked = 0;
    }

    /// `remote_id` comes from the packet: a slot still opening has
    /// none of its own yet.
    fn fault(&self, idx: usize, remote_id: u32, fault: ChannelFault) -> DispatchOutcome {
        DispatchOutcome::ChannelFault {
            idx,
            local_id: self.local_id,
            remote_id,
            opening: self.state == ChannelState::Opening,
            fault,
        }
    }

    pub fn accept_open_ready(
        &mut self,
        remote_id: u32,
        payload: &[u8],
        delayed_ack: bool,
    ) -> Result<(), ProtocolError> {
        // Parsed first: a READY the slot cannot take leaves it as it
        // was, still opening, rather than open with no budget.
        if delayed_ack {
            self.send_budget = parse_ready_credit(payload)? as i64;
        }
        self.remote_id = remote_id;
        self.state = ChannelState::Open;
        Ok(())
    }

    pub fn apply_ready(&mut self, payload: &[u8], delayed_ack: bool) -> Result<(), ProtocolError> {
        if delayed_ack {
            self.send_budget += parse_ready_credit(payload)? as i64;
        } else {
            self.wrte_acked = true;
        }
        Ok(())
    }

    /// Take an inbound WRTE and say whether to acknowledge it now.
    ///
    /// Acknowledging is what re-opens the sender's window, so doing it
    /// on arrival means the device may keep writing to a channel the
    /// application never reads — the buffer then grows without bound.
    ///
    /// With delayed-ack the answer is always "later": credit is returned
    /// as the application consumes bytes, and the budget we advertised
    /// bounds what can pile up meanwhile. Without it the window is a
    /// single packet, so waiting for the read on every packet would turn
    /// the channel into a ping-pong; the acknowledgement goes out at
    /// once while little is buffered, and is held back once `watermark`
    /// bytes are waiting to be read.
    pub fn apply_write(
        &mut self,
        payload: &[u8],
        cap: usize,
        delayed_ack: bool,
        watermark: usize,
    ) -> Result<AckDecision, RxOverflow> {
        self.push_rx(payload, cap)?;
        self.unacked = self.unacked.saturating_add(payload.len());
        if !delayed_ack && self.rx_buf.len() < watermark {
            self.unacked = 0;
            return Ok(AckDecision::Now {
                local_id: self.local_id,
                remote_id: self.remote_id,
                len: payload.len(),
            });
        }
        Ok(AckDecision::Hold)
    }

    /// Hand `taken` bytes of a freshly arrived packet to the caller,
    /// buffer whatever is left of it, and say what to acknowledge.
    pub fn deliver(
        &mut self,
        payload: &[u8],
        taken: usize,
        cap: usize,
        delayed_ack: bool,
        watermark: usize,
    ) -> Result<Option<(u32, u32, usize)>, RxOverflow> {
        if taken < payload.len() {
            self.push_rx(&payload[taken..], cap)?;
            self.unacked = self.unacked.saturating_add(payload.len() - taken);
        }
        if delayed_ack {
            return Ok((taken > 0).then_some((self.local_id, self.remote_id, taken)));
        }
        if self.rx_buf.len() >= watermark {
            return Ok(None);
        }
        let len = core::mem::take(&mut self.unacked);
        Ok(Some((self.local_id, self.remote_id, len)))
    }

    /// Record that the application took `n` bytes, and say what to
    /// acknowledge as a result.
    pub fn consume(
        &mut self,
        n: usize,
        delayed_ack: bool,
        watermark: usize,
    ) -> Option<(u32, u32, usize)> {
        let len = self.ack_len(n, self.rx_buf.len(), delayed_ack, watermark)?;
        self.unacked -= len;
        Some((self.local_id, self.remote_id, len))
    }

    /// Whether taking up to `want` buffered bytes now would owe the
    /// device an OKAY — what [`take_buffered`](Self::take_buffered)
    /// would answer, without taking anything.
    #[allow(dead_code)] // used only by split::Shared
    pub fn take_acks(&self, want: usize, delayed_ack: bool, watermark: usize) -> bool {
        let n = want.min(self.rx_buf.len());
        let remaining = self.rx_buf.len() - n;
        self.ack_len(n, remaining, delayed_ack, watermark).is_some()
    }

    /// How much taking `n` bytes acknowledges, `remaining` being what
    /// the buffer holds once they are gone. With delayed ACK, the bytes
    /// taken; without it, everything held back, once the buffer is
    /// below `watermark` again.
    fn ack_len(
        &self,
        n: usize,
        remaining: usize,
        delayed_ack: bool,
        watermark: usize,
    ) -> Option<usize> {
        if self.unacked == 0 {
            return None;
        }
        if delayed_ack {
            let len = n.min(self.unacked);
            return (len > 0).then_some(len);
        }
        (remaining < watermark).then_some(self.unacked)
    }

    /// Copy buffered bytes into `buf`, and say what to acknowledge for
    /// taking them. `None` while an open channel has nothing buffered;
    /// once a closed one is drained, [`Error::ChannelClosed`] or the
    /// fault that closed it.
    #[allow(clippy::type_complexity)]
    pub fn take_buffered<E>(
        &mut self,
        buf: &mut [u8],
        delayed_ack: bool,
        watermark: usize,
    ) -> Result<Option<(usize, Option<(u32, u32, usize)>)>, Error<E>> {
        if self.rx_buf.is_empty() {
            return if self.is_closed() {
                Err(self.closed_error())
            } else {
                Ok(None)
            };
        }
        let n = buf.len().min(self.rx_buf.len());
        buf[..n].copy_from_slice(&self.rx_buf[..n]);
        self.rx_buf.advance(n);
        Ok(Some((n, self.consume(n, delayed_ack, watermark))))
    }

    pub fn push_rx(&mut self, payload: &[u8], cap: usize) -> Result<(), RxOverflow> {
        if self.rx_buf.len().saturating_add(payload.len()) > cap {
            return Err(RxOverflow);
        }
        self.rx_buf.extend_from_slice(payload);
        Ok(())
    }

    pub fn apply_close(&mut self) {
        self.state = ChannelState::Closed;
    }

    #[allow(dead_code)] // used only by split::Writer
    pub fn try_reserve_send(&mut self, want: usize, delayed_ack: bool) -> Option<usize> {
        if delayed_ack {
            if self.send_budget > 0 {
                let n = (self.send_budget as usize).min(want);
                self.send_budget -= n as i64;
                return Some(n);
            }
        } else if self.wrte_acked {
            self.wrte_acked = false;
            return Some(want);
        }
        None
    }

    #[allow(dead_code)] // used only by split::Writer's CreditGuard
    pub fn refund(&mut self, n: usize, delayed_ack: bool) {
        if delayed_ack {
            self.send_budget += n as i64;
        } else {
            self.wrte_acked = true;
        }
    }

    /// Take a place at the back of the send queue.
    #[allow(dead_code)] // used only by split::Writer
    pub fn send_enqueue(&mut self) -> u64 {
        let place = self.send_q_tail;
        self.send_q_tail += 1;
        place
    }

    /// The place currently allowed to reserve credit.
    #[allow(dead_code)] // used only by split::Writer
    pub fn send_turn(&self) -> u64 {
        self.send_q_head
    }

    /// Move the queue past the served head, skipping places whose
    /// writer already left.
    #[allow(dead_code)] // used only by split::Writer
    pub fn send_advance(&mut self) {
        self.send_q_head += 1;
        while self.send_q_gone.remove(&self.send_q_head) {
            self.send_q_head += 1;
        }
    }

    /// Leave the queue from `place` without being served. Returns
    /// whether the head moved — the caller then wakes the next writer.
    ///
    /// A leaving tail hands its place straight back — together with any
    /// holes that end up at the tail with it — so a caller that keeps
    /// queueing and dropping writes behind a blocked head reuses one
    /// place instead of growing the hole set.
    #[allow(dead_code)] // used only by split::Writer
    pub fn send_leave(&mut self, place: u64) -> bool {
        if place == self.send_q_head {
            self.send_advance();
            true
        } else if place + 1 == self.send_q_tail {
            self.send_q_tail = place;
            while self.send_q_tail > self.send_q_head
                && self.send_q_gone.remove(&(self.send_q_tail - 1))
            {
                self.send_q_tail -= 1;
            }
            false
        } else if place > self.send_q_head {
            self.send_q_gone.insert(place);
            false
        } else {
            false
        }
    }
}

pub(crate) fn channel_ids_of<E>(
    channels: &[Option<ChannelSlot>],
    ch: ChannelId,
) -> Result<(u32, u32), Error<E>> {
    channels
        .get(ch.slot)
        .and_then(|s| s.as_ref())
        .filter(|s| s.local_id == ch.local_id)
        .map(ChannelSlot::channel_ids)
        .ok_or(Error::ChannelClosed)
}

#[allow(dead_code)] // used only by split::{CreditGuard, Reader, Writer}
pub(crate) fn slot_for_mut(
    channels: &mut [Option<ChannelSlot>],
    ch: ChannelId,
) -> Option<&mut ChannelSlot> {
    channels
        .get_mut(ch.slot)
        .and_then(|s| s.as_mut())
        .filter(|s| s.local_id == ch.local_id)
}

/// An open ADB channel tied to a [`Session`].
///
/// Provides [`read`](Self::read), [`write`](Self::write), and
/// [`close`](Self::close) methods.  Created by [`Session::open`] or
/// [`Connection::open`](crate::Connection::open).
///
/// Because `Channel` holds a mutable borrow on the session, only one
/// `Channel` can be active at a time on it.  For concurrent access to
/// multiple channels, use the [`ChannelId`]-based methods on
/// [`Connection`](crate::Connection) directly
/// ([`open_channel`](crate::Connection::open_channel),
/// [`read_channel`](crate::Connection::read_channel), etc.), or split the
/// connection and give each task a clone of the
/// [`Writer`](crate::Writer).
pub struct Channel<'a, S> {
    pub(crate) session: &'a mut S,
    pub(crate) id: ChannelId,
}

impl<S: Session> Channel<'_, S> {
    /// Read data from the channel into `buf`.
    ///
    /// Returns the number of bytes read. If data was already buffered
    /// (from a previous WRTE) the call returns immediately. Otherwise it
    /// waits until a WRTE arrives for this channel.
    pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error<S::IoError>> {
        self.session.read_channel(self.id, buf).await
    }

    /// Write data to the channel.
    ///
    /// Data is split into `max_payload`-sized chunks with appropriate
    /// flow-control (OKAY acknowledgement in legacy mode, credit-based
    /// budgeting in delayed ACK mode).
    pub async fn write(&mut self, data: &[u8]) -> Result<(), Error<S::IoError>> {
        self.session.write_channel(self.id, data).await
    }

    /// Read from the channel, but return early if `interrupt` resolves first.
    ///
    /// This is the primary way to combine channel reads with other async
    /// event sources (e.g. stdin, signals) without raw packet manipulation.
    /// If `interrupt` wins, the channel state is unchanged and the next
    /// call resumes normally.
    ///
    /// How quickly `interrupt` can win depends on the session. On a
    /// split [`Writer`](crate::Writer) it is raced against the wait for
    /// data. On a [`Connection`](crate::Connection) over TCP it is raced against the read
    /// itself, so a pending read is dropped the moment the interrupt is
    /// due. A transport that would lose data that way — USB, where
    /// cancelling a bulk transfer discards what the device already
    /// wrote into it — has the interrupt checked between reads instead,
    /// so it takes effect once the read in flight has finished. See
    /// [`ReadCancelSafety`](crate::transport::ReadCancelSafety).
    ///
    /// ```ignore
    /// loop {
    ///     match ch.select(&mut buf, stdin_rx.recv()).await? {
    ///         SelectResult::Data(n) => { /* handle buf[..n] */ }
    ///         SelectResult::Interrupted(input) => {
    ///             ch.write(&input).await?;
    ///         }
    ///     }
    /// }
    /// ```
    pub async fn select<F: Future>(
        &mut self,
        buf: &mut [u8],
        interrupt: F,
    ) -> Result<SelectResult<F::Output>, Error<S::IoError>> {
        self.session.select_channel(self.id, buf, interrupt).await
    }

    /// Close the channel, sending CLSE to the device and freeing the slot.
    ///
    /// Consumes the `Channel`.
    pub async fn close(self) -> Result<(), Error<S::IoError>> {
        self.session.close_channel(self.id).await
    }
}

#[cfg(test)]
mod tests {
    use super::ChannelSlot;

    #[test]
    fn cancellation_churn_behind_a_blocked_head_does_not_accumulate() {
        let mut slot = ChannelSlot::new(1);
        let _head = slot.send_enqueue();

        for _ in 0..1_000 {
            let mid = slot.send_enqueue();
            let tail = slot.send_enqueue();
            // Dropped mid-queue: a hole, while `tail` still lives...
            assert!(!slot.send_leave(mid));
            // ...and the leaving tail reclaims itself and the hole.
            assert!(!slot.send_leave(tail));
        }

        assert!(slot.send_q_gone.is_empty());
        assert_eq!(slot.send_q_tail, 1);
        assert_eq!(slot.send_q_head, 0);
    }
}