jitter-backoff 11.2.0

Zero-dependency exponential backoff, full/equal/decorrelated jitter, deadline retry budgets, Retry-After header parsing, and synchronous retry execution.
Documentation
use super::*;

/// Parses an unsigned ASCII decimal integer into `u64` without locale or generic overhead.
///
/// # Arguments
///
/// - `&[u8]` - Non-empty ASCII digit slice.
///
/// # Returns
///
/// - `Option<u64>` - Parsed value or `None` on non-digit or overflow.
#[inline(always)]
fn parse_u64_ascii(bytes: &[u8]) -> Option<u64> {
    if bytes.is_empty() {
        return None;
    }
    let mut acc: u64 = 0;
    for &b in bytes {
        let d: u8 = b.wrapping_sub(b'0');
        if d > 9 {
            return None;
        }
        acc = acc.checked_mul(10)?.checked_add(u64::from(d))?;
    }
    Some(acc)
}

/// Parses a fixed-width two-digit ASCII integer (`00..=99`).
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `Option<u64>` - Parsed integer or `None` if invalid.
#[inline(always)]
fn parse_small_u64_ascii(bytes: &[u8]) -> Option<u64> {
    if bytes.is_empty() || bytes.len() > 4 {
        return None;
    }
    let mut acc: u64 = 0;
    for &b in bytes {
        let d: u8 = b.wrapping_sub(b'0');
        if d > 9 {
            return None;
        }
        acc = acc * 10 + u64::from(d);
    }
    Some(acc)
}

/// Parses an RFC 9110 `Retry-After` header value (`delay-seconds` or IMF-fixdate HTTP-date).
///
/// # Arguments
///
/// - `&str` - Raw `Retry-After` header value.
/// - `u64` - Current Unix timestamp in seconds (used when value is an HTTP-date).
///
/// # Returns
///
/// - `Option<Duration>` - Parsed delay duration, or `None` if syntactically invalid.
#[inline]
pub fn parse_retry_after_at(value: &str, now_unix_secs: u64) -> Option<Duration> {
    let trimmed: &str = value.trim();
    if trimmed.is_empty() {
        return None;
    }
    if let Some(secs) = parse_u64_ascii(trimmed.as_bytes()) {
        return Some(Duration::from_secs(secs));
    }
    let target_secs: u64 = parse_imf_fixdate(trimmed)?;
    Some(Duration::from_secs(
        target_secs.saturating_sub(now_unix_secs),
    ))
}

/// Parses an RFC 9110 `Retry-After` header value relative to the current system clock.
///
/// # Arguments
///
/// - `&str` - Raw `Retry-After` header value.
///
/// # Returns
///
/// - `Option<Duration>` - Parsed delay duration, or `None` if invalid.
#[inline]
pub fn parse_retry_after(value: &str) -> Option<Duration> {
    let trimmed: &str = value.trim();
    if trimmed.is_empty() {
        return None;
    }
    if let Some(secs) = parse_u64_ascii(trimmed.as_bytes()) {
        return Some(Duration::from_secs(secs));
    }
    let target_secs: u64 = parse_imf_fixdate(trimmed)?;
    let now_secs: u64 = match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(d) => d.as_secs(),
        Err(_) => 0,
    };
    Some(Duration::from_secs(target_secs.saturating_sub(now_secs)))
}

/// Parses an IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`) into Unix epoch seconds.
///
/// # Arguments
///
/// - `&str` - Trimmed HTTP-date string.
///
/// # Returns
///
/// - `Option<u64>` - Unix epoch seconds or `None` on malformed input.
#[inline]
fn parse_imf_fixdate(input: &str) -> Option<u64> {
    let (_, rest): (&str, &str) = input.split_once(',')?;
    let mut parts: SplitAsciiWhitespace<'_> = rest.split_ascii_whitespace();
    let day: u32 = parse_small_u64_ascii(parts.next()?.as_bytes())? as u32;
    let mon_str: &str = parts.next()?;
    let year: i64 = parse_small_u64_ascii(parts.next()?.as_bytes())? as i64;
    let time_str: &str = parts.next()?;
    let tz: &str = parts.next()?;
    if parts.next().is_some() || !tz.eq_ignore_ascii_case("GMT") {
        return None;
    }
    let month: u32 = match mon_str.as_bytes() {
        b"Jan" => 1,
        b"Feb" => 2,
        b"Mar" => 3,
        b"Apr" => 4,
        b"May" => 5,
        b"Jun" => 6,
        b"Jul" => 7,
        b"Aug" => 8,
        b"Sep" => 9,
        b"Oct" => 10,
        b"Nov" => 11,
        b"Dec" => 12,
        _ => return None,
    };
    let mut tparts: Split<'_, char> = time_str.split(':');
    let hour: u64 = parse_small_u64_ascii(tparts.next()?.as_bytes())?;
    let minute: u64 = parse_small_u64_ascii(tparts.next()?.as_bytes())?;
    let second: u64 = parse_small_u64_ascii(tparts.next()?.as_bytes())?;
    if tparts.next().is_some()
        || !(1..=31).contains(&day)
        || year < 1970
        || hour > 23
        || minute > 59
        || second > 60
    {
        return None;
    }
    let days: i64 = days_from_civil(year, month, day);
    if days < 0 {
        return None;
    }
    Some((days as u64) * 86_400 + hour * 3600 + minute * 60 + second)
}

/// Converts a proleptic Gregorian `(year, month, day)` to days since `1970-01-01` (Howard Hinnant).
///
/// # Arguments
///
/// - `i64` - Full year (e.g. `2026`).
/// - `u32` - Month `1..=12`.
/// - `u32` - Day of month `1..=31`.
///
/// # Returns
///
/// - `i64` - Signed days since Unix epoch.
#[inline(always)]
fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
    let y: i64 = if month <= 2 { year - 1 } else { year };
    let era: i64 = if y >= 0 { y } else { y - 399 } / 400;
    let yoe: u32 = (y - era * 400) as u32;
    let m_adj: u32 = if month > 2 { month - 3 } else { month + 9 };
    let doy: u32 = (153 * m_adj + 2) / 5 + day - 1;
    let doe: u32 = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + i64::from(doe) - 719_468
}