-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathInt128.cs
2229 lines (1890 loc) · 91.6 KB
/
Int128.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers.Binary;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
/// <summary>Represents a 128-bit signed integer.</summary>
[Intrinsic]
[StructLayout(LayoutKind.Sequential)]
public readonly struct Int128
: IBinaryInteger<Int128>,
IMinMaxValue<Int128>,
ISignedNumber<Int128>,
IUtf8SpanFormattable,
IBinaryIntegerParseAndFormatInfo<Int128>
{
internal const int Size = 16;
#if BIGENDIAN
private readonly ulong _upper;
private readonly ulong _lower;
#else
private readonly ulong _lower;
private readonly ulong _upper;
#endif
/// <summary>Initializes a new instance of the <see cref="Int128" /> struct.</summary>
/// <param name="upper">The upper 64-bits of the 128-bit value.</param>
/// <param name="lower">The lower 64-bits of the 128-bit value.</param>
[CLSCompliant(false)]
public Int128(ulong upper, ulong lower)
{
_lower = lower;
_upper = upper;
}
internal ulong Lower => _lower;
internal ulong Upper => _upper;
/// <inheritdoc cref="IComparable.CompareTo(object)" />
public int CompareTo(object? value)
{
if (value is Int128 other)
{
return CompareTo(other);
}
else if (value is null)
{
return 1;
}
else
{
throw new ArgumentException(SR.Arg_MustBeInt128);
}
}
/// <inheritdoc cref="IComparable{T}.CompareTo(T)" />
public int CompareTo(Int128 value)
{
if (this < value)
{
return -1;
}
else if (this > value)
{
return 1;
}
else
{
return 0;
}
}
/// <inheritdoc cref="object.Equals(object?)" />
public override bool Equals([NotNullWhen(true)] object? obj)
{
return (obj is Int128 other) && Equals(other);
}
/// <inheritdoc cref="IEquatable{T}.Equals(T)" />
public bool Equals(Int128 other)
{
return this == other;
}
/// <inheritdoc cref="object.GetHashCode()" />
public override int GetHashCode() => HashCode.Combine(_lower, _upper);
/// <inheritdoc cref="object.ToString()" />
public override string ToString()
{
return Number.Int128ToDecStr(this);
}
public string ToString(IFormatProvider? provider)
{
return Number.FormatInt128(this, null, provider);
}
public string ToString([StringSyntax(StringSyntaxAttribute.NumericFormat)] string? format)
{
return Number.FormatInt128(this, format, null);
}
public string ToString([StringSyntax(StringSyntaxAttribute.NumericFormat)] string? format, IFormatProvider? provider)
{
return Number.FormatInt128(this, format, provider);
}
public bool TryFormat(Span<char> destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
{
return Number.TryFormatInt128(this, format, provider, destination, out charsWritten);
}
/// <inheritdoc cref="IUtf8SpanFormattable.TryFormat" />
public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
{
return Number.TryFormatInt128(this, format, provider, utf8Destination, out bytesWritten);
}
public static Int128 Parse(string s) => Parse(s, NumberStyles.Integer, provider: null);
public static Int128 Parse(string s, NumberStyles style) => Parse(s, style, provider: null);
public static Int128 Parse(string s, IFormatProvider? provider) => Parse(s, NumberStyles.Integer, provider);
public static Int128 Parse(string s, NumberStyles style, IFormatProvider? provider)
{
if (s is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); }
return Parse(s.AsSpan(), style, provider);
}
public static Int128 Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseBinaryInteger<char, Int128>(s, style, NumberFormatInfo.GetInstance(provider));
}
public static bool TryParse([NotNullWhen(true)] string? s, out Int128 result) => TryParse(s, NumberStyles.Integer, provider: null, out result);
public static bool TryParse(ReadOnlySpan<char> s, out Int128 result) => TryParse(s, NumberStyles.Integer, provider: null, out result);
/// <summary>Tries to convert a UTF-8 character span containing the string representation of a number to its 128-bit signed integer equivalent.</summary>
/// <param name="utf8Text">A span containing the UTF-8 characters representing the number to convert.</param>
/// <param name="result">When this method returns, contains the 128-bit signed integer value equivalent to the number contained in <paramref name="utf8Text" /> if the conversion succeeded, or zero if the conversion failed. This parameter is passed uninitialized; any value originally supplied in result will be overwritten.</param>
/// <returns><c>true</c> if <paramref name="utf8Text" /> was converted successfully; otherwise, false.</returns>
public static bool TryParse(ReadOnlySpan<byte> utf8Text, out Int128 result) => TryParse(utf8Text, NumberStyles.Integer, provider: null, out result);
public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out Int128 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s is null)
{
result = 0;
return false;
}
return Number.TryParseBinaryInteger(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out Int128 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseBinaryInteger(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
//
// Explicit Conversions From Int128
//
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="byte" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="byte" />.</returns>
public static explicit operator byte(Int128 value) => (byte)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="byte" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="byte" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
public static explicit operator checked byte(Int128 value)
{
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((byte)value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="char" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="char" />.</returns>
public static explicit operator char(Int128 value) => (char)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="char" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="char" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
public static explicit operator checked char(Int128 value)
{
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((char)value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="decimal" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="decimal" />.</returns>
public static explicit operator decimal(Int128 value)
{
if (IsNegative(value))
{
value = -value;
return -(decimal)(UInt128)(value);
}
return (decimal)(UInt128)(value);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="double" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="double" />.</returns>
public static explicit operator double(Int128 value)
{
if (IsNegative(value))
{
value = -value;
return -(double)(UInt128)(value);
}
return (double)(UInt128)(value);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="Half" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="Half" />.</returns>
public static explicit operator Half(Int128 value)
{
if (IsNegative(value))
{
value = -value;
return -(Half)(UInt128)(value);
}
return (Half)(UInt128)(value);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="short" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="short" />.</returns>
public static explicit operator short(Int128 value) => (short)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="short" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="short" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
public static explicit operator checked short(Int128 value)
{
if (~value._upper == 0)
{
long lower = (long)value._lower;
return checked((short)lower);
}
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((short)value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="int" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="int" />.</returns>
public static explicit operator int(Int128 value) => (int)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="int" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="int" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
public static explicit operator checked int(Int128 value)
{
if (~value._upper == 0)
{
long lower = (long)value._lower;
return checked((int)lower);
}
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((int)value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="long" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="long" />.</returns>
public static explicit operator long(Int128 value) => (long)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="long" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="long" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
public static explicit operator checked long(Int128 value)
{
if (~value._upper == 0)
{
long lower = (long)value._lower;
return lower;
}
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((long)value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="IntPtr" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="IntPtr" />.</returns>
public static explicit operator nint(Int128 value) => (nint)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="IntPtr" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="IntPtr" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
public static explicit operator checked nint(Int128 value)
{
if (~value._upper == 0)
{
long lower = (long)value._lower;
return checked((nint)lower);
}
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((nint)value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="sbyte" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="sbyte" />.</returns>
[CLSCompliant(false)]
public static explicit operator sbyte(Int128 value) => (sbyte)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="sbyte" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="sbyte" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked sbyte(Int128 value)
{
if (~value._upper == 0)
{
long lower = (long)value._lower;
return checked((sbyte)lower);
}
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((sbyte)value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="float" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="float" />.</returns>
public static explicit operator float(Int128 value)
{
if (IsNegative(value))
{
value = -value;
return -(float)(UInt128)(value);
}
return (float)(UInt128)(value);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="ushort" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="ushort" />.</returns>
[CLSCompliant(false)]
public static explicit operator ushort(Int128 value) => (ushort)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="ushort" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="ushort" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked ushort(Int128 value)
{
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((ushort)value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="uint" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="uint" />.</returns>
[CLSCompliant(false)]
public static explicit operator uint(Int128 value) => (uint)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="uint" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="uint" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked uint(Int128 value)
{
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((uint)value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="ulong" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="ulong" />.</returns>
[CLSCompliant(false)]
public static explicit operator ulong(Int128 value) => value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="ulong" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="ulong" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked ulong(Int128 value)
{
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return value._lower;
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="UInt128" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="UInt128" />.</returns>
[CLSCompliant(false)]
public static explicit operator UInt128(Int128 value) => new UInt128(value._upper, value._lower);
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="UInt128" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="UInt128" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked UInt128(Int128 value)
{
if ((long)value._upper < 0)
{
ThrowHelper.ThrowOverflowException();
}
return new UInt128(value._upper, value._lower);
}
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="UIntPtr" /> value.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="UIntPtr" />.</returns>
[CLSCompliant(false)]
public static explicit operator nuint(Int128 value) => (nuint)value._lower;
/// <summary>Explicitly converts a 128-bit signed integer to a <see cref="UIntPtr" /> value, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a <see cref="UIntPtr" />.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
[CLSCompliant(false)]
public static explicit operator checked nuint(Int128 value)
{
if (value._upper != 0)
{
ThrowHelper.ThrowOverflowException();
}
return checked((nuint)value._lower);
}
//
// Explicit Conversions To Int128
//
/// <summary>Explicitly converts a <see cref="decimal" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static explicit operator Int128(decimal value)
{
value = decimal.Truncate(value);
Int128 result = new Int128(value.High, value.Low64);
if (decimal.IsNegative(value))
{
result = -result;
}
return result;
}
/// <summary>Explicitly converts a <see cref="double" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static explicit operator Int128(double value)
{
const double TwoPow127 = 170141183460469231731687303715884105728.0;
if (value <= -TwoPow127)
{
return MinValue;
}
else if (double.IsNaN(value))
{
return 0;
}
else if (value >= +TwoPow127)
{
return MaxValue;
}
return ToInt128(value);
}
/// <summary>Explicitly converts a <see cref="double" /> value to a 128-bit signed integer, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
public static explicit operator checked Int128(double value)
{
const double TwoPow127 = 170141183460469231731687303715884105728.0;
if ((value < -TwoPow127) || double.IsNaN(value) || (value >= +TwoPow127))
{
ThrowHelper.ThrowOverflowException();
}
return ToInt128(value);
}
internal static Int128 ToInt128(double value)
{
const double TwoPow127 = 170141183460469231731687303715884105728.0;
Debug.Assert(value >= -TwoPow127);
Debug.Assert(double.IsFinite(value));
Debug.Assert(value < TwoPow127);
// This code is based on `f64_to_i128` from m-ou-se/floatconv
// Copyright (c) 2020 Mara Bos <m-ou.se@m-ou.se>. All rights reserved.
//
// Licensed under the BSD 2 - Clause "Simplified" License
// See THIRD-PARTY-NOTICES.TXT for the full license text
bool isNegative = double.IsNegative(value);
if (isNegative)
{
value = -value;
}
if (value >= 1.0)
{
// In order to convert from double to int128 we first need to extract the signficand,
// including the implicit leading bit, as a full 128-bit significand. We can then adjust
// this down to the represented integer by right shifting by the unbiased exponent, taking
// into account the significand is now represented as 128-bits.
ulong bits = BitConverter.DoubleToUInt64Bits(value);
Int128 result = new Int128((bits << 12) >> 1 | 0x8000_0000_0000_0000, 0x0000_0000_0000_0000);
result >>>= (1023 + 128 - 1 - (int)(bits >> 52));
if (isNegative)
{
result = -result;
}
return result;
}
else
{
return 0;
}
}
/// <summary>Explicitly converts a <see cref="float" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static explicit operator Int128(float value) => (Int128)(double)(value);
/// <summary>Explicitly converts a <see cref="float" /> value to a 128-bit signed integer, throwing an overflow exception for any values that fall outside the representable range.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
/// <exception cref="OverflowException"><paramref name="value" /> is not representable by <see cref="Int128" />.</exception>
public static explicit operator checked Int128(float value) => checked((Int128)(double)(value));
//
// Implicit Conversions To Int128
//
/// <summary>Implicitly converts a <see cref="byte" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static implicit operator Int128(byte value) => new Int128(0, value);
/// <summary>Implicitly converts a <see cref="char" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static implicit operator Int128(char value) => new Int128(0, value);
/// <summary>Implicitly converts a <see cref="short" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static implicit operator Int128(short value)
{
long lower = value;
return new Int128((ulong)(lower >> 63), (ulong)lower);
}
/// <summary>Implicitly converts a <see cref="int" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static implicit operator Int128(int value)
{
long lower = value;
return new Int128((ulong)(lower >> 63), (ulong)lower);
}
/// <summary>Implicitly converts a <see cref="long" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static implicit operator Int128(long value)
{
long lower = value;
return new Int128((ulong)(lower >> 63), (ulong)lower);
}
/// <summary>Implicitly converts a <see cref="IntPtr" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
public static implicit operator Int128(nint value)
{
long lower = value;
return new Int128((ulong)(lower >> 63), (ulong)lower);
}
/// <summary>Implicitly converts a <see cref="sbyte" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
[CLSCompliant(false)]
public static implicit operator Int128(sbyte value)
{
long lower = value;
return new Int128((ulong)(lower >> 63), (ulong)lower);
}
/// <summary>Implicitly converts a <see cref="ushort" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
[CLSCompliant(false)]
public static implicit operator Int128(ushort value) => new Int128(0, value);
/// <summary>Implicitly converts a <see cref="uint" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
[CLSCompliant(false)]
public static implicit operator Int128(uint value) => new Int128(0, value);
/// <summary>Implicitly converts a <see cref="ulong" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
[CLSCompliant(false)]
public static implicit operator Int128(ulong value) => new Int128(0, value);
/// <summary>Implicitly converts a <see cref="UIntPtr" /> value to a 128-bit signed integer.</summary>
/// <param name="value">The value to convert.</param>
/// <returns><paramref name="value" /> converted to a 128-bit signed integer.</returns>
[CLSCompliant(false)]
public static implicit operator Int128(nuint value) => new Int128(0, value);
//
// IAdditionOperators
//
/// <inheritdoc cref="IAdditionOperators{TSelf, TOther, TResult}.op_Addition(TSelf, TOther)" />
public static Int128 operator +(Int128 left, Int128 right)
{
// For unsigned addition, we can detect overflow by checking `(x + y) < x`
// This gives us the carry to add to upper to compute the correct result
ulong lower = left._lower + right._lower;
ulong carry = (lower < left._lower) ? 1UL : 0UL;
ulong upper = left._upper + right._upper + carry;
return new Int128(upper, lower);
}
/// <inheritdoc cref="IAdditionOperators{TSelf, TOther, TResult}.op_Addition(TSelf, TOther)" />
public static Int128 operator checked +(Int128 left, Int128 right)
{
// For signed addition, we can detect overflow by checking if the sign of
// both inputs are the same and then if that differs from the sign of the
// output.
Int128 result = left + right;
uint sign = (uint)(left._upper >> 63);
if (sign == (uint)(right._upper >> 63))
{
if (sign != (uint)(result._upper >> 63))
{
ThrowHelper.ThrowOverflowException();
}
}
return result;
}
//
// IAdditiveIdentity
//
/// <inheritdoc cref="IAdditiveIdentity{TSelf, TResult}.AdditiveIdentity" />
static Int128 IAdditiveIdentity<Int128, Int128>.AdditiveIdentity => default;
//
// IBinaryInteger
//
/// <inheritdoc cref="IBinaryInteger{TSelf}.DivRem(TSelf, TSelf)" />
public static (Int128 Quotient, Int128 Remainder) DivRem(Int128 left, Int128 right)
{
Int128 quotient = left / right;
return (quotient, left - (quotient * right));
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.LeadingZeroCount(TSelf)" />
public static Int128 LeadingZeroCount(Int128 value)
=> LeadingZeroCountAsInt32(value);
/// <summary>Computes the number of leading zero bits in this value.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LeadingZeroCountAsInt32(Int128 value)
{
if (value._upper == 0)
{
return 64 + BitOperations.LeadingZeroCount(value._lower);
}
return BitOperations.LeadingZeroCount(value._upper);
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.PopCount(TSelf)" />
public static Int128 PopCount(Int128 value)
=> ulong.PopCount(value._lower) + ulong.PopCount(value._upper);
/// <inheritdoc cref="IBinaryInteger{TSelf}.RotateLeft(TSelf, int)" />
public static Int128 RotateLeft(Int128 value, int rotateAmount)
=> (value << rotateAmount) | (value >>> (128 - rotateAmount));
/// <inheritdoc cref="IBinaryInteger{TSelf}.RotateRight(TSelf, int)" />
public static Int128 RotateRight(Int128 value, int rotateAmount)
=> (value >>> rotateAmount) | (value << (128 - rotateAmount));
/// <inheritdoc cref="IBinaryInteger{TSelf}.TrailingZeroCount(TSelf)" />
public static Int128 TrailingZeroCount(Int128 value)
{
if (value._lower == 0)
{
return 64 + ulong.TrailingZeroCount(value._upper);
}
return ulong.TrailingZeroCount(value._lower);
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.TryReadBigEndian(ReadOnlySpan{byte}, bool, out TSelf)" />
static bool IBinaryInteger<Int128>.TryReadBigEndian(ReadOnlySpan<byte> source, bool isUnsigned, out Int128 value)
{
Int128 result = default;
if (source.Length != 0)
{
// Propagate the most significant bit so we have `0` or `-1`
sbyte sign = (sbyte)(source[0]);
sign >>= 31;
Debug.Assert((sign == 0) || (sign == -1));
// We need to also track if the input data is unsigned
isUnsigned |= (sign == 0);
if (isUnsigned && sbyte.IsNegative(sign) && (source.Length >= Size))
{
// When we are unsigned and the most significant bit is set, we are a large positive
// and therefore definitely out of range
value = result;
return false;
}
if (source.Length > Size)
{
if (source[..^Size].ContainsAnyExcept((byte)sign))
{
// When we are unsigned and have any non-zero leading data or signed with any non-set leading
// data, we are a large positive/negative, respectively, and therefore definitely out of range
value = result;
return false;
}
if (isUnsigned == sbyte.IsNegative((sbyte)source[^Size]))
{
// When the most significant bit of the value being set/clear matches whether we are unsigned
// or signed then we are a large positive/negative and therefore definitely out of range
value = result;
return false;
}
}
ref byte sourceRef = ref MemoryMarshal.GetReference(source);
if (source.Length >= Size)
{
sourceRef = ref Unsafe.Add(ref sourceRef, source.Length - Size);
// We have at least 16 bytes, so just read the ones we need directly
result = Unsafe.ReadUnaligned<Int128>(ref sourceRef);
if (BitConverter.IsLittleEndian)
{
result = BinaryPrimitives.ReverseEndianness(result);
}
}
else
{
// We have between 1 and 15 bytes, so construct the relevant value directly
// since the data is in Big Endian format, we can just read the bytes and
// shift left by 8-bits for each subsequent part
for (int i = 0; i < source.Length; i++)
{
result <<= 8;
result |= Unsafe.Add(ref sourceRef, i);
}
if (!isUnsigned)
{
result |= ((One << ((Size * 8) - 1)) >> (((Size - source.Length) * 8) - 1));
}
}
}
value = result;
return true;
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.TryReadLittleEndian(ReadOnlySpan{byte}, bool, out TSelf)" />
static bool IBinaryInteger<Int128>.TryReadLittleEndian(ReadOnlySpan<byte> source, bool isUnsigned, out Int128 value)
{
Int128 result = default;
if (source.Length != 0)
{
// Propagate the most significant bit so we have `0` or `-1`
sbyte sign = (sbyte)(source[^1]);
sign >>= 31;
Debug.Assert((sign == 0) || (sign == -1));
// We need to also track if the input data is unsigned
isUnsigned |= (sign == 0);
if (isUnsigned && sbyte.IsNegative(sign) && (source.Length >= Size))
{
// When we are unsigned and the most significant bit is set, we are a large positive
// and therefore definitely out of range
value = result;
return false;
}
if (source.Length > Size)
{
if (source[Size..].ContainsAnyExcept((byte)sign))
{
// When we are unsigned and have any non-zero leading data or signed with any non-set leading
// data, we are a large positive/negative, respectively, and therefore definitely out of range
value = result;
return false;
}
if (isUnsigned == sbyte.IsNegative((sbyte)source[Size - 1]))
{
// When the most significant bit of the value being set/clear matches whether we are unsigned
// or signed then we are a large positive/negative and therefore definitely out of range
value = result;
return false;
}
}
ref byte sourceRef = ref MemoryMarshal.GetReference(source);
if (source.Length >= Size)
{
// We have at least 16 bytes, so just read the ones we need directly
result = Unsafe.ReadUnaligned<Int128>(ref sourceRef);
if (!BitConverter.IsLittleEndian)
{
result = BinaryPrimitives.ReverseEndianness(result);
}
}
else
{
// We have between 1 and 15 bytes, so construct the relevant value directly
// since the data is in Little Endian format, we can just read the bytes and
// shift left by 8-bits for each subsequent part, then reverse endianness to
// ensure the order is correct. This is more efficient than iterating in reverse
// due to current JIT limitations
for (int i = 0; i < source.Length; i++)
{
result <<= 8;
result |= Unsafe.Add(ref sourceRef, i);
}
result <<= ((Size - source.Length) * 8);
result = BinaryPrimitives.ReverseEndianness(result);
if (!isUnsigned)
{
result |= ((One << ((Size * 8) - 1)) >> (((Size - source.Length) * 8) - 1));
}
}
}
value = result;
return true;
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.GetShortestBitLength()" />
int IBinaryInteger<Int128>.GetShortestBitLength()
{
Int128 value = this;
if (IsPositive(value))
{
return (Size * 8) - LeadingZeroCountAsInt32(value);
}
else
{
return (Size * 8) + 1 - LeadingZeroCountAsInt32(~value);
}
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.GetByteCount()" />
int IBinaryInteger<Int128>.GetByteCount() => Size;
/// <inheritdoc cref="IBinaryInteger{TSelf}.TryWriteBigEndian(Span{byte}, out int)" />
bool IBinaryInteger<Int128>.TryWriteBigEndian(Span<byte> destination, out int bytesWritten)
{
if (destination.Length >= Size)
{
ulong lower = _lower;
ulong upper = _upper;
if (BitConverter.IsLittleEndian)
{
lower = BinaryPrimitives.ReverseEndianness(lower);
upper = BinaryPrimitives.ReverseEndianness(upper);
}
ref byte address = ref MemoryMarshal.GetReference(destination);
Unsafe.WriteUnaligned(ref address, upper);
Unsafe.WriteUnaligned(ref Unsafe.AddByteOffset(ref address, sizeof(ulong)), lower);
bytesWritten = Size;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.TryWriteLittleEndian(Span{byte}, out int)" />
bool IBinaryInteger<Int128>.TryWriteLittleEndian(Span<byte> destination, out int bytesWritten)
{
if (destination.Length >= Size)
{
ulong lower = _lower;
ulong upper = _upper;