-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
number.rs
1296 lines (1134 loc) · 44.5 KB
/
number.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
// Reference rust implementation of AluVM (arithmetic logic unit virtual machine).
// To find more on AluVM please check <https://github.com/internet2-org/aluvm-spec>
//
// Designed & written in 2021 by
// Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
// This work is donated to LNP/BP Standards Association by Pandora Core AG
//
// This software is licensed under the terms of MIT License.
// You should have received a copy of the MIT License along with this software.
// If not, see <https://opensource.org/licenses/MIT>.
//! Module defining number layout (integer, signed/unsigned, float etc) and universal in-memory
//! number representation.
use alloc::format;
use alloc::string::{String, ToString};
use core::fmt::{
self, Debug, Display, Formatter, LowerExp, LowerHex, Octal, UpperExp, UpperHex, Write,
};
use core::hash::{Hash, Hasher};
use core::ops::{
Deref, Index, IndexMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
};
use core::str::FromStr;
use amplify::num::{u1024, u256, u512};
use half::bf16;
use rustc_apfloat::{ieee, Float, Status};
/// Trait of different number layouts
pub trait NumberLayout: Copy {
/// Returns how many bits are used by the layout
#[inline]
fn bits(self) -> u16 { self.bytes() * 8 }
/// Returns how many bytes are used by the layout
fn bytes(self) -> u16;
/// Returns whether layout supports signed numbers
fn is_signed(self) -> bool;
/// Detects whether layout uses fixed number of bits or may be applied to the numbers with
/// arbitrary bit size.
#[inline]
fn is_fixed_width(self) -> bool { true }
/// Returns bit number which keeps (or may be used to store) sign information
fn sign_bit(self) -> u16;
/// Returns byte number which keeps (or may be used to store) sign information
fn sign_byte(self) -> u16;
}
/// Layout of the value encoding.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[display(inner)]
pub enum Layout {
/// Integer layout
Integer(IntLayout),
/// Float layouts
Float(FloatLayout),
}
impl Layout {
/// Returns signed integer layout
#[inline]
pub fn signed(bytes: u16) -> Layout { Layout::Integer(IntLayout::signed(bytes)) }
/// Returns unsigned integer layout
#[inline]
pub fn unsigned(bytes: u16) -> Layout { Layout::Integer(IntLayout::unsigned(bytes)) }
/// Constructs float layout
#[inline]
pub fn float(layout: FloatLayout) -> Layout { Layout::Float(layout) }
/// Detects if the number layout is unsigned integer
#[inline]
pub fn is_unsigned_int(self) -> bool {
matches!(self, Layout::Integer(IntLayout { signed: false, .. }))
}
/// Detects if the number layout is signed integer
#[inline]
pub fn is_signed_int(self) -> bool {
matches!(self, Layout::Integer(IntLayout { signed: true, .. }))
}
/// Detects if the number layout is one of integer (signed or unsigned) layouts
#[inline]
pub fn is_integer(self) -> bool { matches!(self, Layout::Integer(_)) }
/// Detects if the number layout is one of float layouts
#[inline]
pub fn is_float(self) -> bool { matches!(self, Layout::Float(_)) }
/// Converts unsigned integer layout into signed; does nothing for float layouts
#[inline]
pub fn into_signed(mut self) -> Layout {
if let Layout::Integer(il) = &mut self {
*il = il.into_signed()
}
self
}
/// Updates integer layout (if used) to match signed/unsigned format of some other layout.
/// Does nothing if any of the layouts are not integer layouts or `other` layout is unsigned.
#[inline]
pub fn using_sign(mut self, other: Layout) -> Layout {
if let (Layout::Integer(il), Layout::Integer(il2)) = (&mut self, other) {
*il = il2.using_sign(il2)
}
self
}
}
impl NumberLayout for Layout {
#[inline]
fn bytes(self) -> u16 {
match self {
Layout::Integer(il) => il.bytes(),
Layout::Float(fl) => fl.bytes(),
}
}
#[inline]
fn is_signed(self) -> bool { matches!(self, Layout::Integer(IntLayout { signed: true, .. })) }
#[inline]
fn sign_bit(self) -> u16 {
match self {
Layout::Integer(il) => il.sign_bit(),
Layout::Float(fl) => fl.sign_bit(),
}
}
#[inline]
fn sign_byte(self) -> u16 {
match self {
Layout::Integer(il) => il.sign_byte(),
Layout::Float(fl) => fl.sign_byte(),
}
}
}
/// Layout of the integer value encoding.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct IntLayout {
/// Format of the integer (signed or unsigned).
///
/// Unsigned integer: exact correspondence of bits to bytes in little-endian bit format
///
/// Signed integer: the most significant bit (highest bit) indicates value sign. For the
/// negative numbers the value is modulo-divided by the maximum number.
pub signed: bool,
/// Number of bytes occupied by the number
pub bytes: u16,
}
impl Display for IntLayout {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_char(if self.signed { 'i' } else { 'u' })?;
write!(f, "{}", self.bits())
}
}
impl IntLayout {
/// Returns signed integer layout
#[inline]
pub fn signed(bytes: u16) -> IntLayout { Self { signed: true, bytes } }
/// Returns unsigned integer layout
#[inline]
pub fn unsigned(bytes: u16) -> IntLayout { Self { signed: false, bytes } }
/// Converts unsigned integer layout into signed
#[inline]
pub fn into_signed(mut self) -> IntLayout {
self.signed = true;
self
}
/// Updates layout (if used) to match signed/unsigned format of some other layout.
#[inline]
pub fn using_sign(mut self, other: IntLayout) -> IntLayout {
self.signed = other.signed;
self
}
/// Returns whether a `usize`-value fits the layout dimensions.
///
/// # Panics
///
/// Panics on platforms where usize is less than `u64`
pub fn fits_usize(self, value: usize) -> bool {
(self.bytes() <= 8 && value > u64::MAX as usize)
|| (self.bytes() <= 4 && value > u32::MAX as usize)
|| (self.bytes() <= 2 && value > u16::MAX as usize)
|| (self.bytes() <= 1 && value > u8::MAX as usize)
}
}
impl NumberLayout for IntLayout {
#[inline]
fn bytes(self) -> u16 { self.bytes }
#[inline]
fn is_signed(self) -> bool { self.signed }
#[inline]
fn sign_bit(self) -> u16 { self.bits() - 1 }
#[inline]
fn sign_byte(self) -> u16 { self.bytes() - 1 }
}
impl From<IntLayout> for Layout {
#[inline]
fn from(layout: IntLayout) -> Self { Layout::Integer(layout) }
}
impl From<&IntLayout> for Layout {
#[inline]
fn from(layout: &IntLayout) -> Self { Layout::Integer(*layout) }
}
/// Layout of the float value encoding.
///
/// Defines bit dimensionality and encoding format for float types.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
pub enum FloatLayout {
/// 16-bit bfloat16 format used in machine learning
#[display("bfloat16")]
BFloat16 = 2,
/// 16-bit IEEE-754 binary16 half-precision
#[display("ieee:binary16")]
IeeeHalf = 3,
/// 32-bit IEEE-754 binary32 single-precision
#[display("ieee:binary32")]
IeeeSingle = 4,
/// 64-bit IEEE-754 binary64 double-precision
#[display("ieee:binary64")]
IeeeDouble = 5,
/// 80-bit IEEE-754 extended precision
#[display("x87:binary80")]
X87DoubleExt = 6,
/// 128-bit IEEE-754 binary128 quadruple precision
#[display("ieee:binary128")]
IeeeQuad = 7,
/// 256-bit IEEE-754 binary256 octuple precision
#[display("ieee:binary256")]
IeeeOct = 8,
/// 512-bit tapered floating point
#[display("tapered:binary512")]
FloatTapered = 9,
}
impl NumberLayout for FloatLayout {
fn bytes(self) -> u16 {
match self {
FloatLayout::BFloat16 => 2,
FloatLayout::IeeeHalf => 2,
FloatLayout::IeeeSingle => 4,
FloatLayout::IeeeDouble => 8,
FloatLayout::X87DoubleExt => 10,
FloatLayout::IeeeQuad => 16,
FloatLayout::IeeeOct => 32,
FloatLayout::FloatTapered => 64,
}
}
#[inline]
fn is_signed(self) -> bool { true }
#[inline]
fn sign_bit(self) -> u16 { self.bits() - 1 }
#[inline]
fn sign_byte(self) -> u16 { self.bytes() - 1 }
}
impl FloatLayout {
/// Constructs [`FloatLayout`] from byte representation
pub fn with(value: u8) -> Option<Self> {
Some(match value {
x if x == FloatLayout::BFloat16 as u8 => FloatLayout::BFloat16,
x if x == FloatLayout::IeeeHalf as u8 => FloatLayout::IeeeHalf,
x if x == FloatLayout::IeeeSingle as u8 => FloatLayout::IeeeSingle,
x if x == FloatLayout::IeeeDouble as u8 => FloatLayout::IeeeDouble,
x if x == FloatLayout::IeeeQuad as u8 => FloatLayout::IeeeQuad,
x if x == FloatLayout::IeeeOct as u8 => FloatLayout::IeeeOct,
x if x == FloatLayout::X87DoubleExt as u8 => FloatLayout::X87DoubleExt,
x if x == FloatLayout::FloatTapered as u8 => FloatLayout::FloatTapered,
_ => return None,
})
}
/// Detects if layout is used for encoding floating-point numbers
#[inline]
pub fn is_float(self) -> bool { self as u8 > 1 }
/// Detects if this layout uses variable significand/exponent size
#[inline]
pub fn is_tapered(self) -> bool { self == FloatLayout::FloatTapered }
/// For float numbers returns range of bits used by significand. For integer numbers always
/// `None`.
#[inline]
pub fn significand_pos(self) -> Option<Range<u16>> {
match self {
FloatLayout::BFloat16 => Some(0..7),
FloatLayout::IeeeHalf => Some(0..10),
FloatLayout::IeeeSingle => Some(0..23),
FloatLayout::IeeeDouble => Some(0..52),
FloatLayout::X87DoubleExt => Some(0..64),
FloatLayout::IeeeQuad => Some(0..112),
FloatLayout::IeeeOct => Some(0..236),
FloatLayout::FloatTapered => None,
}
}
/// For float numbers returns range of bits used by exponent. For integer numbers always `None`.
#[inline]
pub fn exponent_pos(self) -> Option<Range<u16>> {
match self {
FloatLayout::BFloat16 => Some(7..15),
FloatLayout::IeeeHalf => Some(10..15),
FloatLayout::IeeeSingle => Some(23..31),
FloatLayout::IeeeDouble => Some(52..63),
FloatLayout::X87DoubleExt => Some(64..79),
FloatLayout::IeeeQuad => Some(112..127),
FloatLayout::IeeeOct => Some(236..255),
FloatLayout::FloatTapered => None,
}
}
}
impl From<FloatLayout> for Layout {
#[inline]
fn from(layout: FloatLayout) -> Self { Layout::Float(layout) }
}
impl From<&FloatLayout> for Layout {
#[inline]
fn from(layout: &FloatLayout) -> Self { Layout::Float(*layout) }
}
/// Representation of the value from a register, which may be `None` if the register is unset.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, From)]
pub struct MaybeNumber(Option<Number>);
impl MaybeNumber {
/// Creates [`MaybeNumber`] without assigning a value to it
#[inline]
pub fn none() -> MaybeNumber { MaybeNumber(None) }
/// Creates [`MaybeNumber`] assigning a value to it
#[inline]
pub fn some(val: Number) -> MaybeNumber { MaybeNumber(Some(val)) }
/// Transforms internal value layout returning whether this was possible without discarding any
/// bit information
#[inline]
pub fn reshape(&mut self, to: Layout) -> bool {
match self.0 {
None => true,
Some(ref mut val) => val.reshape(to),
}
}
}
impl From<Number> for MaybeNumber {
fn from(val: Number) -> Self { MaybeNumber(Some(val)) }
}
impl From<&Number> for MaybeNumber {
fn from(val: &Number) -> Self { MaybeNumber(Some(*val)) }
}
impl From<&Option<Number>> for MaybeNumber {
fn from(val: &Option<Number>) -> Self { MaybeNumber(*val) }
}
impl From<Option<&Number>> for MaybeNumber {
fn from(val: Option<&Number>) -> Self { MaybeNumber(val.copied()) }
}
impl From<MaybeNumber> for Option<Number> {
fn from(val: MaybeNumber) -> Self { val.0 }
}
impl Deref for MaybeNumber {
type Target = Option<Number>;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl Display for MaybeNumber {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self.0 {
None => f.write_str("~"),
Some(ref val) => Display::fmt(val, f),
}
}
}
/// Type holding number of any layout
#[derive(Copy, Clone)]
pub struct Number {
/// Internal number representation, up to the possible maximum size of any supported number
/// layout
bytes: [u8; 1024],
/// Number layout used by the value
layout: Layout,
}
impl Hash for Number {
fn hash<H: Hasher>(&self, state: &mut H) {
let clean = self.to_clean();
clean.layout.hash(state);
state.write(&clean.bytes);
}
}
impl Default for Number {
fn default() -> Number {
Number { layout: Layout::Integer(IntLayout::unsigned(1)), bytes: [0u8; 1024] }
}
}
impl AsRef<[u8]> for Number {
fn as_ref(&self) -> &[u8] { &self[..] }
}
impl AsMut<[u8]> for Number {
fn as_mut(&mut self) -> &mut [u8] { &mut self[..] }
}
impl Index<u16> for Number {
type Output = u8;
fn index(&self, index: u16) -> &Self::Output {
assert!(index < self.len());
&self.bytes[index as usize]
}
}
impl IndexMut<u16> for Number {
fn index_mut(&mut self, index: u16) -> &mut Self::Output {
assert!(index < self.len());
&mut self.bytes[index as usize]
}
}
impl Index<RangeFull> for Number {
type Output = [u8];
fn index(&self, _: RangeFull) -> &Self::Output { &self.bytes[..self.len() as usize] }
}
impl IndexMut<RangeFull> for Number {
fn index_mut(&mut self, _: RangeFull) -> &mut Self::Output {
let len = self.len() as usize;
&mut self.bytes[..len]
}
}
impl Index<Range<u16>> for Number {
type Output = [u8];
fn index(&self, index: Range<u16>) -> &Self::Output {
assert!(index.start < self.len() && index.end <= self.len());
&self.bytes[index.start as usize..index.end as usize]
}
}
impl IndexMut<Range<u16>> for Number {
fn index_mut(&mut self, index: Range<u16>) -> &mut Self::Output {
assert!(index.start < self.len() && index.end <= self.len());
&mut self.bytes[index.start as usize..index.end as usize]
}
}
impl Index<RangeInclusive<u16>> for Number {
type Output = [u8];
fn index(&self, index: RangeInclusive<u16>) -> &Self::Output {
assert!(*index.start() < self.len() && *index.end() < self.len());
&self.bytes[*index.start() as usize..*index.end() as usize]
}
}
impl IndexMut<RangeInclusive<u16>> for Number {
fn index_mut(&mut self, index: RangeInclusive<u16>) -> &mut Self::Output {
&mut self.bytes[*index.start() as usize..*index.end() as usize]
}
}
impl Index<RangeFrom<u16>> for Number {
type Output = [u8];
fn index(&self, index: RangeFrom<u16>) -> &Self::Output {
assert!(index.start < self.len());
&self.bytes[index.start as usize..self.len() as usize]
}
}
impl IndexMut<RangeFrom<u16>> for Number {
fn index_mut(&mut self, index: RangeFrom<u16>) -> &mut Self::Output {
assert!(index.start < self.len());
let len = self.len() as usize;
&mut self.bytes[index.start as usize..len]
}
}
impl Index<RangeTo<u16>> for Number {
type Output = [u8];
fn index(&self, index: RangeTo<u16>) -> &Self::Output {
assert!(index.end <= self.len());
&self.bytes[..index.end as usize]
}
}
impl IndexMut<RangeTo<u16>> for Number {
fn index_mut(&mut self, index: RangeTo<u16>) -> &mut Self::Output {
assert!(index.end <= self.len());
&mut self.bytes[..index.end as usize]
}
}
impl Index<RangeToInclusive<u16>> for Number {
type Output = [u8];
fn index(&self, index: RangeToInclusive<u16>) -> &Self::Output {
assert!(index.end < self.len());
&self.bytes[..=index.end as usize]
}
}
impl IndexMut<RangeToInclusive<u16>> for Number {
fn index_mut(&mut self, index: RangeToInclusive<u16>) -> &mut Self::Output {
assert!(index.end < self.len());
&mut self.bytes[..=index.end as usize]
}
}
impl Number {
/// Creates zero value with a given layout
#[inline]
pub fn zero(layout: Layout) -> Number { Number { layout, bytes: [0u8; 1024] } }
/// Creates value with the specified bit masked
#[inline]
pub fn masked_bit(bit_no: u16, layout: Layout) -> Number {
let mut zero = Number { layout, bytes: [0u8; 1024] };
zero.bytes[(bit_no / 8) as usize] = 1 << (bit_no % 8);
zero
}
/// Constructs number representation from a slice and a given layout.
///
/// Fails returning `None` if the length of slice does not match the required layout byte
/// length.
pub fn with(slice: impl AsRef<[u8]>, layout: impl Into<Layout>) -> Option<Number> {
let layout = layout.into();
let slice = slice.as_ref();
if slice.len() != layout.bytes() as usize {
return None;
}
let mut me = Number::from_slice(slice);
me.layout = layout;
Some(me)
}
/// Constructs value from slice of bytes.
///
/// Panics if the length of the slice is greater than 1024 bytes.
pub fn from_slice(slice: impl AsRef<[u8]>) -> Number {
let len = slice.as_ref().len();
let mut bytes = [0u8; 1024];
bytes[0..len].copy_from_slice(slice.as_ref());
Number { layout: Layout::unsigned(len as u16), bytes }
}
/// Constructs value from hex string
#[cfg(feature = "std")]
pub fn from_hex(s: &str) -> Result<Number, amplify::hex::Error> {
use amplify::hex::FromHex;
let s = s.trim_start_matches("0x");
let len = s.len() / 2;
if len > 1024 {
return Err(amplify::hex::Error::InvalidLength(1024, len));
}
let mut bytes = [0u8; 1024];
let hex = Vec::<u8>::from_hex(s)?;
bytes[0..len].copy_from_slice(&hex);
Ok(Number { layout: Layout::unsigned(hex.len() as u16), bytes })
}
/// Serializes value in hexadecimal format to a string
#[cfg(feature = "std")]
pub fn to_hex(self) -> String {
let mut ret = String::with_capacity(2usize * self.len() as usize + 2);
write!(ret, "0x").expect("writing to string");
for ch in &self.bytes {
write!(ret, "{:02x}", ch).expect("writing to string");
}
ret
}
/// Returns length of the used portion of the value
#[inline]
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> u16 { self.layout.bytes() }
/// Returns number layout used by the value
#[inline]
pub fn layout(&self) -> Layout { self.layout }
/// Returns the number of zeros in the binary representation of `self`.
#[inline]
pub fn count_zeros(&self) -> u16 { self.len() - self.count_ones() }
/// Returns the number of ones in the binary representation of `self`.
pub fn count_ones(&self) -> u16 {
let mut count = 0u16;
for byte in &self[..] {
count += byte.count_ones() as u16;
}
count
}
/// Measures minimum number of bits required to store the number. For float layouts, always
/// matches the layout bit size.
pub fn min_bit_len(&self) -> u16 {
if self.layout.is_float() {
return self.layout.bits() as u16;
}
if self.len() == 0 {
return 0;
}
let mut data = self[..].to_vec();
let sig_len = if self.layout.is_signed() {
data[self.layout.sign_byte() as usize] &= 0x7F;
1
} else {
0
};
let mut index = self.len() as usize - 1;
while data[index].count_ones() == 0 && index > 0 {
index -= 1;
}
index as u16 * 8 + 8 - data[index].leading_zeros() as u16 + sig_len
}
/// Detects if the number value positive (i.e. `>0`) or not.
pub fn is_positive(self) -> bool {
if self.layout.is_unsigned_int() {
return true;
}
self[self.layout.sign_byte()] & 0x80 > 0
}
/// Detects if the value is equal to zero
pub fn is_zero(self) -> bool {
let mut clean = self.to_clean();
if self.layout.is_float() {
clean = clean.without_sign();
}
clean.to_u1024_bytes() == u1024::from(0u8)
}
/// Detects if the value is `NaN`. For integer layouts always false
pub fn is_nan(self) -> bool {
match self.layout {
Layout::Integer(_) => false,
Layout::Float(FloatLayout::BFloat16) => bf16::from(self).is_nan(),
Layout::Float(FloatLayout::IeeeHalf) => ieee::Half::from(self).is_nan(),
Layout::Float(FloatLayout::IeeeSingle) => ieee::Single::from(self).is_nan(),
Layout::Float(FloatLayout::IeeeDouble) => ieee::Double::from(self).is_nan(),
Layout::Float(FloatLayout::IeeeQuad) => ieee::Quad::from(self).is_nan(),
Layout::Float(FloatLayout::IeeeOct) => todo!("(#4) 512-bit float NaN detection"),
Layout::Float(FloatLayout::X87DoubleExt) => {
ieee::X87DoubleExtended::from(self).is_nan()
}
Layout::Float(FloatLayout::FloatTapered) => todo!("(#5) tapered float NaN detection"),
}
}
/// Detects if the value is equal to the maximum possible value for the used layout. For floats,
/// always `false`.
pub fn is_max(self) -> bool {
match self.layout {
Layout::Integer(int_layout) => {
let mut mask = u1024::from(0u8);
for _ in 0..int_layout.bytes - int_layout.is_signed() as u16 {
mask <<= 1;
mask |= 1u8;
}
self.to_clean() == mask.into()
}
_ => false,
}
}
/// Ensures that all non-value bits are set to zero
#[inline]
pub fn clean(&mut self) {
let len = self.len() as usize;
self.bytes[len..].fill(0);
}
/// Returns a copy where all non-value bits are set to zero
#[inline]
pub fn to_clean(mut self) -> Self {
self.clean();
self
}
/// Transforms internal value layout returning whether this was possible without discarding any
/// bit information
pub fn reshape(&mut self, to: Layout) -> bool {
match (self.layout, to) {
(from, to) if from == to => false,
// We need to change only bit dimensions
(
Layout::Integer(IntLayout { signed: false, .. }),
Layout::Integer(IntLayout { signed: false, bytes: len2 }),
) => {
let bit_len = self.min_bit_len();
self.layout = to;
self.clean();
bit_len <= len2 * 8
}
(Layout::Float(l1), Layout::Float(l2)) => {
let value = match l1 {
FloatLayout::BFloat16 => bf16::from(*self).to_string(),
FloatLayout::IeeeHalf => ieee::Half::from(*self).to_string(),
FloatLayout::IeeeSingle => ieee::Single::from(*self).to_string(),
FloatLayout::IeeeDouble => ieee::Double::from(*self).to_string(),
FloatLayout::X87DoubleExt => ieee::X87DoubleExtended::from(*self).to_string(),
FloatLayout::IeeeQuad => ieee::Quad::from(*self).to_string(),
FloatLayout::IeeeOct => {
unimplemented!("IEEE octal precision layout conversion")
}
FloatLayout::FloatTapered => unimplemented!("tapered float layout conversion"),
};
*self = match l2 {
FloatLayout::BFloat16 => {
bf16::from_str(&value).map(Number::from).expect("float layout conversion")
}
FloatLayout::IeeeHalf => ieee::Half::from_str(&value)
.map(Number::from)
.expect("float layout conversion"),
FloatLayout::IeeeSingle => ieee::Single::from_str(&value)
.map(Number::from)
.expect("float layout conversion"),
FloatLayout::IeeeDouble => ieee::Double::from_str(&value)
.map(Number::from)
.expect("float layout conversion"),
FloatLayout::X87DoubleExt => ieee::X87DoubleExtended::from_str(&value)
.map(Number::from)
.expect("float layout conversion"),
FloatLayout::IeeeQuad => ieee::Quad::from_str(&value)
.map(Number::from)
.expect("float layout conversion"),
FloatLayout::IeeeOct => {
unimplemented!("IEEE octal precision layout conversion")
}
FloatLayout::FloatTapered => unimplemented!("tapered float layout conversion"),
};
false
}
(Layout::Float(fl), Layout::Integer(_)) => {
let val = match fl {
FloatLayout::BFloat16 => todo!("BFloat16 to integer conversion"),
FloatLayout::IeeeHalf => ieee::Half::from(*self).to_i128(128),
FloatLayout::IeeeSingle => ieee::Single::from(*self).to_i128(128),
FloatLayout::IeeeDouble => ieee::Double::from(*self).to_i128(128),
FloatLayout::X87DoubleExt => ieee::X87DoubleExtended::from(*self).to_i128(128),
FloatLayout::IeeeQuad => ieee::Quad::from(*self).to_i128(128),
FloatLayout::IeeeOct => {
unimplemented!("IEEE octal precision layout conversion")
}
FloatLayout::FloatTapered => unimplemented!("tapered float layout conversion"),
};
*self = Number::from(val.value);
self.reshape(to);
val.status == Status::OK
}
(from, to) => todo!("Number layout reshape from {} to {}", from, to),
}
}
/// Adds or removes negative sign to the number (negates negative or positive number, depending
/// on the method argument value)
#[inline]
pub fn applying_sign(mut self, sign: impl Into<bool>) -> Number {
let sign_byte = self.layout.sign_byte();
if sign.into() {
self[sign_byte] |= 0x80;
} else {
self[sign_byte] &= 0x7F;
}
self
}
/// Removes negative sign if present (negates negative number)
#[inline]
pub fn without_sign(self) -> Number { self.applying_sign(false) }
#[doc(hidden)]
/// Converts the value into `u1024` integer with the bytes corresponding to the internal
/// representation.
#[inline]
pub(super) fn to_u1024_bytes(self) -> u1024 { self.to_clean().into() }
}
/// Errors parsing literal values in AluVM assembly code
#[derive(Clone, Eq, PartialEq, Debug, Display, From)]
#[cfg_attr(feature = "std", derive(Error))]
#[display(inner)]
#[non_exhaustive]
pub enum LiteralParseError {
/// Error parsing decimal literal
#[from]
Int(core::num::ParseIntError),
/// Error parsing float value
#[from]
#[display(Debug)]
Float(rustc_apfloat::ParseError),
/// Unknown literal
#[display("unknown token `{0}` while parsing AluVM assembly literal")]
UnknownLiteral(String),
}
impl FromStr for Number {
type Err = LiteralParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(if let Some(s) = s.strip_prefix("0x") {
u128::from_str_radix(s, 16)?.into()
} else if let Some(s) = s.strip_prefix("0o") {
u128::from_str_radix(s, 8)?.into()
} else if let Some(s) = s.strip_prefix("0b") {
u128::from_str_radix(s, 2)?.into()
} else if s.contains(&['E', 'e'][..]) {
ieee::Double::from_str(s)?.into()
} else if s.starts_with('-') {
i128::from_str(s)?.into()
} else {
u128::from_str(s)?.into()
})
}
}
impl Debug for Number {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let len = self.layout.bytes() as usize;
f.debug_struct("Number")
.field("layout", &self.layout)
.field("bytes", {
#[cfg(feature = "std")]
{
use amplify::hex::ToHex;
&self.bytes[..len].to_hex()
}
#[cfg(not(feature = "std"))]
{
&format!("{:#04X?}", &self.bytes[0..len])
}
})
.finish()
}
}
impl Display for Number {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self.layout {
Layout::Integer(IntLayout { signed: false, .. }) if self.min_bit_len() <= 12 => {
write!(f, "{}", u16::from(self))
}
Layout::Integer(IntLayout { signed: false, .. }) if self.min_bit_len() < 16 * 8 => {
write!(f, "0x{:X}", self)
}
Layout::Integer(IntLayout { signed: true, bytes }) if bytes <= 16 => {
Display::fmt(&i128::from(self), f)
}
Layout::Integer(IntLayout { signed: false, bytes }) if bytes <= 16 => {
Display::fmt(&u128::from(self), f)
}
Layout::Integer(IntLayout { signed: false, bytes }) if bytes <= 32 => {
Display::fmt(&u256::from(self), f)
}
Layout::Integer(IntLayout { signed: false, .. }) if self.min_bit_len() < 512 => {
Display::fmt(&u512::from(self), f)
}
Layout::Integer(IntLayout { .. }) => Display::fmt(&u1024::from(self), f),
Layout::Float(FloatLayout::BFloat16) => Display::fmt(&half::bf16::from(self), f),
Layout::Float(FloatLayout::IeeeHalf) => Display::fmt(&ieee::Half::from(self), f),
Layout::Float(FloatLayout::IeeeSingle) => Display::fmt(&ieee::Single::from(self), f),
Layout::Float(FloatLayout::IeeeDouble) => Display::fmt(&ieee::Double::from(self), f),
Layout::Float(FloatLayout::IeeeQuad) => Display::fmt(&ieee::Quad::from(self), f),
Layout::Float(FloatLayout::X87DoubleExt) => {
Display::fmt(&ieee::X87DoubleExtended::from(self), f)
}
_ => {
// TODO(#16) Implement Display for the rest of float layouts
f.write_str("<not supported float layout for display>")
}
}
}
}
impl LowerHex for Number {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
#[cfg(feature = "std")]
use amplify::hex::ToHex;
match self.layout {
Layout::Integer(IntLayout { signed: true, bytes }) if bytes <= 16 => {
LowerHex::fmt(&i128::from(self), f)
}
Layout::Integer(IntLayout { signed: false, bytes }) if bytes <= 16 => {
LowerHex::fmt(&u128::from(self), f)
}
// TODO(#16) Use LowerHex implementation once it will be done in amplify::num
Layout::Integer(IntLayout { signed: false, bytes }) if bytes < 32 => {
#[cfg(feature = "std")]
{
f.write_str(u256::from(self).to_be_bytes().to_hex().trim_start_matches('0'))
}
#[cfg(not(feature = "std"))]
{
f.write_str("<hex display requires std library>")
}
}
Layout::Integer(IntLayout { signed: false, bytes }) if bytes < 32 => {
#[cfg(feature = "std")]
{
f.write_str(u512::from(self).to_be_bytes().to_hex().trim_start_matches('0'))
}
#[cfg(not(feature = "std"))]
{
f.write_str("<hex display requires std library>")
}
}
Layout::Integer(IntLayout { .. }) => {
#[cfg(feature = "std")]
{
f.write_str(u1024::from(self).to_be_bytes().to_hex().trim_start_matches('0'))
}
#[cfg(not(feature = "std"))]
{
f.write_str("<hex display requires std library>")
}
}
// TODO(#16) Use LowerHex implementation once it will be done in `half` crate
/* TODO(#16) Use LowerHex implementation once it will be done in `rustc_apfloat`
Layout::Float(FloatLayout::BFloat16) => LowerHex::fmt(&half::bf16::from(self), f),
Layout::Float(FloatLayout::IeeeHalf) => LowerHex::fmt(&ieee::Half::from(self), f),
Layout::Float(FloatLayout::IeeeSingle) => LowerHex::fmt(&ieee::Single::from(self), f),
Layout::Float(FloatLayout::IeeeDouble) => LowerHex::fmt(&ieee::Double::from(self), f),
Layout::Float(FloatLayout::IeeeQuad) => LowerHex::fmt(&ieee::Quad::from(self), f),
Layout::Float(FloatLayout::X87DoubleExt) => {
LowerHex::fmt(&ieee::X87DoubleExtended::from(self), f)
}
*/
_ => {
// TODO(#16) Implement Display for the rest of float layouts
f.write_str("<not supported float layout for display>")
}
}
}
}
impl UpperHex for Number {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let s = if f.alternate() { format!("{:#x}", self) } else { format!("{:x}", self) };
f.write_str(&s.to_uppercase())
}
}
impl Octal for Number {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self.layout {
Layout::Integer(IntLayout { signed: true, bytes }) if bytes <= 16 => {