-
Notifications
You must be signed in to change notification settings - Fork 704
/
fixed_point.rs
2216 lines (1850 loc) · 65.1 KB
/
fixed_point.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Decimal Fixed Point implementations for Substrate runtime.
use crate::{
helpers_128bit::{multiply_by_rational_with_rounding, sqrt},
traits::{
Bounded, CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedSub, One,
SaturatedConversion, Saturating, UniqueSaturatedInto, Zero,
},
PerThing, Perbill, Rounding, SignedRounding,
};
use codec::{CompactAs, Decode, Encode};
use sp_std::{
fmt::Debug,
ops::{self, Add, Div, Mul, Sub},
prelude::*,
};
#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
#[cfg(all(not(feature = "std"), feature = "serde"))]
use sp_std::alloc::string::{String, ToString};
/// Integer types that can be used to interact with `FixedPointNumber` implementations.
pub trait FixedPointOperand:
Copy
+ Clone
+ Bounded
+ Zero
+ Saturating
+ PartialOrd<Self>
+ UniqueSaturatedInto<u128>
+ TryFrom<u128>
+ CheckedNeg
{
}
impl<T> FixedPointOperand for T where
T: Copy
+ Clone
+ Bounded
+ Zero
+ Saturating
+ PartialOrd<Self>
+ UniqueSaturatedInto<u128>
+ TryFrom<u128>
+ CheckedNeg
{
}
/// Something that implements a decimal fixed point number.
///
/// The precision is given by `Self::DIV`, i.e. `1 / DIV` can be represented.
///
/// Each type can store numbers from `Self::Inner::min_value() / Self::DIV`
/// to `Self::Inner::max_value() / Self::DIV`.
/// This is also referred to as the _accuracy_ of the type in the documentation.
pub trait FixedPointNumber:
Sized
+ Copy
+ Default
+ Debug
+ Saturating
+ Bounded
+ Eq
+ PartialEq
+ Ord
+ PartialOrd
+ CheckedSub
+ CheckedAdd
+ CheckedMul
+ CheckedDiv
+ Add
+ Sub
+ Div
+ Mul
+ Zero
+ One
{
/// The underlying data type used for this fixed point number.
type Inner: Debug + One + CheckedMul + CheckedDiv + FixedPointOperand;
/// Precision of this fixed point implementation. It should be a power of `10`.
const DIV: Self::Inner;
/// Indicates if this fixed point implementation is signed or not.
const SIGNED: bool;
/// Precision of this fixed point implementation.
fn accuracy() -> Self::Inner {
Self::DIV
}
/// Builds this type from an integer number.
fn from_inner(int: Self::Inner) -> Self;
/// Consumes `self` and returns the inner raw value.
fn into_inner(self) -> Self::Inner;
/// Creates self from an integer number `int`.
///
/// Returns `Self::max` or `Self::min` if `int` exceeds accuracy.
fn saturating_from_integer<N: FixedPointOperand>(int: N) -> Self {
let mut n: I129 = int.into();
n.value = n.value.saturating_mul(Self::DIV.saturated_into());
Self::from_inner(from_i129(n).unwrap_or_else(|| to_bound(int, 0)))
}
/// Creates `self` from an integer number `int`.
///
/// Returns `None` if `int` exceeds accuracy.
fn checked_from_integer<N: Into<Self::Inner>>(int: N) -> Option<Self> {
let int: Self::Inner = int.into();
int.checked_mul(&Self::DIV).map(Self::from_inner)
}
/// Creates `self` from a rational number. Equal to `n / d`.
///
/// Panics if `d = 0`. Returns `Self::max` or `Self::min` if `n / d` exceeds accuracy.
fn saturating_from_rational<N: FixedPointOperand, D: FixedPointOperand>(n: N, d: D) -> Self {
if d == D::zero() {
panic!("attempt to divide by zero")
}
Self::checked_from_rational(n, d).unwrap_or_else(|| to_bound(n, d))
}
/// Creates `self` from a rational number. Equal to `n / d`.
///
/// Returns `None` if `d == 0` or `n / d` exceeds accuracy.
fn checked_from_rational<N: FixedPointOperand, D: FixedPointOperand>(
n: N,
d: D,
) -> Option<Self> {
if d == D::zero() {
return None
}
let n: I129 = n.into();
let d: I129 = d.into();
let negative = n.negative != d.negative;
multiply_by_rational_with_rounding(
n.value,
Self::DIV.unique_saturated_into(),
d.value,
Rounding::from_signed(SignedRounding::Minor, negative),
)
.and_then(|value| from_i129(I129 { value, negative }))
.map(Self::from_inner)
}
/// Checked multiplication for integer type `N`. Equal to `self * n`.
///
/// Returns `None` if the result does not fit in `N`.
fn checked_mul_int<N: FixedPointOperand>(self, n: N) -> Option<N> {
let lhs: I129 = self.into_inner().into();
let rhs: I129 = n.into();
let negative = lhs.negative != rhs.negative;
multiply_by_rational_with_rounding(
lhs.value,
rhs.value,
Self::DIV.unique_saturated_into(),
Rounding::from_signed(SignedRounding::Minor, negative),
)
.and_then(|value| from_i129(I129 { value, negative }))
}
/// Saturating multiplication for integer type `N`. Equal to `self * n`.
///
/// Returns `N::min` or `N::max` if the result does not fit in `N`.
fn saturating_mul_int<N: FixedPointOperand>(self, n: N) -> N {
self.checked_mul_int(n).unwrap_or_else(|| to_bound(self.into_inner(), n))
}
/// Checked division for integer type `N`. Equal to `self / d`.
///
/// Returns `None` if the result does not fit in `N` or `d == 0`.
fn checked_div_int<N: FixedPointOperand>(self, d: N) -> Option<N> {
let lhs: I129 = self.into_inner().into();
let rhs: I129 = d.into();
let negative = lhs.negative != rhs.negative;
lhs.value
.checked_div(rhs.value)
.and_then(|n| n.checked_div(Self::DIV.unique_saturated_into()))
.and_then(|value| from_i129(I129 { value, negative }))
}
/// Saturating division for integer type `N`. Equal to `self / d`.
///
/// Panics if `d == 0`. Returns `N::min` or `N::max` if the result does not fit in `N`.
fn saturating_div_int<N: FixedPointOperand>(self, d: N) -> N {
if d == N::zero() {
panic!("attempt to divide by zero")
}
self.checked_div_int(d).unwrap_or_else(|| to_bound(self.into_inner(), d))
}
/// Saturating multiplication for integer type `N`, adding the result back.
/// Equal to `self * n + n`.
///
/// Returns `N::min` or `N::max` if the multiplication or final result does not fit in `N`.
fn saturating_mul_acc_int<N: FixedPointOperand>(self, n: N) -> N {
if self.is_negative() && n > N::zero() {
n.saturating_sub(Self::zero().saturating_sub(self).saturating_mul_int(n))
} else {
self.saturating_mul_int(n).saturating_add(n)
}
}
/// Saturating absolute value.
///
/// Returns `Self::max` if `self == Self::min`.
fn saturating_abs(self) -> Self {
let inner = self.into_inner();
if inner >= Self::Inner::zero() {
self
} else {
Self::from_inner(inner.checked_neg().unwrap_or_else(Self::Inner::max_value))
}
}
/// Takes the reciprocal (inverse). Equal to `1 / self`.
///
/// Returns `None` if `self = 0`.
fn reciprocal(self) -> Option<Self> {
Self::one().checked_div(&self)
}
/// Checks if the number is one.
fn is_one(&self) -> bool {
self.into_inner() == Self::Inner::one()
}
/// Returns `true` if `self` is positive and `false` if the number is zero or negative.
fn is_positive(self) -> bool {
self.into_inner() > Self::Inner::zero()
}
/// Returns `true` if `self` is negative and `false` if the number is zero or positive.
fn is_negative(self) -> bool {
self.into_inner() < Self::Inner::zero()
}
/// Returns the integer part.
fn trunc(self) -> Self {
self.into_inner()
.checked_div(&Self::DIV)
.expect("panics only if DIV is zero, DIV is not zero; qed")
.checked_mul(&Self::DIV)
.map(Self::from_inner)
.expect("can not overflow since fixed number is >= integer part")
}
/// Returns the fractional part.
///
/// Note: the returned fraction will be non-negative for negative numbers,
/// except in the case where the integer part is zero.
fn frac(self) -> Self {
let integer = self.trunc();
let fractional = self.saturating_sub(integer);
if integer == Self::zero() {
fractional
} else {
fractional.saturating_abs()
}
}
/// Returns the smallest integer greater than or equal to a number.
///
/// Saturates to `Self::max` (truncated) if the result does not fit.
fn ceil(self) -> Self {
if self.is_negative() {
self.trunc()
} else if self.frac() == Self::zero() {
self
} else {
self.saturating_add(Self::one()).trunc()
}
}
/// Returns the largest integer less than or equal to a number.
///
/// Saturates to `Self::min` (truncated) if the result does not fit.
fn floor(self) -> Self {
if self.is_negative() {
self.saturating_sub(Self::one()).trunc()
} else {
self.trunc()
}
}
/// Returns the number rounded to the nearest integer. Rounds half-way cases away from 0.0.
///
/// Saturates to `Self::min` or `Self::max` (truncated) if the result does not fit.
fn round(self) -> Self {
let n = self.frac().saturating_mul(Self::saturating_from_integer(10));
if n < Self::saturating_from_integer(5) {
self.trunc()
} else if self.is_positive() {
self.saturating_add(Self::one()).trunc()
} else {
self.saturating_sub(Self::one()).trunc()
}
}
}
/// Data type used as intermediate storage in some computations to avoid overflow.
struct I129 {
value: u128,
negative: bool,
}
impl<N: FixedPointOperand> From<N> for I129 {
fn from(n: N) -> I129 {
if n < N::zero() {
let value: u128 = n
.checked_neg()
.map(|n| n.unique_saturated_into())
.unwrap_or_else(|| N::max_value().unique_saturated_into().saturating_add(1));
I129 { value, negative: true }
} else {
I129 { value: n.unique_saturated_into(), negative: false }
}
}
}
/// Transforms an `I129` to `N` if it is possible.
fn from_i129<N: FixedPointOperand>(n: I129) -> Option<N> {
let max_plus_one: u128 = N::max_value().unique_saturated_into().saturating_add(1);
if n.negative && N::min_value() < N::zero() && n.value == max_plus_one {
Some(N::min_value())
} else {
let unsigned_inner: N = n.value.try_into().ok()?;
let inner = if n.negative { unsigned_inner.checked_neg()? } else { unsigned_inner };
Some(inner)
}
}
/// Returns `R::max` if the sign of `n * m` is positive, `R::min` otherwise.
fn to_bound<N: FixedPointOperand, D: FixedPointOperand, R: Bounded>(n: N, m: D) -> R {
if (n < N::zero()) != (m < D::zero()) {
R::min_value()
} else {
R::max_value()
}
}
macro_rules! implement_fixed {
(
$name:ident,
$test_mod:ident,
$inner_type:ty,
$signed:tt,
$div:tt,
$title:expr $(,)?
) => {
/// A fixed point number representation in the range.
#[doc = $title]
#[derive(
Encode,
Decode,
CompactAs,
Default,
Copy,
Clone,
codec::MaxEncodedLen,
PartialEq,
Eq,
PartialOrd,
Ord,
scale_info::TypeInfo,
)]
pub struct $name($inner_type);
impl From<$inner_type> for $name {
fn from(int: $inner_type) -> Self {
$name::saturating_from_integer(int)
}
}
impl<N: FixedPointOperand, D: FixedPointOperand> From<(N, D)> for $name {
fn from(r: (N, D)) -> Self {
$name::saturating_from_rational(r.0, r.1)
}
}
impl FixedPointNumber for $name {
type Inner = $inner_type;
const DIV: Self::Inner = $div;
const SIGNED: bool = $signed;
fn from_inner(inner: Self::Inner) -> Self {
Self(inner)
}
fn into_inner(self) -> Self::Inner {
self.0
}
}
impl $name {
/// Create a new instance from the given `inner` value.
///
/// `const` version of `FixedPointNumber::from_inner`.
pub const fn from_inner(inner: $inner_type) -> Self {
Self(inner)
}
/// Return the instance's inner value.
///
/// `const` version of `FixedPointNumber::into_inner`.
pub const fn into_inner(self) -> $inner_type {
self.0
}
/// Creates self from a `u32`.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
pub const fn from_u32(n: u32) -> Self {
Self::from_inner((n as $inner_type) * $div)
}
/// Convert from a `float` value.
#[cfg(any(feature = "std", test))]
pub fn from_float(x: f64) -> Self {
Self((x * (<Self as FixedPointNumber>::DIV as f64)) as $inner_type)
}
/// Convert from a `Perbill` value.
pub const fn from_perbill(n: Perbill) -> Self {
Self::from_rational(n.deconstruct() as u128, 1_000_000_000)
}
/// Convert into a `Perbill` value. Will saturate if above one or below zero.
pub const fn into_perbill(self) -> Perbill {
if self.0 <= 0 {
Perbill::zero()
} else if self.0 >= $div {
Perbill::one()
} else {
match multiply_by_rational_with_rounding(
self.0 as u128,
1_000_000_000,
Self::DIV as u128,
Rounding::NearestPrefDown,
) {
Some(value) => {
if value > (u32::max_value() as u128) {
panic!(
"prior logic ensures 0<self.0<DIV; \
multiply ensures 0<self.0<1000000000; \
qed"
);
}
Perbill::from_parts(value as u32)
},
None => Perbill::zero(),
}
}
}
/// Convert into a `float` value.
#[cfg(any(feature = "std", test))]
pub fn to_float(self) -> f64 {
self.0 as f64 / <Self as FixedPointNumber>::DIV as f64
}
/// Attempt to convert into a `PerThing`. This will succeed iff `self` is at least zero
/// and at most one. If it is out of bounds, it will result in an error returning the
/// clamped value.
pub fn try_into_perthing<P: PerThing>(self) -> Result<P, P> {
if self < Self::zero() {
Err(P::zero())
} else if self > Self::one() {
Err(P::one())
} else {
Ok(P::from_rational(self.0 as u128, $div))
}
}
/// Attempt to convert into a `PerThing`. This will always succeed resulting in a
/// clamped value if `self` is less than zero or greater than one.
pub fn into_clamped_perthing<P: PerThing>(self) -> P {
if self < Self::zero() {
P::zero()
} else if self > Self::one() {
P::one()
} else {
P::from_rational(self.0 as u128, $div)
}
}
/// Negate the value.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
pub const fn neg(self) -> Self {
Self(0 - self.0)
}
/// Take the square root of a positive value.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
pub const fn sqrt(self) -> Self {
match self.try_sqrt() {
Some(v) => v,
None => panic!("sqrt overflow or negative input"),
}
}
/// Compute the square root, rounding as desired. If it overflows or is negative, then
/// `None` is returned.
pub const fn try_sqrt(self) -> Option<Self> {
if self.0 == 0 {
return Some(Self(0))
}
if self.0 < 1 {
return None
}
let v = self.0 as u128;
// Want x' = sqrt(x) where x = n/D and x' = n'/D (D is fixed)
// Our prefered way is:
// sqrt(n/D) = sqrt(nD / D^2) = sqrt(nD)/sqrt(D^2) = sqrt(nD)/D
// ergo n' = sqrt(nD)
// but this requires nD to fit into our type.
// if nD doesn't fit then we can fall back on:
// sqrt(nD) = sqrt(n)*sqrt(D)
// computing them individually and taking the product at the end. we will lose some
// precision though.
let maybe_vd = u128::checked_mul(v, $div);
let r = if let Some(vd) = maybe_vd { sqrt(vd) } else { sqrt(v) * sqrt($div) };
Some(Self(r as $inner_type))
}
/// Add a value and return the result.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
pub const fn add(self, rhs: Self) -> Self {
Self(self.0 + rhs.0)
}
/// Subtract a value and return the result.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
pub const fn sub(self, rhs: Self) -> Self {
Self(self.0 - rhs.0)
}
/// Multiply by a value and return the result.
///
/// Result will be rounded to the nearest representable value, rounding down if it is
/// equidistant between two neighbours.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
pub const fn mul(self, rhs: Self) -> Self {
match $name::const_checked_mul(self, rhs) {
Some(v) => v,
None => panic!("attempt to multiply with overflow"),
}
}
/// Divide by a value and return the result.
///
/// Result will be rounded to the nearest representable value, rounding down if it is
/// equidistant between two neighbours.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
pub const fn div(self, rhs: Self) -> Self {
match $name::const_checked_div(self, rhs) {
Some(v) => v,
None => panic!("attempt to divide with overflow or NaN"),
}
}
/// Convert into an `I129` format value.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
const fn into_i129(self) -> I129 {
#[allow(unused_comparisons)]
if self.0 < 0 {
let value = match self.0.checked_neg() {
Some(n) => n as u128,
None => u128::saturating_add(<$inner_type>::max_value() as u128, 1),
};
I129 { value, negative: true }
} else {
I129 { value: self.0 as u128, negative: false }
}
}
/// Convert from an `I129` format value.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
const fn from_i129(n: I129) -> Option<Self> {
let max_plus_one = u128::saturating_add(<$inner_type>::max_value() as u128, 1);
#[allow(unused_comparisons)]
let inner = if n.negative && <$inner_type>::min_value() < 0 && n.value == max_plus_one {
<$inner_type>::min_value()
} else {
let unsigned_inner = n.value as $inner_type;
if unsigned_inner as u128 != n.value || (unsigned_inner > 0) != (n.value > 0) {
return None
};
if n.negative {
match unsigned_inner.checked_neg() {
Some(v) => v,
None => return None,
}
} else {
unsigned_inner
}
};
Some(Self(inner))
}
/// Calculate an approximation of a rational.
///
/// Result will be rounded to the nearest representable value, rounding down if it is
/// equidistant between two neighbours.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
pub const fn from_rational(a: u128, b: u128) -> Self {
Self::from_rational_with_rounding(a, b, Rounding::NearestPrefDown)
}
/// Calculate an approximation of a rational with custom rounding.
///
/// WARNING: This is a `const` function designed for convenient use at build time and
/// will panic on overflow. Ensure that any inputs are sensible.
pub const fn from_rational_with_rounding(a: u128, b: u128, rounding: Rounding) -> Self {
if b == 0 {
panic!("attempt to divide by zero in from_rational")
}
match multiply_by_rational_with_rounding(Self::DIV as u128, a, b, rounding) {
Some(value) => match Self::from_i129(I129 { value, negative: false }) {
Some(x) => x,
None => panic!("overflow in from_rational"),
},
None => panic!("overflow in from_rational"),
}
}
/// Multiply by another value, returning `None` in the case of an error.
///
/// Result will be rounded to the nearest representable value, rounding down if it is
/// equidistant between two neighbours.
pub const fn const_checked_mul(self, other: Self) -> Option<Self> {
self.const_checked_mul_with_rounding(other, SignedRounding::NearestPrefLow)
}
/// Multiply by another value with custom rounding, returning `None` in the case of an
/// error.
///
/// Result will be rounded to the nearest representable value, rounding down if it is
/// equidistant between two neighbours.
pub const fn const_checked_mul_with_rounding(
self,
other: Self,
rounding: SignedRounding,
) -> Option<Self> {
let lhs = self.into_i129();
let rhs = other.into_i129();
let negative = lhs.negative != rhs.negative;
match multiply_by_rational_with_rounding(
lhs.value,
rhs.value,
Self::DIV as u128,
Rounding::from_signed(rounding, negative),
) {
Some(value) => Self::from_i129(I129 { value, negative }),
None => None,
}
}
/// Divide by another value, returning `None` in the case of an error.
///
/// Result will be rounded to the nearest representable value, rounding down if it is
/// equidistant between two neighbours.
pub const fn const_checked_div(self, other: Self) -> Option<Self> {
self.checked_rounding_div(other, SignedRounding::NearestPrefLow)
}
/// Divide by another value with custom rounding, returning `None` in the case of an
/// error.
///
/// Result will be rounded to the nearest representable value, rounding down if it is
/// equidistant between two neighbours.
pub const fn checked_rounding_div(
self,
other: Self,
rounding: SignedRounding,
) -> Option<Self> {
if other.0 == 0 {
return None
}
let lhs = self.into_i129();
let rhs = other.into_i129();
let negative = lhs.negative != rhs.negative;
match multiply_by_rational_with_rounding(
lhs.value,
Self::DIV as u128,
rhs.value,
Rounding::from_signed(rounding, negative),
) {
Some(value) => Self::from_i129(I129 { value, negative }),
None => None,
}
}
}
impl Saturating for $name {
fn saturating_add(self, rhs: Self) -> Self {
Self(self.0.saturating_add(rhs.0))
}
fn saturating_sub(self, rhs: Self) -> Self {
Self(self.0.saturating_sub(rhs.0))
}
fn saturating_mul(self, rhs: Self) -> Self {
self.checked_mul(&rhs).unwrap_or_else(|| to_bound(self.0, rhs.0))
}
fn saturating_pow(self, exp: usize) -> Self {
if exp == 0 {
return Self::saturating_from_integer(1)
}
let exp = exp as u32;
let msb_pos = 32 - exp.leading_zeros();
let mut result = Self::saturating_from_integer(1);
let mut pow_val = self;
for i in 0..msb_pos {
if ((1 << i) & exp) > 0 {
result = result.saturating_mul(pow_val);
}
pow_val = pow_val.saturating_mul(pow_val);
}
result
}
}
impl ops::Neg for $name {
type Output = Self;
fn neg(self) -> Self::Output {
Self(<Self as FixedPointNumber>::Inner::zero() - self.0)
}
}
impl ops::Add for $name {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self(self.0 + rhs.0)
}
}
impl ops::Sub for $name {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self(self.0 - rhs.0)
}
}
impl ops::Mul for $name {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
self.checked_mul(&rhs)
.unwrap_or_else(|| panic!("attempt to multiply with overflow"))
}
}
impl ops::Div for $name {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
if rhs.0 == 0 {
panic!("attempt to divide by zero")
}
self.checked_div(&rhs)
.unwrap_or_else(|| panic!("attempt to divide with overflow"))
}
}
impl CheckedSub for $name {
fn checked_sub(&self, rhs: &Self) -> Option<Self> {
self.0.checked_sub(rhs.0).map(Self)
}
}
impl CheckedAdd for $name {
fn checked_add(&self, rhs: &Self) -> Option<Self> {
self.0.checked_add(rhs.0).map(Self)
}
}
impl CheckedDiv for $name {
fn checked_div(&self, other: &Self) -> Option<Self> {
if other.0 == 0 {
return None
}
let lhs: I129 = self.0.into();
let rhs: I129 = other.0.into();
let negative = lhs.negative != rhs.negative;
// Note that this uses the old (well-tested) code with sign-ignorant rounding. This
// is equivalent to the `SignedRounding::NearestPrefMinor`. This means it is
// expected to give exactly the same result as `const_checked_div` when the result
// is positive and a result up to one epsilon greater when it is negative.
multiply_by_rational_with_rounding(
lhs.value,
Self::DIV as u128,
rhs.value,
Rounding::from_signed(SignedRounding::Minor, negative),
)
.and_then(|value| from_i129(I129 { value, negative }))
.map(Self)
}
}
impl CheckedMul for $name {
fn checked_mul(&self, other: &Self) -> Option<Self> {
let lhs: I129 = self.0.into();
let rhs: I129 = other.0.into();
let negative = lhs.negative != rhs.negative;
multiply_by_rational_with_rounding(
lhs.value,
rhs.value,
Self::DIV as u128,
Rounding::from_signed(SignedRounding::Minor, negative),
)
.and_then(|value| from_i129(I129 { value, negative }))
.map(Self)
}
}
impl Bounded for $name {
fn min_value() -> Self {
Self(<Self as FixedPointNumber>::Inner::min_value())
}
fn max_value() -> Self {
Self(<Self as FixedPointNumber>::Inner::max_value())
}
}
impl Zero for $name {
fn zero() -> Self {
Self::from_inner(<Self as FixedPointNumber>::Inner::zero())
}
fn is_zero(&self) -> bool {
self.into_inner() == <Self as FixedPointNumber>::Inner::zero()
}
}
impl One for $name {
fn one() -> Self {
Self::from_inner(Self::DIV)
}
}
impl sp_std::fmt::Debug for $name {
#[cfg(feature = "std")]
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
let integral = {
let int = self.0 / Self::accuracy();
let signum_for_zero = if int == 0 && self.is_negative() { "-" } else { "" };
format!("{}{}", signum_for_zero, int)
};
let precision = (Self::accuracy() as f64).log10() as usize;
let fractional = format!(
"{:0>weight$}",
((self.0 % Self::accuracy()) as i128).abs(),
weight = precision
);
write!(f, "{}({}.{})", stringify!($name), integral, fractional)
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
Ok(())
}
}
impl<P: PerThing> From<P> for $name
where
P::Inner: FixedPointOperand,
{
fn from(p: P) -> Self {
let accuracy = P::ACCURACY;
let value = p.deconstruct();
$name::saturating_from_rational(value, accuracy)
}
}
impl sp_std::fmt::Display for $name {
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl sp_std::str::FromStr for $name {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let inner: <Self as FixedPointNumber>::Inner =
s.parse().map_err(|_| "invalid string input for fixed point number")?;
Ok(Self::from_inner(inner))
}
}
// Manual impl `Serialize` as serde_json does not support i128.
// TODO: remove impl if issue https://github.com/serde-rs/json/issues/548 fixed.
#[cfg(feature = "serde")]
impl Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
// Manual impl `Deserialize` as serde_json does not support i128.
// TODO: remove impl if issue https://github.com/serde-rs/json/issues/548 fixed.
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use sp_std::str::FromStr;
let s = String::deserialize(deserializer)?;
$name::from_str(&s).map_err(de::Error::custom)
}
}
#[cfg(test)]
mod $test_mod {
use super::*;
use crate::{Perbill, Percent, Permill, Perquintill};
fn max() -> $name {
$name::max_value()
}
fn min() -> $name {
$name::min_value()
}
fn precision() -> usize {
($name::accuracy() as f64).log10() as usize
}
#[test]
fn macro_preconditions() {
assert!($name::DIV > 0);
}
#[test]