1pub extern crate muldiv;
68pub extern crate num_traits;
69pub extern crate typenum;
70
71pub mod aliases;
72pub mod fix_value;
73pub mod prelude;
74pub mod util;
75
76use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
77use core::fmt::{Debug, Error, Formatter};
78use core::hash::{Hash, Hasher};
79use core::marker::PhantomData;
80use core::ops::{Add, Div, Mul, Neg, Rem, Sub};
81use core::ops::{AddAssign, DivAssign, MulAssign, RemAssign, SubAssign};
82
83use muldiv::MulDiv;
84use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub};
85use paste::paste;
86use typenum::consts::Z0;
87use typenum::marker_traits::{Bit, Integer, Unsigned};
88use typenum::operator_aliases::{AbsVal, Diff, Le, Sum};
89use typenum::type_operators::{Abs, IsLess};
90
91pub struct Fix<Bits, Base, Exp> {
119 pub bits: Bits,
121
122 marker: PhantomData<(Base, Exp)>,
123}
124
125impl<Bits, Base, Exp> Fix<Bits, Base, Exp> {
126 pub fn new(bits: Bits) -> Self {
136 Fix {
137 bits,
138 marker: PhantomData,
139 }
140 }
141
142 pub const fn constant(bits: Bits) -> Self {
144 Fix {
145 bits,
146 marker: PhantomData,
147 }
148 }
149
150 pub fn convert<ToExp>(self) -> Fix<Bits, Base, ToExp>
162 where
163 Bits: FromUnsigned + Pow + Mul<Output = Bits> + Div<Output = Bits>,
164 Base: Unsigned,
165 Exp: Sub<ToExp>,
166 Diff<Exp, ToExp>: Abs + IsLess<Z0>,
167 AbsVal<Diff<Exp, ToExp>>: Integer,
168 {
169 let base = Bits::from_unsigned::<Base>();
170 let diff = AbsVal::<Diff<Exp, ToExp>>::to_i32();
171 let inverse = Le::<Diff<Exp, ToExp>, Z0>::to_bool();
172
173 let ratio = base.pow(diff.unsigned_abs());
176
177 if inverse {
178 Fix::new(self.bits / ratio)
179 } else {
180 Fix::new(self.bits * ratio)
181 }
182 }
183
184 pub fn widen<ToBits>(self) -> Fix<ToBits, Base, Exp>
196 where
197 ToBits: From<Bits>,
198 {
199 Fix::<ToBits, Base, Exp>::new(self.bits.into())
200 }
201
202 pub fn narrow<ToBits>(self) -> Option<Fix<ToBits, Base, Exp>>
215 where
216 ToBits: TryFrom<Bits>,
217 {
218 self.bits.try_into().ok().map(Fix::<ToBits, Base, Exp>::new)
219 }
220}
221
222pub trait FromUnsigned {
229 fn from_unsigned<U>() -> Self
231 where
232 U: Unsigned;
233}
234
235macro_rules! impl_from_unsigned {
236 ($ty:ident) => {
237 impl FromUnsigned for $ty {
238 fn from_unsigned<U: Unsigned>() -> Self {
239 paste! { U::[<to_$ty>]() }
240 }
241 }
242 };
243}
244
245impl_from_unsigned!(u8);
246impl_from_unsigned!(u16);
247impl_from_unsigned!(u32);
248impl_from_unsigned!(u64);
249impl_from_unsigned!(u128);
250impl_from_unsigned!(usize);
251impl_from_unsigned!(i8);
252impl_from_unsigned!(i16);
253impl_from_unsigned!(i32);
254impl_from_unsigned!(i64);
255impl_from_unsigned!(i128);
256impl_from_unsigned!(isize);
257
258pub trait Pow {
263 #[must_use]
265 fn pow(self, exp: u32) -> Self;
266}
267
268macro_rules! impl_pow {
269 ($ty:ident) => {
270 impl Pow for $ty {
271 #[inline]
272 fn pow(self, exp: u32) -> Self {
273 self.pow(exp)
274 }
275 }
276 };
277}
278
279impl_pow!(u8);
280impl_pow!(u16);
281impl_pow!(u32);
282impl_pow!(u64);
283impl_pow!(u128);
284impl_pow!(usize);
285impl_pow!(i8);
286impl_pow!(i16);
287impl_pow!(i32);
288impl_pow!(i64);
289impl_pow!(i128);
290impl_pow!(isize);
291
292impl<Bits, Base, Exp> Copy for Fix<Bits, Base, Exp> where Bits: Copy {}
295
296impl<Bits, Base, Exp> Clone for Fix<Bits, Base, Exp>
297where
298 Bits: Clone,
299{
300 fn clone(&self) -> Self {
301 Self::new(self.bits.clone())
302 }
303}
304
305impl<Bits, Base, Exp> Default for Fix<Bits, Base, Exp>
306where
307 Bits: Default,
308{
309 fn default() -> Self {
310 Self::new(Bits::default())
311 }
312}
313
314impl<Bits, Base, Exp> Hash for Fix<Bits, Base, Exp>
315where
316 Bits: Hash,
317{
318 fn hash<H>(&self, state: &mut H)
319 where
320 H: Hasher,
321 {
322 self.bits.hash(state);
323 }
324}
325
326impl<Bits, Base, Exp> Debug for Fix<Bits, Base, Exp>
327where
328 Bits: Debug,
329 Base: Unsigned,
330 Exp: Integer,
331{
332 fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
333 write!(f, "{:?}x{}^{}", self.bits, Base::to_u64(), Exp::to_i64())
334 }
335}
336
337impl<Bits, Base, Exp> Eq for Fix<Bits, Base, Exp> where Bits: Eq {}
340impl<Bits, Base, Exp> PartialEq for Fix<Bits, Base, Exp>
341where
342 Bits: PartialEq,
343{
344 fn eq(&self, rhs: &Self) -> bool {
345 self.bits == rhs.bits
346 }
347}
348
349impl<Bits, Base, Exp> PartialOrd for Fix<Bits, Base, Exp>
350where
351 Bits: PartialOrd,
352{
353 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
354 self.bits.partial_cmp(&rhs.bits)
355 }
356}
357
358impl<Bits, Base, Exp> Ord for Fix<Bits, Base, Exp>
359where
360 Bits: Ord,
361{
362 fn cmp(&self, rhs: &Self) -> Ordering {
363 self.bits.cmp(&rhs.bits)
364 }
365}
366
367impl<Bits, Base, Exp> Neg for Fix<Bits, Base, Exp>
370where
371 Bits: Neg<Output = Bits>,
372{
373 type Output = Self;
374 fn neg(self) -> Self {
375 Self::new(-self.bits)
376 }
377}
378
379impl<Bits, Base, Exp> Add for Fix<Bits, Base, Exp>
380where
381 Bits: Add<Output = Bits>,
382{
383 type Output = Self;
384 fn add(self, rhs: Self) -> Self {
385 Self::new(self.bits + rhs.bits)
386 }
387}
388
389impl<Bits, Base, Exp> Sub for Fix<Bits, Base, Exp>
390where
391 Bits: Sub<Output = Bits>,
392{
393 type Output = Self;
394 fn sub(self, rhs: Self) -> Self {
395 Self::new(self.bits - rhs.bits)
396 }
397}
398
399impl<Bits, Base, LExp, RExp> Mul<Fix<Bits, Base, RExp>> for Fix<Bits, Base, LExp>
400where
401 Bits: Mul<Output = Bits>,
402 LExp: Add<RExp>,
403{
404 type Output = Fix<Bits, Base, Sum<LExp, RExp>>;
405 fn mul(self, rhs: Fix<Bits, Base, RExp>) -> Self::Output {
406 Self::Output::new(self.bits * rhs.bits)
407 }
408}
409
410impl<Bits, Base, LExp, RExp> Div<Fix<Bits, Base, RExp>> for Fix<Bits, Base, LExp>
411where
412 Bits: Div<Output = Bits>,
413 LExp: Sub<RExp>,
414{
415 type Output = Fix<Bits, Base, Diff<LExp, RExp>>;
416 fn div(self, rhs: Fix<Bits, Base, RExp>) -> Self::Output {
417 Self::Output::new(self.bits / rhs.bits)
418 }
419}
420
421impl<Bits, Base, Exp> Rem for Fix<Bits, Base, Exp>
422where
423 Bits: Rem<Output = Bits>,
424{
425 type Output = Self;
426 fn rem(self, rhs: Self) -> Self {
427 Self::new(self.bits % rhs.bits)
428 }
429}
430
431impl<Bits, Base, Exp> Mul<Bits> for Fix<Bits, Base, Exp>
432where
433 Bits: Mul<Output = Bits>,
434{
435 type Output = Self;
436 fn mul(self, rhs: Bits) -> Self {
437 Self::new(self.bits * rhs)
438 }
439}
440
441impl<Bits, Base, Exp> Div<Bits> for Fix<Bits, Base, Exp>
442where
443 Bits: Div<Output = Bits>,
444{
445 type Output = Self;
446 fn div(self, rhs: Bits) -> Self {
447 Self::new(self.bits / rhs)
448 }
449}
450
451impl<Bits, Base, Exp> Rem<Bits> for Fix<Bits, Base, Exp>
452where
453 Bits: Rem<Output = Bits>,
454{
455 type Output = Self;
456 fn rem(self, rhs: Bits) -> Self {
457 Self::new(self.bits % rhs)
458 }
459}
460
461impl<Bits, Base, Exp> AddAssign for Fix<Bits, Base, Exp>
462where
463 Bits: AddAssign,
464{
465 fn add_assign(&mut self, rhs: Self) {
466 self.bits += rhs.bits;
467 }
468}
469
470impl<Bits, Base, Exp> SubAssign for Fix<Bits, Base, Exp>
471where
472 Bits: SubAssign,
473{
474 fn sub_assign(&mut self, rhs: Self) {
475 self.bits -= rhs.bits;
476 }
477}
478
479impl<Bits, Base, Exp> MulAssign<Bits> for Fix<Bits, Base, Exp>
480where
481 Bits: MulAssign,
482{
483 fn mul_assign(&mut self, rhs: Bits) {
484 self.bits *= rhs;
485 }
486}
487
488impl<Bits, Base, Exp> DivAssign<Bits> for Fix<Bits, Base, Exp>
489where
490 Bits: DivAssign,
491{
492 fn div_assign(&mut self, rhs: Bits) {
493 self.bits /= rhs;
494 }
495}
496
497impl<Bits, Base, LExp, RExp> RemAssign<Fix<Bits, Base, RExp>> for Fix<Bits, Base, LExp>
498where
499 Bits: RemAssign,
500{
501 fn rem_assign(&mut self, rhs: Fix<Bits, Base, RExp>) {
502 self.bits %= rhs.bits;
503 }
504}
505
506impl<Bits, Base, Exp> RemAssign<Bits> for Fix<Bits, Base, Exp>
507where
508 Bits: RemAssign,
509{
510 fn rem_assign(&mut self, rhs: Bits) {
511 self.bits %= rhs;
512 }
513}
514
515impl<Bits, Base, Exp> CheckedAdd for Fix<Bits, Base, Exp>
518where
519 Bits: CheckedAdd,
520{
521 fn checked_add(&self, v: &Self) -> Option<Self> {
522 self.bits.checked_add(&v.bits).map(Self::new)
523 }
524}
525
526impl<Bits, Base, Exp> CheckedSub for Fix<Bits, Base, Exp>
527where
528 Bits: CheckedSub,
529{
530 fn checked_sub(&self, v: &Self) -> Option<Self> {
531 self.bits.checked_sub(&v.bits).map(Self::new)
532 }
533}
534
535impl<Bits, Base, Exp> Fix<Bits, Base, Exp>
536where
537 Self: CheckedSub,
538 Bits: Copy,
539{
540 #[must_use]
541 pub fn abs_diff(&self, v: &Self) -> Fix<Bits, Base, Exp> {
542 self.checked_sub(v).unwrap_or_else(|| *v - *self)
543 }
544}
545
546pub trait CheckedMulFix<Rhs> {
548 type Output;
549 fn checked_mul(&self, v: &Rhs) -> Option<Self::Output>;
550}
551
552impl<Bits, Base, LExp, RExp> CheckedMulFix<Fix<Bits, Base, RExp>> for Fix<Bits, Base, LExp>
553where
554 Bits: CheckedMul,
555 LExp: Add<RExp>,
556{
557 type Output = Fix<Bits, Base, Sum<LExp, RExp>>;
558 fn checked_mul(&self, v: &Fix<Bits, Base, RExp>) -> Option<Self::Output> {
559 self.bits.checked_mul(&v.bits).map(Self::Output::new)
560 }
561}
562
563pub trait CheckedDivFix<Rhs> {
565 type Output;
566 fn checked_div(&self, v: &Rhs) -> Option<Self::Output>;
567}
568
569impl<Bits, Base, LExp, RExp> CheckedDivFix<Fix<Bits, Base, RExp>> for Fix<Bits, Base, LExp>
570where
571 Bits: CheckedDiv,
572 LExp: Sub<RExp>,
573{
574 type Output = Fix<Bits, Base, Diff<LExp, RExp>>;
575 fn checked_div(&self, v: &Fix<Bits, Base, RExp>) -> Option<Self::Output> {
576 self.bits.checked_div(&v.bits).map(Self::Output::new)
577 }
578}
579
580impl<Bits, Base, LExp, RExp> MulDiv<Fix<Bits, Base, RExp>> for Fix<Bits, Base, LExp>
581where
582 Bits: MulDiv,
583{
584 type Output = Fix<<Bits as MulDiv>::Output, Base, LExp>;
585 fn mul_div_ceil(
586 self,
587 num: Fix<Bits, Base, RExp>,
588 denom: Fix<Bits, Base, RExp>,
589 ) -> Option<Self::Output> {
590 self.bits
591 .mul_div_ceil(num.bits, denom.bits)
592 .map(Self::Output::new)
593 }
594 fn mul_div_floor(
595 self,
596 num: Fix<Bits, Base, RExp>,
597 denom: Fix<Bits, Base, RExp>,
598 ) -> Option<Self::Output> {
599 self.bits
600 .mul_div_floor(num.bits, denom.bits)
601 .map(Self::Output::new)
602 }
603 fn mul_div_round(
604 self,
605 num: Fix<Bits, Base, RExp>,
606 denom: Fix<Bits, Base, RExp>,
607 ) -> Option<Self::Output> {
608 self.bits
609 .mul_div_round(num.bits, denom.bits)
610 .map(Self::Output::new)
611 }
612}
613
614#[cfg(test)]
615mod tests {
616 use crate::aliases::si::{Kilo, Milli, Unit};
617 use crate::{CheckedAdd, CheckedDivFix, CheckedMulFix, CheckedSub, MulDiv};
618
619 #[test]
620 fn convert_milli_to_kilo() {
621 assert_eq!(Kilo::new(15), Milli::new(15_000_000).convert());
622 }
623
624 #[test]
625 fn convert_kilo_to_milli() {
626 assert_eq!(Milli::new(15_000_000), Kilo::new(15).convert());
627 }
628
629 #[test]
630 fn cmp() {
631 assert!(Kilo::new(1) < Kilo::new(2));
632 }
633
634 #[test]
635 fn neg() {
636 assert_eq!(Kilo::new(-1), -Kilo::new(1i32));
637 }
638
639 #[test]
640 fn add() {
641 assert_eq!(Kilo::new(3), Kilo::new(1) + Kilo::new(2));
642 }
643
644 #[test]
645 fn sub() {
646 assert_eq!(Kilo::new(1), Kilo::new(3) - Kilo::new(2));
647 }
648
649 #[test]
650 fn mul() {
651 assert_eq!(Unit::new(6), Kilo::new(2) * Milli::new(3));
652 }
653
654 #[test]
655 fn div() {
656 assert_eq!(Unit::new(3), Kilo::new(6) / Kilo::new(2));
657 }
658
659 #[test]
660 fn rem() {
661 assert_eq!(Kilo::new(1), Kilo::new(6) % Kilo::new(5));
662 }
663
664 #[test]
665 fn mul_bits() {
666 assert_eq!(Kilo::new(6), Kilo::new(2) * 3);
667 }
668
669 #[test]
670 fn div_bits() {
671 assert_eq!(Kilo::new(3), Kilo::new(6) / 2);
672 }
673
674 #[test]
675 fn rem_bits() {
676 assert_eq!(Kilo::new(1), Kilo::new(6) % 5);
677 }
678
679 #[test]
680 fn add_assign() {
681 let mut a = Kilo::new(1);
682 a += Kilo::new(2);
683 assert_eq!(Kilo::new(3), a);
684 }
685
686 #[test]
687 fn sub_assign() {
688 let mut a = Kilo::new(3);
689 a -= Kilo::new(2);
690 assert_eq!(Kilo::new(1), a);
691 }
692
693 #[test]
694 fn mul_assign_bits() {
695 let mut a = Kilo::new(2);
696 a *= 3;
697 assert_eq!(Kilo::new(6), a);
698 }
699
700 #[test]
701 fn div_assign_bits() {
702 let mut a = Kilo::new(6);
703 a /= 2;
704 assert_eq!(Kilo::new(3), a);
705 }
706
707 #[test]
708 fn rem_assign() {
709 let mut a = Kilo::new(6);
710 a %= Milli::new(5);
711 assert_eq!(Kilo::new(1), a);
712 }
713
714 #[test]
715 fn rem_assign_bits() {
716 let mut a = Kilo::new(6);
717 a %= 5;
718 assert_eq!(Kilo::new(1), a);
719 }
720
721 #[test]
722 fn checked_add_neg() {
723 let max = Kilo::new(u8::MAX);
724 let one = Kilo::new(1);
725 assert!(max.checked_add(&one).is_none())
726 }
727
728 #[test]
729 fn checked_add_pos() {
730 let forty = Kilo::new(40);
731 let two = Kilo::new(2);
732 assert_eq!(forty.checked_add(&two), Some(Kilo::new(42)))
733 }
734
735 #[test]
736 fn checked_sub_neg() {
737 let one = Kilo::new(1);
738 let max = Kilo::new(u8::MAX);
739 assert!(one.checked_sub(&max).is_none())
740 }
741
742 #[test]
743 fn checked_sub_pos() {
744 let fifty = Kilo::new(50);
745 let eight = Kilo::new(8);
746 assert_eq!(fifty.checked_sub(&eight), Some(Kilo::new(42)))
747 }
748
749 #[test]
750 fn checked_mul_neg() {
751 let fifty = Kilo::new(50);
752 let max = Kilo::new(u8::MAX);
753 assert!(fifty.checked_mul(&max).is_none())
754 }
755
756 #[test]
757 fn checked_mul_pos() {
758 let fifty = Kilo::new(50_u64);
759 assert_eq!(
760 fifty.checked_mul(&fifty).map(|out| out.convert()),
761 Some(Kilo::new(2_500_000_u64))
762 )
763 }
764
765 #[test]
766 fn checked_div_neg() {
767 let one = Unit::new(0);
768 assert!(one.checked_div(&one).is_none())
769 }
770
771 #[test]
772 fn checked_div_pos() {
773 let hundred = Kilo::new(100);
774 let five = Kilo::new(5);
775 assert_eq!(hundred.checked_div(&five), Some(Unit::new(20)))
776 }
777
778 #[test]
779 fn narrow_succeeds() {
780 let one = Milli::new(1000u128);
781 let mapped = one.narrow::<u64>();
782 assert_eq!(mapped, Some(Milli::new(1000u64)));
783 }
784
785 #[test]
786 fn narrow_fails() {
787 let one = Milli::new(1699u64);
788 let mapped = one.narrow::<u8>();
789 assert_eq!(mapped, None);
790 }
791
792 #[test]
793 fn widen_succeeds() {
794 let one = Milli::new(1340191u64);
795 let mapped = one.widen::<u128>();
796 assert_eq!(mapped, Milli::new(1340191u128));
797 }
798
799 #[test]
800 fn mul_div_ceil() {
801 let start = Milli::new(313459u64);
802 let mul = Milli::new(1200u64);
803 let div = Milli::new(2450u64);
804 assert_eq!(start.mul_div_ceil(mul, div), Some(Milli::new(153531)));
805 }
806
807 #[test]
808 fn mul_div_ceil_unit() {
809 let start = Milli::new(31345934u64);
810 let mul = Milli::new(1000u64);
811 let div = Milli::new(2000u64);
812 assert_eq!(start.mul_div_ceil(mul, div), Some(Milli::new(15672967u64)));
813 }
814
815 #[test]
816 fn mul_div_floor() {
817 let start = Milli::new(69_693u64);
818 let mul = Milli::new(5_192u64);
819 let div = Milli::new(190u64);
820 assert_eq!(start.mul_div_floor(mul, div), Some(Milli::new(1904452u64)));
821 }
822
823 #[test]
824 fn mul_div_floor_unit() {
825 let start = Milli::new(69_693u64);
826 let mul = Milli::new(1000u64);
827 let div = Milli::new(9u64);
828 assert_eq!(start.mul_div_floor(mul, div), Some(Milli::new(7743666u64)));
829 }
830
831 #[test]
832 fn mul_div_round() {
833 let start = Milli::new(1892u64);
834 let mul = Milli::new(3222u64);
835 let div = Milli::new(9999u64);
836 assert_eq!(start.mul_div_round(mul, div), Some(Milli::new(610u64)));
837 }
838
839 #[test]
840 fn mul_div_round_unit() {
841 let start = Milli::new(1892u64);
842 let mul = Milli::new(1000u64);
843 let div = Milli::new(322u64);
844 assert_eq!(start.mul_div_round(mul, div), Some(Milli::new(5876u64)));
845 }
846
847 #[test]
848 fn abs_diff() {
849 let start = Milli::new(u128::MIN);
850 let end = Milli::new(u128::MAX);
851 assert_eq!(start.abs_diff(&end), end);
852 }
853
854 #[test]
855 fn constant() {
856 assert_eq!(Kilo::constant(69u64), Kilo::new(69u64));
857 }
858}