use bnum::{Int,cast::As,n};

pub(crate)const BNUM_DIGIT_WIDTH:usize=8;
const DIGIT_SHIFT:u32=BNUM_DIGIT_WIDTH.ilog2();

#[derive(Clone,Copy,Default,Hash,PartialEq,Eq,PartialOrd,Ord)]
/// A Fixed point number for which multiply operations widen the bits in the output. (when the wide-mul feature is enabled)
/// N is the number of u8s to use
/// F is the number of fractional bits (currently always N*8/2)
pub struct Fixed<const N:usize,const F:usize>{
	bits:Int<N>,
}

impl<const N:usize,const F:usize> Fixed<N,F>{
	pub const MAX:Self=Self::from_bits(Int::<N>::MAX);
	pub const MIN:Self=Self::from_bits(Int::<N>::MIN);
	pub const ZERO:Self=Self::from_bits(n!(0));
	pub const EPSILON:Self=Self::from_bits(n!(1));
	pub const NEG_EPSILON:Self=Self::from_bits(n!(-1));
	pub const ONE:Self=Self::from_bits(n!(1).shl(F as u32));
	pub const TWO:Self=Self::from_bits(n!(2).shl(F as u32));
	pub const HALF:Self=Self::from_bits(n!(1).shl(F as u32-1));
	pub const NEG_ONE:Self=Self::from_bits(n!(-1).shl(F as u32));
	pub const NEG_TWO:Self=Self::from_bits(n!(-2).shl(F as u32));
	pub const NEG_HALF:Self=Self::from_bits(n!(-1).shl(F as u32-1));
}
impl<const N:usize,const F:usize> Fixed<N,F>{
	#[inline]
	pub const fn from_bits(bits:Int::<N>)->Self{
		Self{
			bits,
		}
	}
	#[inline]
	pub const fn to_bits(self)->Int<N>{
		self.bits
	}
	#[inline]
	pub const fn as_bits(&self)->&Int<N>{
		&self.bits
	}
	#[inline]
	pub const fn as_bits_mut(&mut self)->&mut Int<N>{
		&mut self.bits
	}
	#[inline]
	pub const fn from_u64(value:u64)->Self{
		let mut digits=Self::ZERO;
		let bytes=value.to_ne_bytes();
		let mut digit=0;
		while digit<N&&digit<bytes.len(){
			digits.as_bits_mut().as_bytes_mut()[digit]=bytes[digit];
			digit+=1;
		}
		digits
	}
	#[inline]
	pub const fn is_zero(self)->bool{
		self.bits.is_zero()
	}
	#[inline]
	pub const fn is_negative(self)->bool{
		self.bits.is_negative()
	}
	#[inline]
	pub const fn is_positive(self)->bool{
		self.bits.is_positive()
	}
	#[inline]
	pub const fn abs(self)->Self{
		Self::from_bits(self.bits.abs())
	}
	#[inline]
	pub const fn midpoint(self,other:Self)->Self{
		Self::from_bits(self.bits.midpoint(other.bits))
	}
	#[inline]
	pub const fn min(self,other:Self)->Self{
		Self::from_bits(self.bits.min(other.bits))
	}
	#[inline]
	pub const fn max(self,other:Self)->Self{
		Self::from_bits(self.bits.max(other.bits))
	}
	/// return the result of self*sign(other)
	#[inline]
	pub const fn mul_sign<const N1:usize,const F1:usize>(self,other:Fixed<N1,F1>)->Self{
		if other.is_negative(){
			Self::from_bits(self.bits.neg())
		}else if other.is_zero(){
			Fixed::ZERO
		}else{
			self
		}
	}
	/// return the result of self/sign(other) (divide by zero does not change the sign)
	#[inline]
	pub const fn div_sign<const N1:usize,const F1:usize>(self,other:Fixed<N1,F1>)->Self{
		if other.is_negative(){
			Self::from_bits(self.bits.neg())
		}else{
			self
		}
	}
}
impl<const F:usize> Fixed<{64/BNUM_DIGIT_WIDTH},F>{
	/// My old code called this function everywhere so let's provide it
	#[inline]
	pub const fn raw(value:i64)->Self{
		Self::from_bits(Int::from_bytes(value.to_ne_bytes()))
	}
	#[inline]
	pub const fn to_raw(self)->i64{
		i64::from_le_bytes(self.to_bits().to_bytes())
	}
}

macro_rules! impl_from{
	($($from:ty),*)=>{
		$(
		impl<const N:usize,const F:usize> From<$from> for Fixed<N,F>{
			#[inline]
			fn from(value:$from)->Self{
				Self::from_bits(value.as_::<Int::<{N}>>()<<F as u32)
			}
		}
		)*
	};
}
impl_from!(
	u8,u16,u32,u64,u128,usize,
	i8,i16,i32,i64,i128,isize
);

impl<const N:usize,const F:usize> std::ops::Neg for Fixed<N,F>{
	type Output=Self;
	#[inline]
	fn neg(self)->Self{
		Self::from_bits(self.bits.neg())
	}
}
impl<const N:usize,const F:usize> std::iter::Sum for Fixed<N,F>{
	#[inline]
	fn sum<I:Iterator<Item=Self>>(iter:I)->Self{
		let mut sum=Self::ZERO;
		for elem in iter{
			sum+=elem;
		}
		sum
	}
}

macro_rules! impl_into_float{
	($output:ty,$unsigned:ty,$mantissa_msb:expr,$bias:expr) => {
		impl<const N:usize,const F:usize> Into<$output> for Fixed<N,F>{
			#[inline]
			fn into(self)->$output{
				let unsigned=self.bits.unsigned_abs();
				// most_significant_bit is the "index" of the most significant bit.
				// 0b0000_0000.msb()==0 (but we just special case return 0.0)
				// 0b0000_0001.msb()==0
				// 0b1000_0000.msb()==7
				let Some(most_significant_bit)=unsigned.bit_width().checked_sub(1)else{
					return 0.0;
				};
				// sign
				let sign=if self.bits.is_negative(){(1 as $unsigned)<<(<$unsigned>::BITS-1)}else{0};

				// exp
				let msb=most_significant_bit as $unsigned;
				let msb_offset=msb+$bias-F as $unsigned;
				let exp=msb_offset<<$mantissa_msb;

				// mant
				let digits=unsigned.to_bytes();

				// Copy digits into mantissa
				let mut m_bytes=[0u8;_];

				let mant_unmasked;
				const MOD8:usize=((1<<DIGIT_SHIFT)-1);
				const MANT_REM:usize=$mantissa_msb&MOD8;
				const NEG_MANT_REM:usize=(1<<DIGIT_SHIFT)-MANT_REM;
				if $mantissa_msb<most_significant_bit{
					// lsb of mantissa is higher than lsb of fixed point
					// Copy bytes (f64)
					// CASE 0:
					// F64_32 [00000000,00011111,11111111,11111111,11111111,11111111,11111111,11111111,...]
					// u64             [00011111,11111111,11111111,11111111,11111111,11111111,11111111,00000000]
					// msb%8=4
					// i_m=1
					// CASE 1:
					// F64_32 [00000000,00111111,11111111,11111111,11111111,11111111,11111111,11111110,...]
					// u64             [00111111,11111111,11111111,11111111,11111111,11111111,11111110,00000000]
					// CASE 2:
					// F64_32 [00000000,01111111,11111111,11111111,11111111,11111111,11111111,11111100,...]
					// u64             [01111111,11111111,11111111,11111111,11111111,11111111,11111100,00000000]
					// CASE 3:
					// F64_32 [00000000,11111111,11111111,11111111,11111111,11111111,11111111,11111000,...]
					// u64             [11111111,11111111,11111111,11111111,11111111,11111111,11111000,00000000]
					// CASE 4:
					// F64_32 [00000001,11111111,11111111,11111111,11111111,11111111,11111111,11110000,...]
					// u64    [00000001,11111111,11111111,11111111,11111111,11111111,11111111,11110000]
					// CASE 5:
					// F64_32 [00000011,11111111,11111111,11111111,11111111,11111111,11111111,11100000,...]
					// u64    [00000011,11111111,11111111,11111111,11111111,11111111,11111111,11100000]
					// CASE 6:
					// F64_32 [00000111,11111111,11111111,11111111,11111111,11111111,11111111,11000000,...]
					// u64    [00000111,11111111,11111111,11111111,11111111,11111111,11111111,11000000]
					// CASE 7:
					// F64_32 [00001111,11111111,11111111,11111111,11111111,11111111,11111111,10000000,...]
					// u64    [00001111,11111111,11111111,11111111,11111111,11111111,11111111,10000000]
					//
					// Copy bytes (f32)
					// CASE 0:
					// F64_32 [00000000,01111111,11111111,11111111,...]
					// u32             [01111111,11111111,11111111,00000000]
					// msb%8=4
					// i_m=1
					// CASE 1:
					// F64_32 [00000000,11111111,11111111,11111110,...]
					// u32             [11111111,11111111,11111110,00000000]
					// CASE 2:
					// F64_32 [00000001,11111111,11111111,11111100,...]
					// u32    [00000001,11111111,11111111,11111100]
					// CASE 3:
					// F64_32 [00000011,11111111,11111111,11111000,...]
					// u32    [00000011,11111111,11111111,11111000]
					// CASE 4:
					// F64_32 [00000111,11111111,11111111,11110000,...]
					// u32    [00000111,11111111,11111111,11110000]
					// CASE 5:
					// F64_32 [00001111,11111111,11111111,11100000,...]
					// u32    [00001111,11111111,11111111,11100000]
					// CASE 6:
					// F64_32 [00011111,11111111,11111111,11000000,...]
					// u32    [00011111,11111111,11111111,11000000]
					// CASE 7:
					// F64_32 [00111111,11111111,11111111,10000000,...]
					// u32    [00111111,11111111,11111111,10000000]
					let right_shift=most_significant_bit as usize-$mantissa_msb;
					let mut i_m=((most_significant_bit as usize&MOD8)+NEG_MANT_REM)>>DIGIT_SHIFT;
					let mut i_d=right_shift>>DIGIT_SHIFT;
					while i_m<m_bytes.len()&&i_d<N{
						m_bytes[i_m]=digits[i_d];
						i_m+=1;
						i_d+=1;
					}
					let unsigned=<$unsigned>::from_le_bytes(m_bytes);
					let right_shift=((right_shift+MANT_REM)&MOD8)+NEG_MANT_REM;
					mant_unmasked=unsigned>>right_shift;
				}else{
					// lsb of mantissa is lower than lsb of fixed point
					// [0,0,0,0,0b0100_0000,0,0,0]
					//       [0,0b0001_0000,0,0,0,0,0,0]<<e
					let left_shift=$mantissa_msb-most_significant_bit as usize;
					let mut i_m=left_shift>>DIGIT_SHIFT;
					let mut i_d=0;
					while i_m<m_bytes.len()&&i_d<N{
						m_bytes[i_m]=digits[i_d];
						i_m+=1;
						i_d+=1;
					}
					mant_unmasked=<$unsigned>::from_le_bytes(m_bytes)<<(left_shift&MOD8);
				}

				let mant=mant_unmasked&(((1 as $unsigned)<<$mantissa_msb)-1);
				let bits=sign|exp|mant;
				<$output>::from_bits(bits)
			}
		}
	}
}
impl_into_float!(f32,u32,23,127);
impl_into_float!(f64,u64,52,1023);

#[inline]
fn integer_decode_f32(f: f32) -> (u32, u8, bool) {
	let bits: u32 = f.to_bits();
	let sign: bool = bits & (1<<31) != 0;
	let exponent = (bits >> 23) & 0xff;
	let mantissa = if exponent == 0 {
		(bits & 0x7fffff) << 1
	} else {
		(bits & 0x7fffff) | 0x800000
	};
	(mantissa, exponent as u8, sign)
}
#[inline]
fn integer_decode_f64(f: f64) -> (u64, u16, bool) {
	let bits: u64 = f.to_bits();
	let sign: bool = bits & (1u64<<63) != 0;
	let exponent = (bits >> 52) & 0x7ff;
	let mantissa = if exponent == 0 {
		(bits & 0xfffffffffffff) << 1
	} else {
		(bits & 0xfffffffffffff) | 0x10000000000000
	};
	(mantissa, exponent as u16, sign)
}
#[derive(Debug,Eq,PartialEq)]
pub enum FixedFromFloatError{
	Nan,
	Infinite,
	Overflow,
	Underflow,
}
impl FixedFromFloatError{
	pub fn underflow_to_zero<const N:usize,const F:usize>(self)->Result<Fixed<N,F>,Self>{
		match self{
			FixedFromFloatError::Underflow=>Ok(Fixed::ZERO),
			_=>Err(self),
		}
	}
}
impl core::fmt::Display for FixedFromFloatError{
	fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
		write!(f,"{self:?}")
	}
}
macro_rules! impl_from_float{
	($decode:ident,$input:ty,$mantissa_bits:expr,$bias:expr)=>{
		impl<const N:usize,const F:usize> TryFrom<$input> for Fixed<N,F>{
			type Error=FixedFromFloatError;
			#[inline]
			fn try_from(value:$input)->Result<Self,Self::Error>{
				match value.classify(){
					std::num::FpCategory::Nan=>Err(FixedFromFloatError::Nan),
					std::num::FpCategory::Infinite=>Err(FixedFromFloatError::Infinite),
					std::num::FpCategory::Zero=>Ok(Self::ZERO),
					std::num::FpCategory::Subnormal
					|std::num::FpCategory::Normal
					=>{
						let (m,e,s)=$decode(value);
						let mut digits=[0u8;N];
						let msb_biased=e as usize+F+1;
						if msb_biased<$bias{
							return Err(FixedFromFloatError::Underflow);
						};
						if N*BNUM_DIGIT_WIDTH+$bias<=msb_biased{
							return Err(FixedFromFloatError::Overflow);
						}
						let lsb=msb_biased as isize-$bias-$mantissa_bits;
						// underflow is ok, we only need to know the alignment
						let lsb_alignment=lsb&((1<<DIGIT_SHIFT)-1);
						// the 53 bit mantissa has room to shift by 0-7 bits
						let aligned_mantissa=m<<lsb_alignment;
						let m_bytes=aligned_mantissa.to_le_bytes();
						let digit_index=lsb>>DIGIT_SHIFT;
						let mut i_m;
						let mut i_d;
						if digit_index<0{
							// lsb of mantissa is lower than lsb of fixed point
							//             [0,0,0,0]<<e
							// [0,0,0,1,0,0,0,0]
							i_m=-digit_index as usize;
							i_d=0;
						}else{
							// lsb of mantissa is higher than lsb of fixed point
							//     [0,0,0,0]<<e
							// [0,0,0,1,0,0,0,0]
							i_m=0;
							i_d=digit_index as usize;
						}
						while i_m<m_bytes.len()&&i_d<N{
							digits[i_d]=m_bytes[i_m];
							i_m+=1;
							i_d+=1;
						}

						/* AI idea is not bad
						// Calculate i_m and i_d without branching
						// is_less is 1 if lsb < bias + mantissa_bits (mantissa is "above" fixed point)
						let is_less = (lsb < ($bias + $mantissa_bits)) as usize;

						// If lsb < bias, we skip i_m bytes in m_bytes, i_d is 0
						// If lsb >= bias, i_m is 0, we skip i_d bytes in digits
						i_m = (((($bias + $mantissa_bits) - lsb) >> DIGIT_SHIFT) & is_less);
						i_d = ((lsb.wrapping_sub($bias + $mantissa_bits) >> DIGIT_SHIFT) & !is_less);

						// Calculate how many bytes to copy safely
						let m_bytes_len = m_bytes.len();
						let count = (m_bytes_len.saturating_sub(i_m)).min(N.saturating_sub(i_d));

						if count > 0 {
							digits[i_d..i_d + count].copy_from_slice(&m_bytes[i_m..i_m + count]);
						}
						*/

						let bits=Int::from_bytes(digits);
						Ok(if s{
							Self::from_bits(bits.overflowing_neg().0)
						}else{
							Self::from_bits(bits)
						})
					},
				}
			}
		}
	}
}
impl_from_float!(integer_decode_f32,f32,24,127);
impl_from_float!(integer_decode_f64,f64,53,1023);

impl<const N:usize,const F:usize> core::fmt::Debug for Fixed<N,F>{
	#[inline]
	fn fmt(&self,f:&mut core::fmt::Formatter)->Result<(),core::fmt::Error>{
		let integral=self.as_bits().unsigned_abs()>>F;
		let fractional=self.as_bits().unsigned_abs()&((n!(1)<<F)-n!(1));
		let leading_zeroes=(fractional.leading_zeros() as usize).saturating_sub(N*BNUM_DIGIT_WIDTH-F)>>2;
		if self.is_negative(){
			core::write!(f,"-")?;
		}
		if fractional.is_zero(){
			core::write!(f,"{integral:x}.{}","0".repeat(leading_zeroes))
		}else{
			core::write!(f,"{integral:x}.{}{fractional:x}","0".repeat(leading_zeroes))
		}
	}
}

impl<const N:usize,const F:usize> core::fmt::Display for Fixed<N,F>{
	#[inline]
	fn fmt(&self,f:&mut core::fmt::Formatter)->Result<(),core::fmt::Error>{
		let float:f32=(*self).into();
		core::write!(f,"{:.3}",float)
	}
}

macro_rules! impl_additive_operator {
	( $trait: ident, $method: ident, $output: ty ) => {
		impl<const N:usize,const F:usize> Fixed<N,F>{
			#[inline]
			pub const fn $method(self, other: Self) -> Self {
				Self::from_bits(self.bits.$method(other.bits))
			}
		}
		impl<const N:usize,const F:usize> core::ops::$trait for Fixed<N,F>{
			type Output = $output;
			#[inline]
			fn $method(self, other: Self) -> Self::Output {
				self.$method(other)
			}
		}
	};
}
macro_rules! impl_additive_assign_operator {
	( $trait: ident, $method: ident ) => {
		impl<const N:usize,const F:usize> core::ops::$trait for Fixed<N,F>{
			#[inline]
			fn $method(&mut self, other: Self) {
				self.bits.$method(other.bits);
			}
		}
	};
}

// Impl arithmetic pperators
impl_additive_assign_operator!( AddAssign, add_assign );
impl_additive_operator!( Add, add, Self );
impl_additive_assign_operator!( SubAssign, sub_assign );
impl_additive_operator!( Sub, sub, Self );
impl_additive_assign_operator!( RemAssign, rem_assign );
impl_additive_operator!( Rem, rem, Self );

// Impl bitwise operators
impl_additive_assign_operator!( BitAndAssign, bitand_assign );
impl_additive_operator!( BitAnd, bitand, Self );
impl_additive_assign_operator!( BitOrAssign, bitor_assign );
impl_additive_operator!( BitOr, bitor, Self );
impl_additive_assign_operator!( BitXorAssign, bitxor_assign );
impl_additive_operator!( BitXor, bitxor, Self );

// non-wide operators.  The result is the same width as the inputs.

// This macro is not used in the default configuration.
#[expect(unused_macros)]
macro_rules! impl_multiplicative_operator_not_const_generic {
	( ($trait: ident, $method: ident, $output: ty ), $width:expr ) => {
		impl<const F:usize> core::ops::$trait for Fixed<{$width/BNUM_DIGIT_WIDTH},F>{
			type Output = $output;
			#[inline]
			fn $method(self, other: Self) -> Self::Output {
				paste::item!{
				self.[<fixed_ $method>](other)
				}
			}
		}
	};
}
macro_rules! impl_multiplicative_assign_operator_not_const_generic {
	( ($trait: ident, $method: ident, $non_assign_method: ident ), $width:expr ) => {
		impl<const F:usize> core::ops::$trait for Fixed<{$width/BNUM_DIGIT_WIDTH},F>{
			#[inline]
			fn $method(&mut self, other: Self) {
				paste::item!{
				*self=self.[<fixed_ $non_assign_method>](other);
				}
			}
		}
	};
}

macro_rules! impl_multiply_operator_not_const_generic {
	( ($trait: ident, $method: ident, $output: ty ), $width:expr ) => {
		impl<const F:usize> Fixed<{$width/BNUM_DIGIT_WIDTH},F>{
			paste::item!{
			#[inline]
			pub fn [<fixed_ $method>](self, rhs: Self) -> Self {
				let (low,high)=self.bits.unsigned_abs().widening_mul(rhs.bits.unsigned_abs());
				let out:Int::<{$width*2/BNUM_DIGIT_WIDTH}>=unsafe{core::mem::transmute([low,high])};
				if self.is_negative()==rhs.is_negative(){
					Self::from_bits(out.shr(F as u32).as_())
				}else{
					-Self::from_bits(out.shr(F as u32).as_())
				}
			}
			}
		}
		#[cfg(not(feature="wide-mul"))]
		impl_multiplicative_operator_not_const_generic!(($trait,$method,$output),$width);
		#[cfg(feature="deferred-division")]
		impl ratio_ops::ratio::Divide<i64> for Fixed<{$width/BNUM_DIGIT_WIDTH},{$width>>1}>{
			type Output=Self;
			#[inline]
			fn divide(self, other: i64)->Self::Output{
				Self::from_bits(self.bits.div_euclid(other.as_()))
			}
		}
	}
}
macro_rules! impl_divide_operator_not_const_generic {
	( ($trait: ident, $method: ident, $output: ty ), $width:expr ) => {
		impl<const F:usize> Fixed<{$width/BNUM_DIGIT_WIDTH},F>{
			paste::item!{
			#[inline]
			pub fn [<fixed_ $method>](self,other:Self)->Self{
				//this only needs to be $width+F as u32/64+1 but MUH CONST GENERICS!!!!!
				let lhs=self.bits.as_::<Int::<{$width*2/BNUM_DIGIT_WIDTH}>>().shl(F as u32);
				let rhs=other.bits.as_::<Int::<{$width*2/BNUM_DIGIT_WIDTH}>>();
				Self::from_bits(lhs.div_euclid(rhs).as_())
			}
			}
		}
		#[cfg(all(not(feature="wide-mul"),not(feature="deferred-division")))]
		impl_multiplicative_operator_not_const_generic!(($trait,$method,$output),$width);
		#[cfg(all(not(feature="wide-mul"),feature="deferred-division"))]
		impl<const F:usize> ratio_ops::ratio::Divide for Fixed<{$width/BNUM_DIGIT_WIDTH},F>{
			type Output = $output;
			#[inline]
			fn divide(self, other: Self) -> Self::Output {
				paste::item!{
				self.[<fixed_ $method>](other)
				}
			}
		}
	};
}

macro_rules! impl_multiplicative_operator {
	( $trait: ident, $method: ident, $inner_method: ident, $output: ty ) => {
		impl<const N:usize,const F:usize,U> core::ops::$trait<U> for Fixed<N,F>
			where
				Int::<N>:bnum::cast::CastFrom<U>+core::ops::$trait,
		{
			type Output = $output;
			#[inline]
			fn $method(self,other:U)->Self::Output{
				Self::from_bits(self.bits.$inner_method(other.as_()))
			}
		}
	};
}
macro_rules! impl_multiplicative_assign_operator {
	( $trait: ident, $method: ident, $not_assign_method: ident ) => {
		impl<const N:usize,const F:usize,U> core::ops::$trait<U> for Fixed<N,F>
			where
				Int::<N>:bnum::cast::CastFrom<U>+core::ops::$trait,
		{
			#[inline]
			fn $method(&mut self,other:U){
				self.bits=self.bits.$not_assign_method(other.as_());
			}
		}
	};
}

macro_rules! macro_repeated{
	(
		$macro:ident,
		$any:tt,
		$($repeated:tt),*
	)=>{
		$(
			$macro!($any, $repeated);
		)*
	};
}

macro_rules! macro_16 {
	( $macro: ident, $any:tt ) => {
		macro_repeated!($macro,$any,64,128,192,256,320,384,448,512,576,640,704,768,832,896,960,1024);
	}
}

macro_16!( impl_multiplicative_assign_operator_not_const_generic, (MulAssign, mul_assign, mul) );
macro_16!( impl_multiply_operator_not_const_generic, (Mul, mul, Self) );
macro_16!( impl_multiplicative_assign_operator_not_const_generic, (DivAssign, div_assign, div) );
macro_16!( impl_divide_operator_not_const_generic, (Div, div, Self) );
impl_multiplicative_assign_operator!( MulAssign, mul_assign, mul );
impl_multiplicative_operator!( Mul, mul, mul, Self );
impl_multiplicative_assign_operator!( DivAssign, div_assign, div_euclid );
impl_multiplicative_operator!( Div, div, div_euclid, Self );
#[cfg(feature="deferred-division")]
impl<const LHS_N:usize,const LHS_F:usize,const RHS_N:usize,const RHS_F:usize> core::ops::Div<Fixed<RHS_N,RHS_F>> for Fixed<LHS_N,LHS_F>{
	type Output=ratio_ops::ratio::Ratio<Fixed<LHS_N,LHS_F>,Fixed<RHS_N,RHS_F>>;
	#[inline]
	fn div(self, other: Fixed<RHS_N,RHS_F>)->Self::Output{
		ratio_ops::ratio::Ratio::new(self,other)
	}
}
#[cfg(feature="deferred-division")]
impl<const N:usize,const F:usize> ratio_ops::ratio::Parity for Fixed<N,F>{
	fn parity(&self)->bool{
		self.is_negative()
	}
}
macro_rules! impl_shift_operator {
	( $trait: ident, $method: ident, $output: ty ) => {
		impl<const N:usize,const F:usize> core::ops::$trait<u32> for Fixed<N,F>{
			type Output = $output;
			#[inline]
			fn $method(self, other: u32) -> Self::Output {
				Self::from_bits(self.bits.$method(other))
			}
		}
	};
}
macro_rules! impl_shift_assign_operator {
	( $trait: ident, $method: ident ) => {
		impl<const N:usize,const F:usize> core::ops::$trait<u32> for Fixed<N,F>{
			#[inline]
			fn $method(&mut self, other: u32) {
				self.bits.$method(other);
			}
		}
	};
}
impl_shift_assign_operator!( ShlAssign, shl_assign );
impl_shift_operator!( Shl, shl, Self );
impl_shift_assign_operator!( ShrAssign, shr_assign );
impl_shift_operator!( Shr, shr, Self );

// wide operators.  The result width is the sum of the input widths, i.e. none of the multiplication

#[allow(unused_macros)]
macro_rules! impl_wide_operators{
	($lhs:expr,$rhs:expr)=>{
		impl core::ops::Mul<Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>> for Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>{
			type Output=Fixed<{($lhs+$rhs)/BNUM_DIGIT_WIDTH},{($lhs+$rhs)>>1}>;
			#[inline]
			fn mul(self, other: Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>)->Self::Output{
				paste::item!{
				self.[<wide_mul_ $lhs _ $rhs>](other)
				}
			}
		}
		#[cfg(not(feature="deferred-division"))]
		impl core::ops::Div<Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>> for Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>{
			type Output=Fixed<{($lhs+$rhs)/BNUM_DIGIT_WIDTH},{($lhs+$rhs)>>1}>;
			#[inline]
			fn div(self, other: Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>)->Self::Output{
				paste::item!{
				self.[<wide_div_ $lhs _ $rhs>](other)
				}
			}
		}
		#[cfg(feature="deferred-division")]
		impl ratio_ops::ratio::Divide<Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>> for Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>{
			type Output=Fixed<{($lhs+$rhs)/BNUM_DIGIT_WIDTH},{($lhs+$rhs)>>1}>;
			#[inline]
			fn divide(self, other: Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>)->Self::Output{
				paste::item!{
				self.[<wide_div_ $lhs _ $rhs>](other)
				}
			}
		}
	}
}

// WIDE MUL: multiply into a wider type
// let a = I32F32::ONE;
// let b:I64F64 = a.wide_mul(a);
macro_rules! impl_wide_not_const_generic{
	(
		(),
		($lhs:expr,$rhs:expr)
	)=>{
		impl Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>
		{
			paste::item!{
				#[inline]
				pub fn [<wide_mul_ $lhs _ $rhs>](self,rhs:Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>)->Fixed<{($lhs+$rhs)/BNUM_DIGIT_WIDTH},{($lhs+$rhs)>>1}>{
					let lhs=self.bits.as_::<Int<{($lhs+$rhs)/BNUM_DIGIT_WIDTH}>>();
					let rhs=rhs.bits.as_::<Int<{($lhs+$rhs)/BNUM_DIGIT_WIDTH}>>();
					Fixed::from_bits(lhs*rhs)
				}
				/// This operation cannot represent the fraction exactly,
				/// but it shapes the output to have precision for the
				/// largest and smallest possible fractions.
				#[inline]
				pub fn [<wide_div_ $lhs _ $rhs>](self,rhs:Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>)->Fixed<{($lhs+$rhs)/BNUM_DIGIT_WIDTH},{($lhs+$rhs)>>1}>{
					// (lhs/2^LHS_FRAC)/(rhs/2^RHS_FRAC)
					let lhs=self.bits.as_::<Int<{($lhs+$rhs)/BNUM_DIGIT_WIDTH}>>().shl($rhs);
					let rhs=rhs.bits.as_::<Int<{($lhs+$rhs)/BNUM_DIGIT_WIDTH}>>();
					Fixed::from_bits(lhs.div_euclid(rhs))
				}
			}
		}
		#[cfg(feature="wide-mul")]
		impl_wide_operators!($lhs,$rhs);
	};
}
macro_rules! impl_wide_same_size_not_const_generic{
	(
		(),
		$width:expr
	)=>{
		impl Fixed<{$width/BNUM_DIGIT_WIDTH},{$width>>1}>
		{
			paste::item!{
				#[inline]
				pub fn [<wide_mul_ $width _ $width>](self,rhs:Fixed<{$width/BNUM_DIGIT_WIDTH},{$width>>1}>)->Fixed<{$width*2/BNUM_DIGIT_WIDTH},{$width*2>>1}>{
					let (low,high)=self.bits.unsigned_abs().widening_mul(rhs.bits.unsigned_abs());
					let out:Int::<{$width*2/BNUM_DIGIT_WIDTH}>=unsafe{core::mem::transmute([low,high])};
					if self.is_negative()==rhs.is_negative(){
						Fixed::from_bits(out)
					}else{
						// Normal neg is the cheapest negation operation
						// And the inputs cannot reach the point where it matters
						Fixed::from_bits(out.neg())
					}
				}
				/// This operation cannot represent the fraction exactly,
				/// but it shapes the output to have precision for the
				/// largest and smallest possible fractions.
				#[inline]
				pub fn [<wide_div_ $width _ $width>](self,rhs:Fixed<{$width/BNUM_DIGIT_WIDTH},{$width>>1}>)->Fixed<{$width*2/BNUM_DIGIT_WIDTH},{$width*2>>1}>{
					// (lhs/2^LHS_FRAC)/(rhs/2^RHS_FRAC)
					let lhs=self.bits.as_::<Int<{$width*2/BNUM_DIGIT_WIDTH}>>().shl($width);
					let rhs=rhs.bits.as_::<Int<{$width*2/BNUM_DIGIT_WIDTH}>>();
					Fixed::from_bits(lhs.div_euclid(rhs))
				}
			}
		}
		#[cfg(feature="wide-mul")]
		impl_wide_operators!($width,$width);
	};
}

//const generics sidestepped wahoo
macro_repeated!(
	impl_wide_not_const_generic,(),
	      (128,64),(192,64),(256,64),(320,64),(384,64),(448,64),(512,64),(576,64),(640,64),(704,64),(768,64),(832,64),(896,64),(960,64),
	(64,128),      (192,128),(256,128),(320,128),(384,128),(448,128),(512,128),(576,128),(640,128),(704,128),(768,128),(832,128),(896,128),
	(64,192),(128,192),      (256,192),(320,192),(384,192),(448,192),(512,192),(576,192),(640,192),(704,192),(768,192),(832,192),
	(64,256),(128,256),(192,256),      (320,256),(384,256),(448,256),(512,256),(576,256),(640,256),(704,256),(768,256),
	(64,320),(128,320),(192,320),(256,320),      (384,320),(448,320),(512,320),(576,320),(640,320),(704,320),
	(64,384),(128,384),(192,384),(256,384),(320,384),      (448,384),(512,384),(576,384),(640,384),
	(64,448),(128,448),(192,448),(256,448),(320,448),(384,448),      (512,448),(576,448),
	(64,512),(128,512),(192,512),(256,512),(320,512),(384,512),(448,512),      (576,512),
	(64,576),(128,576),(192,576),(256,576),(320,576),(384,576),(448,576),
	(64,640),(128,640),(192,640),(256,640),(320,640),(384,640),
	(64,704),(128,704),(192,704),(256,704),(320,704),
	(64,768),(128,768),(192,768),(256,768),
	(64,832),(128,832),(192,832),
	(64,896),(128,896),
	(64,960)
);
macro_repeated!(
	impl_wide_same_size_not_const_generic,(),
	64,128,192,256,320,384,448,512
);

#[derive(Debug,Eq,PartialEq)]
pub enum NarrowError{
	Overflow,
	Underflow,
}

pub trait Wrap<Output>{
	fn wrap(self)->Output;
}
pub trait Clamp<Output>{
	fn clamp(self)->Output;
}
impl<const N:usize,const F:usize> Clamp<Fixed<N,F>> for Result<Fixed<N,F>,NarrowError>{
	fn clamp(self)->Fixed<N,F>{
		match self{
			Ok(fixed)=>fixed,
			Err(NarrowError::Overflow)=>Fixed::MAX,
			Err(NarrowError::Underflow)=>Fixed::MIN,
		}
	}
}

macro_rules! impl_narrow_not_const_generic{
	(
		(),
		($lhs:expr,$rhs:expr)
	)=>{
		paste::item!{
			impl Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>
			{
				#[inline]
				pub fn [<wrap_ $rhs>](self)->Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>{
					Fixed::from_bits(bnum::cast::As::as_::<Int::<{$rhs/BNUM_DIGIT_WIDTH}>>(self.bits.shr(($lhs-$rhs)>>1)))
				}
				#[inline]
				pub fn [<narrow_ $rhs>](self)->Result<Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>,NarrowError>{
					if Fixed::<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>::MAX.[<widen_ $lhs>]().bits<self.bits{
						return Err(NarrowError::Overflow);
					}
					if self.bits<Fixed::<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>::MIN.[<widen_ $lhs>]().bits{
						return Err(NarrowError::Underflow);
					}
					Ok(self.[<wrap_ $rhs>]())
				}
				#[inline]
				pub fn [<clamp_ $rhs>](self)->Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>{
					self.[<narrow_ $rhs>]().clamp()
				}
			}
			impl Wrap<Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>> for Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>{
				#[inline]
				fn wrap(self)->Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>{
					self.[<wrap_ $rhs>]()
				}
			}
			impl TryInto<Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>> for Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>{
				type Error=NarrowError;
				#[inline]
				fn try_into(self)->Result<Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>,Self::Error>{
					self.[<narrow_ $rhs>]()
				}
			}
			impl Clamp<Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>> for Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>{
				#[inline]
				fn clamp(self)->Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>{
					self.[<clamp_ $rhs>]()
				}
			}
		}
	}
}
macro_rules! impl_widen_not_const_generic{
	(
		(),
		($lhs:expr,$rhs:expr)
	)=>{
		paste::item!{
			impl Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>
			{
				#[inline]
				pub fn [<widen_ $rhs>](self)->Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>{
					Fixed::from_bits(bnum::cast::As::as_::<Int::<{$rhs/BNUM_DIGIT_WIDTH}>>(self.bits).shl(($rhs-$lhs)>>1))
				}
			}
			impl Into<Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>> for Fixed<{$lhs/BNUM_DIGIT_WIDTH},{$lhs>>1}>{
				#[inline]
				fn into(self)->Fixed<{$rhs/BNUM_DIGIT_WIDTH},{$rhs>>1}>{
					self.[<widen_ $rhs>]()
				}
			}
		}
	}
}

// I LOVE NOT BEING ABLE TO USE CONST GENERICS

macro_repeated!(
	impl_narrow_not_const_generic,(),
	(128,64),(192,64),(256,64),(320,64),(384,64),(448,64),(512,64),(576,64),(640,64),(704,64),(768,64),(832,64),(896,64),(960,64),(1024,64),(1088,64),
	(192,128),(256,128),(320,128),(384,128),(448,128),(512,128),(576,128),(640,128),(704,128),(768,128),(832,128),(896,128),(960,128),(1024,128),
	(256,192),(320,192),(384,192),(448,192),(512,192),(576,192),(640,192),(704,192),(768,192),(832,192),(896,192),(960,192),(1024,192),
	(320,256),(384,256),(448,256),(512,256),(576,256),(640,256),(704,256),(768,256),(832,256),(896,256),(960,256),(1024,256),
	(384,320),(448,320),(512,320),(576,320),(640,320),(704,320),(768,320),(832,320),(896,320),(960,320),(1024,320),
	(448,384),(512,384),(576,384),(640,384),(704,384),(768,384),(832,384),(896,384),(960,384),(1024,384),
	(512,448),(576,448),(640,448),(704,448),(768,448),(832,448),(896,448),(960,448),(1024,448),
	(576,512),(640,512),(704,512),(768,512),(832,512),(896,512),(960,512),(1024,512),
	(640,576),(704,576),(768,576),(832,576),(896,576),(960,576),(1024,576),
	(704,640),(768,640),(832,640),(896,640),(960,640),(1024,640),
	(768,704),(832,704),(896,704),(960,704),(1024,704),
	(832,768),(896,768),(960,768),(1024,768),
	(896,832),(960,832),(1024,832),
	(960,896),(1024,896),
	(1024,960)
);
macro_repeated!(
	impl_widen_not_const_generic,(),
	(64,128),
	(64,192),(128,192),
	(64,256),(128,256),(192,256),
	(64,320),(128,320),(192,320),(256,320),
	(64,384),(128,384),(192,384),(256,384),(320,384),
	(64,448),(128,448),(192,448),(256,448),(320,448),(384,448),
	(64,512),(128,512),(192,512),(256,512),(320,512),(384,512),(448,512),
	(64,576),(128,576),(192,576),(256,576),(320,576),(384,576),(448,576),(512,576),
	(64,640),(128,640),(192,640),(256,640),(320,640),(384,640),(448,640),(512,640),(576,640),
	(64,704),(128,704),(192,704),(256,704),(320,704),(384,704),(448,704),(512,704),(576,704),(640,704),
	(64,768),(128,768),(192,768),(256,768),(320,768),(384,768),(448,768),(512,768),(576,768),(640,768),(704,768),
	(64,832),(128,832),(192,832),(256,832),(320,832),(384,832),(448,832),(512,832),(576,832),(640,832),(704,832),(768,832),
	(64,896),(128,896),(192,896),(256,896),(320,896),(384,896),(448,896),(512,896),(576,896),(640,896),(704,896),(768,896),(832,896),
	(64,960),(128,960),(192,960),(256,960),(320,960),(384,960),(448,960),(512,960),(576,960),(640,960),(704,960),(768,960),(832,960),(896,960),
	(64,1024),(128,1024),(192,1024),(256,1024),(320,1024),(384,1024),(448,1024),(512,1024),(576,1024),(640,1024),(704,1024),(768,1024),(832,1024),(896,1024),(960,1024),
	(64,1088)
);

macro_rules! impl_not_const_generic{
	($n:expr,$_2n:expr)=>{
		impl Fixed<{$n/BNUM_DIGIT_WIDTH},{$n>>1}>{
			paste::item!{
			#[inline]
			pub fn sqrt_unchecked(self)->Self{
				//1<<max_shift must be the minimum power of two which when squared is greater than self
				//calculating max_shift:
				//1. count "used" bits to the left of the decimal, not including the sign bit (so -1)
				//2. divide by 2 via >>1 (sqrt-ish)
				//3. add on fractional offset
				//Voila
				let used_bits=self.bits.unsigned_abs().bit_width() as i32-1-($n>>1) as i32;
				let max_shift=((used_bits>>1)+($n>>1) as i32) as u32;
				let mut result=Self::ZERO;

				//resize self to match the wide mul output
				let wide_self=self.[<widen_ $_2n>]();
				//descend down the bits and check if flipping each bit would push the square over the input value
				for shift in (0..=max_shift).rev(){
					result.as_bits_mut().set_bit(shift,true);
					if wide_self<result.[<wide_mul_ $n _ $n>](result){
						// put it back lol
						result.as_bits_mut().set_bit(shift,false);
					}
				}
				result
			}
			}
			#[inline]
			pub fn sqrt(self)->Self{
				if self<Self::ZERO{
					panic!("Square root less than zero")
				}else{
					self.sqrt_unchecked()
				}
			}
			#[inline]
			pub fn sqrt_checked(self)->Option<Self>{
				if self<Self::ZERO{
					None
				}else{
					Some(self.sqrt_unchecked())
				}
			}
		}
	}
}
impl_not_const_generic!(64,128);
impl_not_const_generic!(128,256);
impl_not_const_generic!(192,384);
impl_not_const_generic!(256,512);
impl_not_const_generic!(320,640);
impl_not_const_generic!(384,768);
impl_not_const_generic!(448,896);
impl_not_const_generic!(512,1024);
