libadb 0.9.0

Low-level ADB protocol library for direct TCP and USB communication
Documentation
#![allow(dead_code)]

use libadb::protocol::features::Feature;
use libadb::{Connection, ConnectionConfig, Error, HostBanner};

/// shell_v2 wire frame IDs.
pub const SH_STDOUT: u8 = 1;
pub const SH_STDERR: u8 = 2;
pub const SH_EXIT: u8 = 3;
pub const SH_CLOSE_STDIN: u8 = 4;
pub const SH_WINDOW_SIZE_CHANGE: u8 = 5;

/// Encode a shell_v2 packet: `[id: u8, length: u32 LE, payload...]`.
pub fn shell_v2_encode(id: u8, payload: &[u8]) -> Vec<u8> {
    let len = (payload.len() as u32).to_le_bytes();
    let mut pkt = Vec::with_capacity(5 + payload.len());
    pkt.push(id);
    pkt.extend_from_slice(&len);
    pkt.extend_from_slice(payload);
    pkt
}

/// Parse a 5-byte shell_v2 message → `(id, payload_length)`.
pub fn shell_v2_parse(buf: &[u8; 5]) -> (u8, u32) {
    (buf[0], u32::from_le_bytes([buf[1], buf[2], buf[3], buf[4]]))
}

use crate::fake_device::{wrap, FakeDevice, FakeSession, TestAuth};
use crate::rt::{self, JoinHandle};

pub async fn handshake(
    device_features: &[&str],
    host_features: &[Feature],
) -> (Connection<rt::AdbTransport>, JoinHandle<FakeSession>) {
    let banner = format!("device::features={}", device_features.join(","));
    let (handle, addr) = FakeDevice::new().banner(banner.into_bytes()).bind().await;
    let device = rt::spawn(async move { handle.accept().await });
    let stream = rt::connect(addr).await;
    let conn = Connection::connect(
        wrap(stream),
        TestAuth,
        HostBanner::Features(host_features),
        ConnectionConfig::new(),
    )
    .await
    .unwrap();
    (conn, device)
}

pub fn expect_missing_feature<T, E: core::fmt::Debug>(
    result: Result<T, Error<E>>,
    expected: Feature,
) {
    let Err(err) = result else {
        panic!("expected Err(MissingFeature({expected:?})), got Ok");
    };
    assert!(
        matches!(err, Error::MissingFeature(f) if f == expected),
        "expected MissingFeature({expected:?}), got {err:?}",
    );
}

#[macro_export]
macro_rules! rt_test {
    ($(#[$attr:meta])* async fn $name:ident() $body:block) => {
        $(#[$attr])*
        #[test]
        fn $name() {
            $crate::rt::block_on(async move $body);
        }
    };
}

/// Build a v4 `logger_entry` record: 28-byte header + caller-supplied
/// payload.
pub fn logger_entry(
    pid: i32,
    tid: u32,
    sec: i32,
    nsec: i32,
    lid: u32,
    uid: u32,
    payload: &[u8],
) -> Vec<u8> {
    let mut buf = Vec::with_capacity(28 + payload.len());
    buf.extend_from_slice(&(payload.len() as u16).to_le_bytes());
    buf.extend_from_slice(&28u16.to_le_bytes());
    buf.extend_from_slice(&pid.to_le_bytes());
    buf.extend_from_slice(&tid.to_le_bytes());
    buf.extend_from_slice(&sec.to_le_bytes());
    buf.extend_from_slice(&nsec.to_le_bytes());
    buf.extend_from_slice(&lid.to_le_bytes());
    buf.extend_from_slice(&uid.to_le_bytes());
    buf.extend_from_slice(payload);
    buf
}

/// Build a `[priority][tag\0][message\0]` logcat payload.
pub fn logger_payload(priority: u8, tag: &[u8], message: &[u8]) -> Vec<u8> {
    let mut p = Vec::with_capacity(1 + tag.len() + 1 + message.len() + 1);
    p.push(priority);
    p.extend_from_slice(tag);
    p.push(0);
    p.extend_from_slice(message);
    p.push(0);
    p
}

pub async fn poll_once<F: core::future::Future>(
    mut f: core::pin::Pin<&mut F>,
) -> core::task::Poll<F::Output> {
    core::future::poll_fn(|cx| core::task::Poll::Ready(f.as_mut().poll(cx))).await
}