use std::{cmp::Ordering, error, fmt, str::FromStr, sync::OnceLock};
use crate::types::{Marshal, SqlType, StatBuffer, Unmarshal};
type Limbs = [u64; 4];
const SIGN_BIT: u64 = 1 << 63;
fn limbs(bytes: &[u8; 32]) -> Limbs {
let mut limbs = [0; 4];
for (limb, word) in limbs.iter_mut().zip(bytes.as_chunks::<8>().0) {
*limb = u64::from_le_bytes(*word);
}
limbs
}
fn bytes(limbs: Limbs) -> [u8; 32] {
let mut bytes = [0; 32];
for (word, limb) in bytes.as_chunks_mut::<8>().0.iter_mut().zip(limbs) {
*word = limb.to_le_bytes();
}
bytes
}
fn mul_add(limbs: Limbs, factor: u64, addend: u64) -> Option<Limbs> {
let mut out = [0; 4];
let mut carry = u128::from(addend);
for (out, limb) in out.iter_mut().zip(limbs) {
let value = u128::from(limb) * u128::from(factor) + carry;
*out = value as u64;
carry = value >> 64;
}
(carry == 0).then_some(out)
}
fn div_rem(limbs: Limbs, divisor: u64) -> (Limbs, u64) {
let mut out = [0; 4];
let mut rem = 0_u128;
for i in (0..4).rev() {
let value = (rem << 64) | u128::from(limbs[i]);
out[i] = (value / u128::from(divisor)) as u64;
rem = value % u128::from(divisor);
}
(out, rem as u64)
}
fn negate(limbs: Limbs) -> Limbs {
let mut out = [0; 4];
let mut carry = true;
for (out, limb) in out.iter_mut().zip(limbs) {
let (value, overflow) = (!limb).overflowing_add(u64::from(carry));
*out = value;
carry = overflow;
}
out
}
fn compare(a: Limbs, b: Limbs) -> Ordering {
a.iter().rev().cmp(b.iter().rev())
}
fn write_decimal(mut limbs: Limbs, nonnegative: bool, f: &mut fmt::Formatter) -> fmt::Result {
const CHUNK: u64 = 10_000_000_000_000_000_000; let mut chunks = [0_u64; 5];
let mut count = 0;
loop {
let (quotient, rem) = div_rem(limbs, CHUNK);
chunks[count] = rem;
count += 1;
limbs = quotient;
if limbs == [0; 4] {
break;
}
}
let mut text = chunks[count - 1].to_string();
for chunk in chunks[..count - 1].iter().rev() {
text.push_str(&format!("{chunk:019}"));
}
f.pad_integral(nonnegative, "", &text)
}
fn parse_digits(digits: &str) -> Result<Limbs, Int256Error> {
if digits.is_empty() {
return Err(Int256Error::Empty);
}
let mut limbs = [0; 4];
for byte in digits.bytes() {
if !byte.is_ascii_digit() {
return Err(Int256Error::InvalidDigit);
}
limbs = mul_add(limbs, 10, u64::from(byte - b'0')).ok_or(Int256Error::OutOfRange)?;
}
Ok(limbs)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Int256Error {
Empty,
InvalidDigit,
OutOfRange,
}
impl fmt::Display for Int256Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
Int256Error::Empty => "cannot parse an integer from empty text",
Int256Error::InvalidDigit => "invalid digit found in the integer text",
Int256Error::OutOfRange => "the integer is out of range of the target type",
})
}
}
impl error::Error for Int256Error {}
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Int256([u8; 32]);
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct UInt256([u8; 32]);
impl Int256 {
pub const ZERO: Int256 = Int256([0; 32]);
pub const MIN: Int256 = {
let mut bytes = [0; 32];
bytes[31] = 0x80;
Int256(bytes)
};
pub const MAX: Int256 = {
let mut bytes = [0xff; 32];
bytes[31] = 0x7f;
Int256(bytes)
};
pub const fn from_le_bytes(bytes: [u8; 32]) -> Self {
Int256(bytes)
}
pub const fn to_le_bytes(self) -> [u8; 32] {
self.0
}
pub const fn is_negative(&self) -> bool {
self.0[31] & 0x80 != 0
}
pub fn unsigned_abs(&self) -> UInt256 {
let limbs = limbs(&self.0);
if self.is_negative() {
UInt256(bytes(negate(limbs)))
} else {
UInt256(self.0)
}
}
}
impl UInt256 {
pub const ZERO: UInt256 = UInt256([0; 32]);
pub const MIN: UInt256 = UInt256::ZERO;
pub const MAX: UInt256 = UInt256([0xff; 32]);
pub const fn from_le_bytes(bytes: [u8; 32]) -> Self {
UInt256(bytes)
}
pub const fn to_le_bytes(self) -> [u8; 32] {
self.0
}
pub(crate) fn pow10(n: u32) -> Option<UInt256> {
static POWERS: OnceLock<Vec<UInt256>> = OnceLock::new();
let powers = POWERS.get_or_init(|| {
let mut value = [1, 0, 0, 0];
let mut powers = vec![UInt256(bytes(value))];
while let Some(next) = mul_add(value, 10, 0) {
value = next;
powers.push(UInt256(bytes(value)));
}
powers
});
powers.get(n as usize).copied()
}
pub(crate) fn checked_mul_small(self, factor: u64) -> Option<UInt256> {
mul_add(limbs(&self.0), factor, 0).map(|value| UInt256(bytes(value)))
}
pub(crate) fn div_rem_small(self, divisor: u64) -> (UInt256, u64) {
let (quotient, rem) = div_rem(limbs(&self.0), divisor);
(UInt256(bytes(quotient)), rem)
}
}
impl Int256 {
pub(crate) fn from_sign_magnitude(negative: bool, magnitude: UInt256) -> Option<Int256> {
let magnitude = limbs(&magnitude.0);
if negative {
(compare(magnitude, limbs(&Int256::MIN.0)) != Ordering::Greater)
.then(|| Int256(bytes(negate(magnitude))))
} else {
(magnitude[3] & SIGN_BIT == 0).then(|| Int256(bytes(magnitude)))
}
}
}
macro_rules! from_signed {
( $( $t:ty ),* ) => {
$(
impl From<$t> for Int256 {
fn from(value: $t) -> Self {
let value = i128::from(value);
let mut bytes = [if value < 0 { 0xff } else { 0 }; 32];
bytes[..16].copy_from_slice(&value.to_le_bytes());
Int256(bytes)
}
}
)*
};
}
macro_rules! from_unsigned {
( $( $t:ty ),* ) => {
$(
impl From<$t> for Int256 {
fn from(value: $t) -> Self {
Int256(UInt256::from(value).0)
}
}
impl From<$t> for UInt256 {
fn from(value: $t) -> Self {
let mut bytes = [0; 32];
bytes[..16].copy_from_slice(&u128::from(value).to_le_bytes());
UInt256(bytes)
}
}
)*
};
}
from_signed! { i8, i16, i32, i64, i128 }
from_unsigned! { u8, u16, u32, u64, u128 }
impl TryFrom<Int256> for i128 {
type Error = Int256Error;
fn try_from(value: Int256) -> Result<Self, Self::Error> {
let mut low = [0; 16];
low.copy_from_slice(&value.0[..16]);
let low = i128::from_le_bytes(low);
let sign = if low < 0 { 0xff } else { 0 };
if value.0[16..].iter().all(|&byte| byte == sign) {
Ok(low)
} else {
Err(Int256Error::OutOfRange)
}
}
}
impl TryFrom<UInt256> for u128 {
type Error = Int256Error;
fn try_from(value: UInt256) -> Result<Self, Self::Error> {
if value.0[16..].iter().all(|&byte| byte == 0) {
let mut low = [0; 16];
low.copy_from_slice(&value.0[..16]);
Ok(u128::from_le_bytes(low))
} else {
Err(Int256Error::OutOfRange)
}
}
}
impl TryFrom<UInt256> for Int256 {
type Error = Int256Error;
fn try_from(value: UInt256) -> Result<Self, Self::Error> {
if value.0[31] & 0x80 == 0 {
Ok(Int256(value.0))
} else {
Err(Int256Error::OutOfRange)
}
}
}
impl TryFrom<Int256> for UInt256 {
type Error = Int256Error;
fn try_from(value: Int256) -> Result<Self, Self::Error> {
if value.is_negative() {
Err(Int256Error::OutOfRange)
} else {
Ok(UInt256(value.0))
}
}
}
impl Ord for Int256 {
fn cmp(&self, other: &Self) -> Ordering {
let (mut a, mut b) = (limbs(&self.0), limbs(&other.0));
a[3] ^= SIGN_BIT;
b[3] ^= SIGN_BIT;
compare(a, b)
}
}
impl PartialOrd for Int256 {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for UInt256 {
fn cmp(&self, other: &Self) -> Ordering {
compare(limbs(&self.0), limbs(&other.0))
}
}
impl PartialOrd for UInt256 {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl fmt::Display for Int256 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_decimal(limbs(&self.unsigned_abs().0), !self.is_negative(), f)
}
}
impl fmt::Display for UInt256 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write_decimal(limbs(&self.0), true, f)
}
}
impl fmt::Debug for Int256 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Debug for UInt256 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl FromStr for Int256 {
type Err = Int256Error;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let (negative, digits) = match text.as_bytes().first() {
Some(b'-') => (true, &text[1..]),
Some(b'+') => (false, &text[1..]),
_ => (false, text),
};
let magnitude = parse_digits(digits)?;
if negative {
let min = limbs(&Int256::MIN.0);
if compare(magnitude, min) == Ordering::Greater {
return Err(Int256Error::OutOfRange);
}
Ok(Int256(bytes(negate(magnitude))))
} else if magnitude[3] & SIGN_BIT != 0 {
Err(Int256Error::OutOfRange)
} else {
Ok(Int256(bytes(magnitude)))
}
}
}
impl FromStr for UInt256 {
type Err = Int256Error;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let digits = text.strip_prefix('+').unwrap_or(text);
parse_digits(digits).map(|limbs| UInt256(bytes(limbs)))
}
}
macro_rules! storage {
( $( $t:ident: $k:ident ),* ) => {
$(
impl StatBuffer for $t {
type Buffer = [u8; 32];
fn buffer() -> Self::Buffer {
[0; 32]
}
fn sql_type() -> SqlType {
SqlType::$k
}
}
impl Marshal for $t {
fn marshal(&self, scratch: &mut [u8]) {
scratch.copy_from_slice(&self.0);
}
}
impl Unmarshal<$t> for $t {
fn unmarshal(scratch: &[u8]) -> Self {
let mut bytes = [0; 32];
bytes.copy_from_slice(scratch);
$t(bytes)
}
}
)*
};
}
storage! { Int256: Int256, UInt256: UInt256 }
#[cfg(test)]
mod test {
use super::*;
const INT256_MIN: &str =
"-57896044618658097711785492504343953926634992332820282019728792003956564819968";
const INT256_MAX: &str =
"57896044618658097711785492504343953926634992332820282019728792003956564819967";
const UINT256_MAX: &str =
"115792089237316195423570985008687907853269984665640564039457584007913129639935";
#[test]
fn test_text_round_trip() {
for text in [
INT256_MIN,
INT256_MAX,
"0",
"-1",
"1",
"-170141183460469231731687303715884105729",
] {
let value: Int256 = text.parse().unwrap();
assert_eq!(value.to_string(), text);
}
for text in [
UINT256_MAX,
"0",
"18446744073709551616",
"10000000000000000000",
] {
let value: UInt256 = text.parse().unwrap();
assert_eq!(value.to_string(), text);
}
assert_eq!(INT256_MIN.parse::<Int256>(), Ok(Int256::MIN));
assert_eq!(INT256_MAX.parse::<Int256>(), Ok(Int256::MAX));
assert_eq!(UINT256_MAX.parse::<UInt256>(), Ok(UInt256::MAX));
assert_eq!("+5".parse::<Int256>(), Ok(Int256::from(5)));
assert_eq!(format!("{:>5}", Int256::from(-3)), " -3");
}
#[test]
fn test_parse_errors() {
assert_eq!("".parse::<Int256>(), Err(Int256Error::Empty));
assert_eq!("-".parse::<Int256>(), Err(Int256Error::Empty));
assert_eq!("12a".parse::<UInt256>(), Err(Int256Error::InvalidDigit));
assert_eq!("-5".parse::<UInt256>(), Err(Int256Error::InvalidDigit));
let past_min =
"-57896044618658097711785492504343953926634992332820282019728792003956564819969";
let past_max =
"57896044618658097711785492504343953926634992332820282019728792003956564819968";
let past_umax =
"115792089237316195423570985008687907853269984665640564039457584007913129639936";
assert_eq!(past_min.parse::<Int256>(), Err(Int256Error::OutOfRange));
assert_eq!(past_max.parse::<Int256>(), Err(Int256Error::OutOfRange));
assert_eq!(past_umax.parse::<UInt256>(), Err(Int256Error::OutOfRange));
}
#[test]
fn test_primitive_conversions() {
assert_eq!(Int256::from(-1_i8).to_le_bytes(), [0xff; 32]);
assert_eq!(i128::try_from(Int256::from(i128::MIN)), Ok(i128::MIN));
assert_eq!(i128::try_from(Int256::from(i128::MAX)), Ok(i128::MAX));
assert_eq!(
i128::try_from(Int256::from(u128::MAX)),
Err(Int256Error::OutOfRange)
);
assert_eq!(i128::try_from(Int256::MIN), Err(Int256Error::OutOfRange));
assert_eq!(u128::try_from(UInt256::from(u128::MAX)), Ok(u128::MAX));
assert_eq!(u128::try_from(UInt256::MAX), Err(Int256Error::OutOfRange));
assert_eq!(
UInt256::try_from(Int256::from(-1)),
Err(Int256Error::OutOfRange)
);
assert_eq!(Int256::try_from(UInt256::MAX), Err(Int256Error::OutOfRange));
assert_eq!(Int256::try_from(UInt256::from(9_u8)), Ok(Int256::from(9)));
assert_eq!(Int256::MIN.unsigned_abs().to_string(), &INT256_MIN[1..]);
}
#[test]
fn test_order() {
let mut values: Vec<Int256> = [INT256_MAX, "1", "-1", INT256_MIN, "0"]
.iter()
.map(|t| t.parse().unwrap())
.collect();
values.sort();
let sorted: Vec<String> = values.iter().map(Int256::to_string).collect();
assert_eq!(sorted, [INT256_MIN, "-1", "0", "1", INT256_MAX]);
assert!(UInt256::from(1_u128 << 64) > UInt256::from(u64::MAX));
assert!(UInt256::MAX > UInt256::from(u128::MAX));
}
}