use std::{array::from_fn, cmp::Ordering};
use crate::{
Encoded, Level, Type,
encode::{Plan, compress_into_timed, compress_payload_into_timed, plan, raw, raw_into, shrink},
};
const N: usize = Level::ALL.len();
const PRIOR_SPEED_LI: [f64; N] = [2.5e8, 1.2e8, 5.0e7, 2.0e7, 4.0e6];
const PRIOR_RATIO_LI: [f64; N] = [0.60, 0.52, 0.45, 0.40, 0.35];
const PRIOR_ODDS_LI: [f64; N] = prior_odds();
const ALPHA: f64 = 0.2;
const MAX_SHIFT: f64 = 4.0;
const MIN_SPEED: f64 = 1.0;
const MAX_SPEED: f64 = 1e12;
const RATIO_MIN: f64 = 1e-6;
const RATIO_MAX: f64 = 1.0 - RATIO_MIN;
const MIN_SPEEDUP: f64 = 1.05;
const MAX_COST: f64 = 1.0 / MIN_SPEEDUP;
const EXPLORE_INTERVAL: u32 = 64;
const fn prior_odds() -> [f64; N] {
let mut out = [0.0; N];
let mut i = 0;
while i < N {
let r = PRIOR_RATIO_LI[i];
out[i] = r / (1.0 - r);
i += 1;
}
out
}
#[inline]
fn ratio_to_odds(ratio: f64) -> f64 {
let r = ratio.clamp(RATIO_MIN, RATIO_MAX);
r / (1.0 - r)
}
#[inline]
fn odds_to_ratio(odds: f64) -> f64 {
if !odds.is_finite() {
return RATIO_MAX;
}
let r = odds / (1.0 + odds);
r.clamp(RATIO_MIN, RATIO_MAX)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Choice {
Off,
Level(Level),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Stat {
pub level: Level,
pub speed: f64,
pub ratio: f64,
pub sample_cnt: u32,
}
#[derive(Debug, Clone)]
pub struct Adaptive {
speed_li: [f64; N],
ratio_li: [f64; N],
sample_li: [u32; N],
step: u32,
explore_up: bool,
}
impl Default for Adaptive {
fn default() -> Self {
Self::new()
}
}
impl Adaptive {
#[must_use]
pub const fn new() -> Self {
Self {
speed_li: PRIOR_SPEED_LI,
ratio_li: PRIOR_RATIO_LI,
sample_li: [0; N],
step: 0,
explore_up: true,
}
}
#[must_use]
pub fn choice(&self, net_speed: u64) -> Choice {
if net_speed == 0 {
return Choice::Level(Level::Balanced);
}
let net = net_speed as f64;
let mut best_cost = MAX_COST;
let mut best = Choice::Off;
for ((level, speed), ratio) in Level::ALL.into_iter().zip(self.speed_li).zip(self.ratio_li) {
let cost = net / speed + ratio;
if cost < best_cost {
best_cost = cost;
best = Choice::Level(level);
}
}
best
}
fn pick(&mut self, net_speed: u64, observable: bool) -> Choice {
let base = self.choice(net_speed);
if net_speed == 0 || !observable {
return base;
}
self.step += 1;
if self.step < EXPLORE_INTERVAL {
return base;
}
self.step = 0;
let min_speed = net_speed as f64 * MIN_SPEEDUP;
let feasible = |idx: usize| self.speed_li[idx] * MAX_SHIFT >= min_speed;
match base {
Choice::Off => {
if feasible(0) {
Choice::Level(Level::Fastest)
} else {
Choice::Off
}
}
Choice::Level(cur) => {
let i = cur.index();
let lo = i.checked_sub(1).filter(|&j| feasible(j));
let hi = (i + 1 < N && feasible(i + 1)).then_some(i + 1);
let probe = match (lo, hi) {
(Some(a), Some(b)) => match self.sample_li[a].cmp(&self.sample_li[b]) {
Ordering::Less => a,
Ordering::Greater => b,
Ordering::Equal => {
self.explore_up = !self.explore_up;
if self.explore_up { b } else { a }
}
},
(Some(j), None) | (None, Some(j)) => j,
(None, None) => return Choice::Level(cur),
};
Choice::Level(Level::ALL[probe])
}
}
}
#[must_use]
pub fn encode(&mut self, data: &[u8], net_speed: u64) -> Vec<u8> {
match plan(data, |observable| self.decide(net_speed, observable)) {
Plan::Raw => raw(data),
Plan::Zstd(level) => {
let mut out = Vec::new();
let (compressed, elapsed) = compress_into_timed(data, level, &mut out);
if compressed {
self.record(level, data.len(), out.len(), elapsed);
} else {
raw_into(&mut out, data);
}
shrink(&mut out);
out
}
}
}
#[must_use]
pub fn encode_owned(&mut self, data: Vec<u8>, net_speed: u64) -> Encoded {
match plan(&data, |observable| self.decide(net_speed, observable)) {
Plan::Raw => Encoded::raw(data),
Plan::Zstd(level) => {
let mut out = Vec::new();
let (compressed, elapsed) = compress_payload_into_timed(&data, level, &mut out);
if compressed {
self.record(level, data.len(), out.len() + 1, elapsed);
shrink(&mut out);
Encoded::zstd(out)
} else {
Encoded::raw(data)
}
}
}
}
pub fn encode_into(&mut self, data: &[u8], net_speed: u64, out: &mut Vec<u8>) -> Type {
match plan(data, |observable| self.decide(net_speed, observable)) {
Plan::Raw => {
raw_into(out, data);
Type::Raw
}
Plan::Zstd(level) => {
let (compressed, elapsed) = compress_into_timed(data, level, out);
if compressed {
self.record(level, data.len(), out.len(), elapsed);
Type::Zstd
} else {
raw_into(out, data);
Type::Raw
}
}
}
}
#[inline]
fn decide(&mut self, net_speed: u64, observable: bool) -> Option<Level> {
match self.pick(net_speed, observable) {
Choice::Off => None,
Choice::Level(level) => Some(level),
}
}
fn record(&mut self, level: Level, raw_len: usize, wire_len: usize, elapsed: Option<f64>) {
if let Some(elapsed) = elapsed
&& elapsed > 0.0
{
self.observe(
level,
raw_len as f64 / elapsed,
wire_len as f64 / (raw_len + 1) as f64,
);
}
}
fn scale_unmeasured(
&mut self,
range: impl Iterator<Item = usize>,
speed_scale: f64,
odds_scale: f64,
) {
for j in range {
if self.sample_li[j] != 0 {
break;
}
self.speed_li[j] = (PRIOR_SPEED_LI[j] * speed_scale).clamp(MIN_SPEED, MAX_SPEED);
self.ratio_li[j] = odds_to_ratio(PRIOR_ODDS_LI[j] * odds_scale);
}
}
pub fn observe(&mut self, level: Level, speed: f64, ratio: f64) {
if !speed.is_finite() || speed <= 0.0 || !ratio.is_finite() {
return;
}
let i = level.index();
let est = self.speed_li[i];
let clamped = speed.clamp(
(est / MAX_SHIFT).max(MIN_SPEED),
(est * MAX_SHIFT).min(MAX_SPEED),
);
let n = self.sample_li[i].saturating_add(1);
self.sample_li[i] = n;
let weight = (1.0 / f64::from(n)).clamp(ALPHA, 0.5);
self.speed_li[i] += (clamped - est) * weight;
self.ratio_li[i] += (ratio.clamp(0.0, 1.0) - self.ratio_li[i]) * weight;
let speed_scale = self.speed_li[i] / PRIOR_SPEED_LI[i];
let odds_scale = ratio_to_odds(self.ratio_li[i]) / PRIOR_ODDS_LI[i];
self.scale_unmeasured((0..i).rev(), speed_scale, odds_scale);
self.scale_unmeasured((i + 1)..N, speed_scale, odds_scale);
for j in (0..i).rev() {
self.speed_li[j] = self.speed_li[j].max(self.speed_li[j + 1]);
self.ratio_li[j] = self.ratio_li[j].max(self.ratio_li[j + 1]);
}
for j in (i + 1)..N {
self.speed_li[j] = self.speed_li[j].min(self.speed_li[j - 1]);
self.ratio_li[j] = self.ratio_li[j].min(self.ratio_li[j - 1]);
}
}
#[must_use]
pub fn stats(&self) -> [Stat; N] {
from_fn(|i| Stat {
level: Level::ALL[i],
speed: self.speed_li[i],
ratio: self.ratio_li[i],
sample_cnt: self.sample_li[i],
})
}
}