use core::fmt;
use crate::{DecodeError, MalformedError};
#[cfg(verus_keep_ghost)]
use vstd::prelude::*;
#[cfg(verus_keep_ghost)]
#[path = "../specs/arithmetic.rs"]
pub(crate) mod arithmetic_spec;
#[cfg(verus_keep_ghost)]
#[macro_use]
#[path = "../proofs/production_impl/arithmetic.rs"]
mod arithmetic_proofs;
#[cfg(verus_keep_ghost)]
#[path = "../proofs/shared/arithmetic.rs"]
mod arithmetic_shared;
#[cfg(verus_keep_ghost)]
#[path = "../proofs/spec_properties/arithmetic.rs"]
mod arithmetic_properties;
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) const MIN_INTERVAL: u32 = 0x8000;
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) const INTEGER_CONTEXT_COUNT: usize = 512;
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) const MAX_IAID_CODE_LENGTH: u8 = 31;
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) const RASTER_SIGNAL_EOF: u8 = 2;
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) const RASTER_SIGNAL_OVERFLOW: u8 = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C, align(8))]
#[cfg_attr(verus_keep_ghost, verus_verify)]
struct QeState {
qe: u16,
next_mps: u8,
next_lps: u8,
switch_mps: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) struct ArithmeticContext {
pub(crate) packed: u8,
}
impl ArithmeticContext {
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
ensures
out.packed == 0,
arithmetic_spec::context_index(out) == 0,
arithmetic_spec::context_mps(out) == 0,
arithmetic_spec::context_valid(out),
))]
#[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
pub(crate) const fn new() -> Self {
Self { packed: 0 }
}
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
ensures out.packed == packed,
))]
#[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
#[inline]
pub(crate) const fn from_packed(packed: u8) -> Self {
Self { packed }
}
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
ensures out == self.packed,
))]
#[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
#[inline]
pub(crate) const fn packed(self) -> u8 {
self.packed
}
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
ensures match out {
Ok(context) =>
state_index < 47
&& mps <= 1
&& arithmetic_spec::context_valid(context)
&& arithmetic_spec::context_index(context) == state_index
&& arithmetic_spec::context_mps(context) == mps,
Err(error) => (state_index >= 47 || mps > 1)
&& error == ArithmeticError::InvalidContextState { state_index, mps },
},
))]
#[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
pub(crate) fn from_state(state_index: u8, mps: u8) -> Result<Self, ArithmeticError> {
if state_index >= 47 || mps > 1 {
return Err(ArithmeticError::InvalidContextState { state_index, mps });
}
let packed = (state_index << 1) | mps;
#[cfg(verus_keep_ghost)]
proof! {
assert(packed == add(mul(state_index, 2), mps)) by (bit_vector)
requires state_index < 47, mps <= 1, packed == ((state_index << 1) | mps);
}
Ok(Self { packed })
}
#[cfg_attr(verus_keep_ghost, verus_spec(
requires state_index < 47, mps <= 1,
ensures
arithmetic_spec::context_valid(*final(self)),
arithmetic_spec::context_index(*final(self)) == state_index,
arithmetic_spec::context_mps(*final(self)) == mps,
))]
#[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
#[inline]
pub(crate) fn set_state_and_mps(&mut self, state_index: u8, mps: u8) {
let packed = (state_index << 1) | mps;
#[cfg(verus_keep_ghost)]
proof! {
assert(packed == add(mul(state_index, 2), mps)) by (bit_vector)
requires state_index < 47, mps <= 1, packed == ((state_index << 1) | mps);
}
self.packed = packed;
}
#[cfg_attr(verus_keep_ghost, verus_spec(
ensures
final(self).packed == 0,
arithmetic_spec::context_index(*final(self)) == 0,
arithmetic_spec::context_mps(*final(self)) == 0,
arithmetic_spec::context_valid(*final(self)),
))]
#[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
pub(crate) fn reset(&mut self) {
*self = Self::new();
}
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
ensures out == arithmetic_spec::context_index(self),
))]
#[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
#[inline]
pub(crate) const fn state_index(self) -> u8 {
#[cfg(verus_keep_ghost)]
proof! {
let p = self.packed;
assert((p >> 1) == p / 2u8) by (bit_vector);
}
self.packed >> 1
}
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
ensures out == arithmetic_spec::context_mps(self),
))]
#[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
#[inline]
pub(crate) const fn mps(self) -> u8 {
#[cfg(verus_keep_ghost)]
proof! {
let p = self.packed;
assert((p & 1) == p % 2u8) by (bit_vector);
}
self.packed & 1
}
}
#[cfg_attr(verus_keep_ghost, verus_verify)]
impl Default for ArithmeticContext {
fn default() -> Self {
Self::new()
}
}
#[cfg_attr(verus_keep_ghost, verus_spec(
ensures
final(contexts)@.len() == old(contexts)@.len(),
forall|index: int| 0 <= index < final(contexts)@.len() ==>
arithmetic_spec::context_valid(final(contexts)@[index]),
forall|index: int| 0 <= index < final(contexts)@.len() ==>
arithmetic_spec::context_index(final(contexts)@[index]) == 0
&& arithmetic_spec::context_mps(final(contexts)@[index]) == 0,
))]
pub(crate) fn reset_contexts(contexts: &mut [ArithmeticContext]) {
let mut index = 0;
#[cfg_attr(verus_keep_ghost, verus_spec(
invariant
0 <= index <= contexts@.len(),
contexts@.len() == old(contexts)@.len(),
forall|completed: int| 0 <= completed < index ==>
arithmetic_spec::context_valid(contexts@[completed]),
forall|completed: int| 0 <= completed < index ==>
arithmetic_spec::context_index(contexts@[completed]) == 0
&& arithmetic_spec::context_mps(contexts@[completed]) == 0,
decreases contexts@.len() - index,
))]
while index < contexts.len() {
contexts[index] = ArithmeticContext::new();
index += 1;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) struct ArithmeticMarker {
pub(crate) offset: usize,
pub(crate) code: u8,
}
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) enum ArithmeticError {
Malformed(MalformedError),
InvalidContextState { state_index: u8, mps: u8 },
InsufficientContexts { required: usize, actual: usize },
InvalidIaidCodeLength(u8),
}
impl fmt::Display for ArithmeticError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Malformed(error) => error.fmt(formatter),
Self::InvalidContextState { state_index, mps } => write!(
formatter,
"invalid arithmetic context state I={state_index}, MPS={mps}"
),
Self::InsufficientContexts { required, actual } => write!(
formatter,
"arithmetic decoding requires {required} contexts, but {actual} were supplied"
),
Self::InvalidIaidCodeLength(length) => {
write!(formatter, "unsupported IAID code length {length}")
}
}
}
}
impl std::error::Error for ArithmeticError {}
#[cfg_attr(verus_keep_ghost, verus_verify)]
impl From<MalformedError> for ArithmeticError {
fn from(error: MalformedError) -> Self {
Self::Malformed(error)
}
}
impl ArithmeticError {
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
ensures out == arithmetic_spec::decode_error(self),
))]
pub(crate) fn into_decode(self) -> DecodeError {
match self {
Self::Malformed(error) => DecodeError::Malformed(error),
Self::InvalidContextState { state_index, mps } => {
DecodeError::Malformed(MalformedError::InvalidArithmeticContextState {
state_index,
mps,
})
}
Self::InsufficientContexts { required, actual } => {
DecodeError::Malformed(MalformedError::InsufficientArithmeticContexts {
required,
actual,
})
}
Self::InvalidIaidCodeLength(length) => {
DecodeError::Malformed(MalformedError::InvalidIaidCodeLength(length))
}
}
}
}
#[cfg_attr(verus_keep_ghost, verus_verify)]
impl From<ArithmeticError> for DecodeError {
fn from(error: ArithmeticError) -> Self {
error.into_decode()
}
}
#[cfg(verus_keep_ghost)]
verus! {
impl vstd::std_specs::convert::FromSpecImpl<MalformedError> for ArithmeticError {
open spec fn obeys_from_spec() -> bool { true }
closed spec fn from_spec(error: MalformedError) -> ArithmeticError {
ArithmeticError::Malformed(error)
}
}
impl vstd::std_specs::convert::FromSpecImpl<ArithmeticError> for DecodeError {
open spec fn obeys_from_spec() -> bool { true }
closed spec fn from_spec(error: ArithmeticError) -> DecodeError {
arithmetic_spec::decode_error(error)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) enum ArithmeticInteger {
Value(i64),
OutOfBand,
}
#[derive(Debug)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) struct ArithmeticDecoder<'a> {
pub(crate) bytes: &'a [u8],
pub(crate) byte_position: usize,
pub(crate) current_byte: u8,
pub(crate) code: u32,
pub(crate) interval: u32,
pub(crate) bit_count: u8,
pub(crate) marker: Option<ArithmeticMarker>,
}
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
ensures out == arithmetic_spec::eof_error(offset, needed, remaining),
))]
fn unexpected_eof(offset: usize, needed: usize, remaining: usize) -> ArithmeticError {
let Ok(offset) = u64::try_from(offset) else {
return ArithmeticError::Malformed(MalformedError::IntegerOverflow);
};
let Ok(needed) = u64::try_from(needed) else {
return ArithmeticError::Malformed(MalformedError::IntegerOverflow);
};
let Ok(remaining) = u64::try_from(remaining) else {
return ArithmeticError::Malformed(MalformedError::IntegerOverflow);
};
ArithmeticError::Malformed(MalformedError::UnexpectedEof {
offset,
needed,
remaining,
})
}
mod certainty;
mod certified_integers;
mod decoding;
mod fast;
mod integers;
mod lps_tables;
mod probability;
mod refill;
#[cfg(verus_keep_ghost)]
pub(crate) use certainty::certainty_spec;
pub(crate) use certainty::PrefixCertainty;
use probability::QE_STATES;
#[allow(unused_imports)]
pub(crate) use probability::{NEXT_MPS_PACKED, QE_PACKED_VALS};
#[cfg(test)]
mod tests;