use std::iter::Peekable;
use super::Packed;
use super::packed::significant;
use crate::error::Error;
use crate::limits::{Charge, heap_cost};
pub const LIMB_WORK: u64 = 8;
const LIMBS: usize = 226;
pub const MAX_LIMBS: usize = LIMBS;
const CHUNK: u64 = 10_000_000_000_000_000_000;
struct Wide {
limbs: [u64; LIMBS],
len: usize,
}
impl Wide {
fn zero() -> Self {
Self {
limbs: [0; LIMBS],
len: 0,
}
}
fn clear(&mut self) {
self.limbs.iter_mut().take(self.len).for_each(|l| *l = 0);
self.len = 0;
}
fn used(&self) -> &[u64] {
self.limbs.get(..self.len).unwrap_or_default()
}
fn mul_add(&mut self, mul: u64, add: u64, work: &mut Work<'_>) -> Result<(), Error> {
let n = (self.len + 1).min(LIMBS);
work.step(n)?;
let mut carry = u128::from(add);
for l in self.limbs.iter_mut().take(n) {
let cur = u128::from(*l) * u128::from(mul) + carry;
*l = u64::try_from(cur & u128::from(u64::MAX)).unwrap_or(0);
carry = cur >> 64;
}
self.len = significant(self.limbs.get(..n).unwrap_or_default());
Ok(())
}
fn or_shifted(&mut self, other: &Self, shift: u32, work: &mut Work<'_>) -> Result<(), Error> {
work.step(other.len)?;
let bits = shift % 64;
for (i, l) in other.used().iter().enumerate() {
if let Some(dst) = self.limbs.get_mut(i) {
*dst |= l << bits;
}
if bits > 0
&& let Some(dst) = self.limbs.get_mut(i + 1)
{
*dst |= l >> (64 - bits);
}
}
let reach = (other.len + 1).max(self.len).min(LIMBS);
self.len = significant(self.limbs.get(..reach).unwrap_or_default());
Ok(())
}
}
pub(super) struct Work<'a> {
charge: Option<&'a mut Charge>,
scanned: u64,
}
impl<'a> Work<'a> {
pub(super) fn new(charge: Option<&'a mut Charge>) -> Self {
Self { charge, scanned: 0 }
}
fn scan(&mut self, bytes: usize) {
self.scanned = self
.scanned
.saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX));
}
fn step(&mut self, limbs: usize) -> Result<(), Error> {
let pending = u64::try_from(limbs)
.unwrap_or(u64::MAX)
.saturating_mul(LIMB_WORK);
let done = std::mem::take(&mut self.scanned);
let Some(charge) = self.charge.as_deref().filter(|_| done > 0 || pending > 0) else {
return Ok(());
};
let meter = charge.meter();
meter.count_work(done.saturating_add(pending)).map_err(|e| {
meter.add_work(done);
Error::Limit(e)
})
}
fn finish(&mut self) -> Result<(), Error> {
self.step(0)
}
fn charge_heap(&mut self, limbs: usize) -> Result<(), Error> {
let Some(charge) = self.charge.as_deref_mut() else {
return Ok(());
};
let bytes = u64::try_from(limbs.saturating_mul(8)).unwrap_or(u64::MAX);
Ok(charge.grow(heap_cost(bytes))?)
}
}
#[derive(Clone, Copy)]
enum Unit {
Char(char),
Byte,
}
impl Unit {
fn len(self) -> usize {
match self {
Self::Char(c) => c.len_utf8(),
Self::Byte => 1,
}
}
}
fn units(bytes: &[u8]) -> impl Iterator<Item = Unit> + '_ {
bytes.utf8_chunks().flat_map(|chunk| {
chunk
.valid()
.chars()
.map(Unit::Char)
.chain(chunk.invalid().iter().map(|_| Unit::Byte))
})
}
fn digit(u: Unit) -> Option<u8> {
match u {
Unit::Char(c) => crate::tables::nd_digit(c),
Unit::Byte => None,
}
}
fn next<I: Iterator<Item = Unit>>(it: &mut Peekable<I>, work: &mut Work<'_>) -> Option<Unit> {
let u = it.next()?;
work.scan(u.len());
Some(u)
}
fn digits<I: Iterator<Item = Unit>>(
it: &mut Peekable<I>,
value: &mut Wide,
work: &mut Work<'_>,
) -> Result<Option<usize>, Error> {
value.clear();
let (mut count, mut chunk, mut chunk_len) = (0usize, 0u64, 0u32);
while let Some(d) = it.peek().copied().and_then(digit) {
next(it, work);
count += 1;
if count > super::PY_INT_MAX_STR_DIGITS {
return Ok(None);
}
chunk = chunk * 10 + u64::from(d);
chunk_len += 1;
if chunk_len == 19 {
value.mul_add(CHUNK, chunk, work)?;
(chunk, chunk_len) = (0, 0);
}
}
if chunk_len > 0 {
value.mul_add(10_u64.pow(chunk_len), chunk, work)?;
}
Ok(Some(count))
}
pub(super) fn parse_packed(raw: &[u8], mut work: Work<'_>) -> Result<Option<Packed>, Error> {
let got = pack(raw, &mut work);
let rest = work.finish();
let packed = got?;
rest?;
let Some(packed) = packed else {
return Ok(None);
};
if packed.len > 2 {
work.charge_heap(packed.len)?;
}
Ok(Some(Packed::from_limbs(packed.used())))
}
fn pack(raw: &[u8], work: &mut Work<'_>) -> Result<Option<Wide>, Error> {
let mut it = units(raw).peekable();
let mut packed = Wide::zero();
let mut group = Wide::zero();
for (i, shift) in [48u32, 32, 16].into_iter().enumerate() {
match digits(&mut it, &mut group, work)? {
None | Some(0) => return Ok(None),
Some(_) => {}
}
if i < 2 && !matches!(next(&mut it, work), Some(Unit::Char('.'))) {
return Ok(None);
}
packed.or_shifted(&group, shift, work)?;
}
let ty = match next(&mut it, work) {
None => 3u64,
Some(unit) => {
let ty = match unit {
Unit::Char('a' | 'A') => 0,
Unit::Char('b' | 'B') => 1,
Unit::Char('c' | 'C') => 2,
Unit::Char('f' | 'F') => 3,
Unit::Char('p' | 'P') => 4,
Unit::Char('x' | 'X') => 5,
_ => 255,
};
if digits(&mut it, &mut group, work)?.is_none() {
return Ok(None);
}
packed.or_shifted(&group, 0, work)?;
ty
}
};
group.clear();
group.mul_add(1, ty, work)?;
packed.or_shifted(&group, 8, work)?;
Ok(Some(packed))
}