pdb-bindgen-codegen 0.1.0

Build-time discovery, PDB acquisition, and binding generation for pdb-bindgen.
Documentation
use super::error::{Error, HttpError};
use std::io::Read;

pub(super) enum Response {
    Full(ureq::Body),
    Partial { bytes: Vec<u8>, total: u64 },
    NotFound,
    RangeNotSatisfiable,
    Status(u16),
}

pub(super) struct Client(ureq::Agent);

impl Client {
    pub(super) fn new() -> Self {
        Self(
            ureq::Agent::config_builder()
                .http_status_as_error(false)
                .build()
                .into(),
        )
    }

    pub(super) fn get(&self, url: &str) -> Result<Response, Error> {
        self.request(url, None)
    }

    pub(super) fn range(&self, url: &str, start: u64, end: u64) -> Result<Response, Error> {
        self.request(url, Some((start, end)))
    }

    fn request(&self, url: &str, range: Option<(u64, u64)>) -> Result<Response, Error> {
        let mut request = self.0.get(url).header("Accept-Encoding", "identity");
        if let Some((start, end)) = range {
            request = request.header("Range", &format!("bytes={start}-{end}"));
        }
        let response = request
            .call()
            .map_err(|error| Error::Http(HttpError::Transport(error)))?;
        match response.status().as_u16() {
            200 => Ok(Response::Full(response.into_body())),
            206 => {
                let (start, end) = range.ok_or(Error::Http(HttpError::ContentRange(
                    "unexpected partial response",
                )))?;
                let values = response.headers().get_all("content-range");
                let mut values = values.iter();
                let value = values
                    .next()
                    .and_then(|value| value.to_str().ok())
                    .ok_or(Error::Http(HttpError::ContentRange("missing")))?;
                if values.next().is_some() {
                    return Err(Error::Http(HttpError::ContentRange("duplicate header")));
                }
                let total = content_range(value, start, end)?;
                let length = end
                    .checked_sub(start)
                    .and_then(|n| n.checked_add(1))
                    .and_then(|n| usize::try_from(n).ok())
                    .ok_or(Error::Http(HttpError::BodyLength))?;
                let mut reader = response.into_body().into_reader();
                let mut bytes = vec![0; length];
                reader
                    .read_exact(&mut bytes)
                    .map_err(|_| Error::Http(HttpError::BodyLength))?;
                let mut extra = [0];
                if reader
                    .read(&mut extra)
                    .map_err(|_| Error::Http(HttpError::BodyLength))?
                    != 0
                {
                    return Err(Error::Http(HttpError::BodyLength));
                }
                Ok(Response::Partial { bytes, total })
            }
            404 => Ok(Response::NotFound),
            416 => Ok(Response::RangeNotSatisfiable),
            status => Ok(Response::Status(status)),
        }
    }
}

fn number(value: &str) -> Result<u64, Error> {
    if value.is_empty()
        || (value.len() > 1 && value.starts_with('0'))
        || !value.bytes().all(|b| b.is_ascii_digit())
    {
        return Err(Error::Http(HttpError::ContentRange("invalid number")));
    }
    value
        .parse()
        .map_err(|_| Error::Http(HttpError::ContentRange("number overflow")))
}

fn content_range(value: &str, expected_start: u64, expected_end: u64) -> Result<u64, Error> {
    let rest = value
        .strip_prefix("bytes ")
        .ok_or(Error::Http(HttpError::ContentRange("wrong grammar")))?;
    let (range, total) = rest
        .split_once('/')
        .ok_or(Error::Http(HttpError::ContentRange("wrong grammar")))?;
    if total.contains('/') {
        return Err(Error::Http(HttpError::ContentRange("wrong grammar")));
    }
    let (start, end) = range
        .split_once('-')
        .ok_or(Error::Http(HttpError::ContentRange("wrong grammar")))?;
    if end.contains('-') {
        return Err(Error::Http(HttpError::ContentRange("wrong grammar")));
    }
    let start = number(start)?;
    let end = number(end)?;
    let total = number(total)?;
    if start != expected_start || end != expected_end || start > end || end >= total {
        return Err(Error::Http(HttpError::ContentRange(
            "does not match request",
        )));
    }
    Ok(total)
}