cryptix-bigint 0.1.0

A bigint library for cryptix
Documentation
#![no_std]
#![allow(incomplete_features)]
#![feature(generic_const_exprs)]
#![feature(bigint_helper_methods)]
#![feature(const_bigint_helper_methods)]
#![feature(const_trait_impl)]
#![feature(array_windows)]
#![feature(const_mut_refs)]
#![feature(const_slice_index)]
#![feature(core_intrinsics)]
#![feature(const_transmute_copy)]
#![feature(const_refs_to_cell)]

pub mod ops;
pub mod property;
pub mod utils;
pub mod convert;
pub mod digit;

pub use hex_literal;

use core::ops::{Deref, DerefMut};

/// Stack-based data structure for big unsigned integers
/// 
/// - The inner structure is an fixed-length array, no memory overhead
/// - It stores number in little-endian, which means lower digits first
/// - Typically T is a primary integer type
pub struct BigUInt<T, const LEN: usize>(pub [T; LEN]);

impl<T: Clone + Copy, const LEN: usize> Clone for BigUInt<T, LEN> {
    fn clone(&self) -> Self {
        BigUInt(self.0)
    }
}

impl<T: Copy, const LEN: usize> Copy for BigUInt<T, LEN> { }

impl<T: Copy, const LEN: usize> Deref for BigUInt<T, LEN> {
    type Target = [T; LEN];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T: Copy, const LEN: usize> DerefMut for BigUInt<T, LEN> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0   
    }
}


impl<T: Copy, const LEN: usize, const N: usize> From<[BigUInt<T, LEN>; N]> for BigUInt<T, {N * LEN}>
where
    [(); N * LEN]: ,
{
    fn from(value: [BigUInt<T, LEN>; N]) -> Self {
         /* # Safety
         * 
         * This operation is safe:
         * 
         * 1. Self is just a wrapper over `[T; LEN * N]`, while value has type `[[T; LEN]; N]`, 
         *    they have exactly the same memory layout and alignment
         * 2. T is copyable
         */
        unsafe {
            core::intrinsics::transmute_unchecked(value)
        }
    }
}

impl<T: Copy, const LEN: usize, const N: usize> From<BigUInt<T, {N * LEN}>> for [BigUInt<T, LEN>; N] 
where
    [(); N * LEN]: ,
{
    fn from(value: BigUInt<T, {N * LEN}>) -> Self {
        /* # Safety
         * 
         * This operation is safe since Self is just a wrapper over `[[T; LEN]; N]`, while 
         * value has type `[T; LEN * N]`, they have exactly the same memory layout and alignment
         */
        unsafe {
            core::intrinsics::transmute_unchecked(value)
        }
    }
}

impl<T: Copy + Default, const LEN: usize> From<T> for BigUInt<T, LEN> {
    fn from(value: T) -> Self {
        let mut out = Self([T::default(); LEN]);
        out[0] = value;
        out
    }
}

impl<T: Copy + Default, const LEN: usize> From<&[T]> for BigUInt<T, LEN> {
    fn from(value: &[T]) -> Self {
        let mut output = [T::default(); LEN];
        output.copy_from_slice(value);
        BigUInt(output)
    }
}