-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Int32.cs
1454 lines (1208 loc) · 56.7 KB
/
Int32.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;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct Int32
: IComparable,
IConvertible,
ISpanFormattable,
IComparable<int>,
IEquatable<int>,
IBinaryInteger<int>,
IMinMaxValue<int>,
ISignedNumber<int>,
IUtf8SpanFormattable,
IBinaryIntegerParseAndFormatInfo<int>
{
private readonly int m_value; // Do not rename (binary serialization)
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
/// <summary>Represents the additive identity (0).</summary>
private const int AdditiveIdentity = 0;
/// <summary>Represents the multiplicative identity (1).</summary>
private const int MultiplicativeIdentity = 1;
/// <summary>Represents the number one (1).</summary>
private const int One = 1;
/// <summary>Represents the number zero (0).</summary>
private const int Zero = 0;
/// <summary>Represents the number negative one (-1).</summary>
private const int NegativeOne = -1;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns :
// 0 if the values are equal
// Negative number if _value is less than value
// Positive number if _value is more than value
// null is considered to be less than any instance, hence returns positive number
// If object is not of type Int32, this method throws an ArgumentException.
//
public int CompareTo(object? value)
{
if (value == null)
{
return 1;
}
// NOTE: Cannot use return (_value - value) as this causes a wrap
// around in cases where _value - value > MaxValue.
if (value is int i)
{
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeInt32);
}
public int CompareTo(int value)
{
// NOTE: Cannot use return (_value - value) as this causes a wrap
// around in cases where _value - value > MaxValue.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals([NotNullWhen(true)] object? obj)
{
if (!(obj is int))
{
return false;
}
return m_value == ((int)obj).m_value;
}
[NonVersionable]
public bool Equals(int obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return m_value;
}
public override string ToString()
{
return Number.Int32ToDecStr(m_value);
}
public string ToString([StringSyntax(StringSyntaxAttribute.NumericFormat)] string? format)
{
return ToString(format, null);
}
public string ToString(IFormatProvider? provider)
{
return Number.FormatInt32(m_value, 0, null, provider);
}
public string ToString([StringSyntax(StringSyntaxAttribute.NumericFormat)] string? format, IFormatProvider? provider)
{
return Number.FormatInt32(m_value, ~0, format, provider);
}
public bool TryFormat(Span<char> destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
{
return Number.TryFormatInt32(m_value, ~0, 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.TryFormatInt32(m_value, ~0, format, provider, utf8Destination, out bytesWritten);
}
public static int Parse(string s) => Parse(s, NumberStyles.Integer, provider: null);
public static int Parse(string s, NumberStyles style) => Parse(s, style, provider: null);
public static int Parse(string s, IFormatProvider? provider) => Parse(s, NumberStyles.Integer, provider);
public static int Parse(string s, NumberStyles style, IFormatProvider? provider)
{
if (s is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); }
return Parse(s.AsSpan(), style, provider);
}
public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseBinaryInteger<char, int>(s, style, NumberFormatInfo.GetInstance(provider));
}
public static bool TryParse([NotNullWhen(true)] string? s, out int result) => TryParse(s, NumberStyles.Integer, provider: null, out result);
public static bool TryParse(ReadOnlySpan<char> s, out int 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 32-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 32-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 int result) => TryParse(utf8Text, NumberStyles.Integer, provider: null, out result);
public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out int 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 int result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseBinaryInteger(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Int32;
}
bool IConvertible.ToBoolean(IFormatProvider? provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider? provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider? provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider? provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider? provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider? provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider? provider)
{
return m_value;
}
uint IConvertible.ToUInt32(IFormatProvider? provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider? provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider? provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider? provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider? provider)
{
return Convert.ToDouble(m_value);
}
decimal IConvertible.ToDecimal(IFormatProvider? provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider? provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider? provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
//
// IAdditionOperators
//
/// <inheritdoc cref="IAdditionOperators{TSelf, TOther, TResult}.op_Addition(TSelf, TOther)" />
static int IAdditionOperators<int, int, int>.operator +(int left, int right) => left + right;
/// <inheritdoc cref="IAdditionOperators{TSelf, TOther, TResult}.op_Addition(TSelf, TOther)" />
static int IAdditionOperators<int, int, int>.operator checked +(int left, int right) => checked(left + right);
//
// IAdditiveIdentity
//
/// <inheritdoc cref="IAdditiveIdentity{TSelf, TResult}.AdditiveIdentity" />
static int IAdditiveIdentity<int, int>.AdditiveIdentity => AdditiveIdentity;
//
// IBinaryInteger
//
/// <inheritdoc cref="IBinaryInteger{TSelf}.DivRem(TSelf, TSelf)" />
public static (int Quotient, int Remainder) DivRem(int left, int right) => Math.DivRem(left, right);
/// <inheritdoc cref="IBinaryInteger{TSelf}.LeadingZeroCount(TSelf)" />
[Intrinsic]
public static int LeadingZeroCount(int value) => BitOperations.LeadingZeroCount((uint)value);
/// <inheritdoc cref="IBinaryInteger{TSelf}.PopCount(TSelf)" />
[Intrinsic]
public static int PopCount(int value) => BitOperations.PopCount((uint)value);
/// <inheritdoc cref="IBinaryInteger{TSelf}.RotateLeft(TSelf, int)" />
[Intrinsic]
public static int RotateLeft(int value, int rotateAmount) => (int)BitOperations.RotateLeft((uint)value, rotateAmount);
/// <inheritdoc cref="IBinaryInteger{TSelf}.RotateRight(TSelf, int)" />
[Intrinsic]
public static int RotateRight(int value, int rotateAmount) => (int)BitOperations.RotateRight((uint)value, rotateAmount);
/// <inheritdoc cref="IBinaryInteger{TSelf}.TrailingZeroCount(TSelf)" />
[Intrinsic]
public static int TrailingZeroCount(int value) => BitOperations.TrailingZeroCount(value);
/// <inheritdoc cref="IBinaryInteger{TSelf}.TryReadBigEndian(ReadOnlySpan{byte}, bool, out TSelf)" />
static bool IBinaryInteger<int>.TryReadBigEndian(ReadOnlySpan<byte> source, bool isUnsigned, out int value)
{
int 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 >= sizeof(int)))
{
// 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 > sizeof(int))
{
if (source[..^sizeof(int)].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[^sizeof(int)]))
{
// 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 >= sizeof(int))
{
sourceRef = ref Unsafe.Add(ref sourceRef, source.Length - sizeof(int));
// We have at least 4 bytes, so just read the ones we need directly
result = Unsafe.ReadUnaligned<int>(ref sourceRef);
if (BitConverter.IsLittleEndian)
{
result = BinaryPrimitives.ReverseEndianness(result);
}
}
else
{
// We have between 1 and 3 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 |= ((1 << ((sizeof(int) * 8) - 1)) >> (((sizeof(int) - source.Length) * 8) - 1));
}
}
}
value = result;
return true;
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.TryReadLittleEndian(ReadOnlySpan{byte}, bool, out TSelf)" />
static bool IBinaryInteger<int>.TryReadLittleEndian(ReadOnlySpan<byte> source, bool isUnsigned, out int value)
{
int 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 >= sizeof(int)))
{
// 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 > sizeof(int))
{
if (source[sizeof(int)..].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[sizeof(int) - 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 >= sizeof(int))
{
// We have at least 4 bytes, so just read the ones we need directly
result = Unsafe.ReadUnaligned<int>(ref sourceRef);
if (!BitConverter.IsLittleEndian)
{
result = BinaryPrimitives.ReverseEndianness(result);
}
}
else
{
// We have between 1 and 3 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 <<= ((sizeof(int) - source.Length) * 8);
result = BinaryPrimitives.ReverseEndianness(result);
if (!isUnsigned)
{
result |= ((1 << ((sizeof(int) * 8) - 1)) >> (((sizeof(int) - source.Length) * 8) - 1));
}
}
}
value = result;
return true;
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.GetShortestBitLength()" />
int IBinaryInteger<int>.GetShortestBitLength()
{
int value = m_value;
if (value >= 0)
{
return (sizeof(int) * 8) - LeadingZeroCount(value);
}
else
{
return (sizeof(int) * 8) + 1 - LeadingZeroCount(~value);
}
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.GetByteCount()" />
int IBinaryInteger<int>.GetByteCount() => sizeof(int);
/// <inheritdoc cref="IBinaryInteger{TSelf}.TryWriteBigEndian(Span{byte}, out int)" />
bool IBinaryInteger<int>.TryWriteBigEndian(Span<byte> destination, out int bytesWritten)
{
if (destination.Length >= sizeof(int))
{
int value = BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(m_value) : m_value;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
bytesWritten = sizeof(int);
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
/// <inheritdoc cref="IBinaryInteger{TSelf}.TryWriteLittleEndian(Span{byte}, out int)" />
bool IBinaryInteger<int>.TryWriteLittleEndian(Span<byte> destination, out int bytesWritten)
{
if (destination.Length >= sizeof(int))
{
int value = BitConverter.IsLittleEndian ? m_value : BinaryPrimitives.ReverseEndianness(m_value);
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
bytesWritten = sizeof(int);
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
//
// IBinaryNumber
//
/// <inheritdoc cref="IBinaryNumber{TSelf}.AllBitsSet" />
static int IBinaryNumber<int>.AllBitsSet => NegativeOne;
/// <inheritdoc cref="IBinaryNumber{TSelf}.IsPow2(TSelf)" />
public static bool IsPow2(int value) => BitOperations.IsPow2(value);
/// <inheritdoc cref="IBinaryNumber{TSelf}.Log2(TSelf)" />
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Log2(int value)
{
if (value < 0)
{
ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException();
}
return BitOperations.Log2((uint)value);
}
//
// IBitwiseOperators
//
/// <inheritdoc cref="IBitwiseOperators{TSelf, TOther, TResult}.op_BitwiseAnd(TSelf, TOther)" />
static int IBitwiseOperators<int, int, int>.operator &(int left, int right) => left & right;
/// <inheritdoc cref="IBitwiseOperators{TSelf, TOther, TResult}.op_BitwiseOr(TSelf, TOther)" />
static int IBitwiseOperators<int, int, int>.operator |(int left, int right) => left | right;
/// <inheritdoc cref="IBitwiseOperators{TSelf, TOther, TResult}.op_ExclusiveOr(TSelf, TOther)" />
static int IBitwiseOperators<int, int, int>.operator ^(int left, int right) => left ^ right;
/// <inheritdoc cref="IBitwiseOperators{TSelf, TOther, TResult}.op_OnesComplement(TSelf)" />
static int IBitwiseOperators<int, int, int>.operator ~(int value) => ~value;
//
// IComparisonOperators
//
/// <inheritdoc cref="IComparisonOperators{TSelf, TOther, TResult}.op_LessThan(TSelf, TOther)" />
static bool IComparisonOperators<int, int, bool>.operator <(int left, int right) => left < right;
/// <inheritdoc cref="IComparisonOperators{TSelf, TOther, TResult}.op_LessThanOrEqual(TSelf, TOther)" />
static bool IComparisonOperators<int, int, bool>.operator <=(int left, int right) => left <= right;
/// <inheritdoc cref="IComparisonOperators{TSelf, TOther, TResult}.op_GreaterThan(TSelf, TOther)" />
static bool IComparisonOperators<int, int, bool>.operator >(int left, int right) => left > right;
/// <inheritdoc cref="IComparisonOperators{TSelf, TOther, TResult}.op_GreaterThanOrEqual(TSelf, TOther)" />
static bool IComparisonOperators<int, int, bool>.operator >=(int left, int right) => left >= right;
//
// IDecrementOperators
//
/// <inheritdoc cref="IDecrementOperators{TSelf}.op_Decrement(TSelf)" />
static int IDecrementOperators<int>.operator --(int value) => --value;
/// <inheritdoc cref="IDecrementOperators{TSelf}.op_Decrement(TSelf)" />
static int IDecrementOperators<int>.operator checked --(int value) => checked(--value);
//
// IDivisionOperators
//
/// <inheritdoc cref="IDivisionOperators{TSelf, TOther, TResult}.op_Division(TSelf, TOther)" />
static int IDivisionOperators<int, int, int>.operator /(int left, int right) => left / right;
//
// IEqualityOperators
//
/// <inheritdoc cref="IEqualityOperators{TSelf, TOther, TResult}.op_Equality(TSelf, TOther)" />
static bool IEqualityOperators<int, int, bool>.operator ==(int left, int right) => left == right;
/// <inheritdoc cref="IEqualityOperators{TSelf, TOther, TResult}.op_Inequality(TSelf, TOther)" />
static bool IEqualityOperators<int, int, bool>.operator !=(int left, int right) => left != right;
//
// IIncrementOperators
//
/// <inheritdoc cref="IIncrementOperators{TSelf}.op_Increment(TSelf)" />
static int IIncrementOperators<int>.operator ++(int value) => ++value;
/// <inheritdoc cref="IIncrementOperators{TSelf}.op_CheckedIncrement(TSelf)" />
static int IIncrementOperators<int>.operator checked ++(int value) => checked(++value);
//
// IMinMaxValue
//
/// <inheritdoc cref="IMinMaxValue{TSelf}.MinValue" />
static int IMinMaxValue<int>.MinValue => MinValue;
/// <inheritdoc cref="IMinMaxValue{TSelf}.MaxValue" />
static int IMinMaxValue<int>.MaxValue => MaxValue;
//
// IModulusOperators
//
/// <inheritdoc cref="IModulusOperators{TSelf, TOther, TResult}.op_Modulus(TSelf, TOther)" />
static int IModulusOperators<int, int, int>.operator %(int left, int right) => left % right;
//
// IMultiplicativeIdentity
//
/// <inheritdoc cref="IMultiplicativeIdentity{TSelf, TResult}.MultiplicativeIdentity" />
static int IMultiplicativeIdentity<int, int>.MultiplicativeIdentity => MultiplicativeIdentity;
//
// IMultiplyOperators
//
/// <inheritdoc cref="IMultiplyOperators{TSelf, TOther, TResult}.op_Multiply(TSelf, TOther)" />
static int IMultiplyOperators<int, int, int>.operator *(int left, int right) => left * right;
/// <inheritdoc cref="IMultiplyOperators{TSelf, TOther, TResult}.op_CheckedMultiply(TSelf, TOther)" />
static int IMultiplyOperators<int, int, int>.operator checked *(int left, int right) => checked(left * right);
//
// INumber
//
/// <inheritdoc cref="INumber{TSelf}.Clamp(TSelf, TSelf, TSelf)" />
public static int Clamp(int value, int min, int max) => Math.Clamp(value, min, max);
/// <inheritdoc cref="INumber{TSelf}.CopySign(TSelf, TSelf)" />
public static int CopySign(int value, int sign)
{
int absValue = value;
if (absValue < 0)
{
absValue = -absValue;
}
if (sign >= 0)
{
if (absValue < 0)
{
Math.ThrowNegateTwosCompOverflow();
}
return absValue;
}
return -absValue;
}
/// <inheritdoc cref="INumber{TSelf}.Max(TSelf, TSelf)" />
public static int Max(int x, int y) => Math.Max(x, y);
/// <inheritdoc cref="INumber{TSelf}.MaxNumber(TSelf, TSelf)" />
static int INumber<int>.MaxNumber(int x, int y) => Max(x, y);
/// <inheritdoc cref="INumber{TSelf}.Min(TSelf, TSelf)" />
public static int Min(int x, int y) => Math.Min(x, y);
/// <inheritdoc cref="INumber{TSelf}.MinNumber(TSelf, TSelf)" />
static int INumber<int>.MinNumber(int x, int y) => Min(x, y);
/// <inheritdoc cref="INumber{TSelf}.Sign(TSelf)" />
public static int Sign(int value) => Math.Sign(value);
//
// INumberBase
//
/// <inheritdoc cref="INumberBase{TSelf}.One" />
static int INumberBase<int>.One => One;
/// <inheritdoc cref="INumberBase{TSelf}.Radix" />
static int INumberBase<int>.Radix => 2;
/// <inheritdoc cref="INumberBase{TSelf}.Zero" />
static int INumberBase<int>.Zero => Zero;
/// <inheritdoc cref="INumberBase{TSelf}.Abs(TSelf)" />
public static int Abs(int value) => Math.Abs(value);
/// <inheritdoc cref="INumberBase{TSelf}.CreateChecked{TOther}(TOther)" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int CreateChecked<TOther>(TOther value)
where TOther : INumberBase<TOther>
{
int result;
if (typeof(TOther) == typeof(int))
{
result = (int)(object)value;
}
else if (!TryConvertFromChecked(value, out result) && !TOther.TryConvertToChecked(value, out result))
{
ThrowHelper.ThrowNotSupportedException();
}
return result;
}
/// <inheritdoc cref="INumberBase{TSelf}.CreateSaturating{TOther}(TOther)" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int CreateSaturating<TOther>(TOther value)
where TOther : INumberBase<TOther>
{
int result;
if (typeof(TOther) == typeof(int))
{
result = (int)(object)value;
}
else if (!TryConvertFromSaturating(value, out result) && !TOther.TryConvertToSaturating(value, out result))
{
ThrowHelper.ThrowNotSupportedException();
}
return result;
}
/// <inheritdoc cref="INumberBase{TSelf}.CreateTruncating{TOther}(TOther)" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int CreateTruncating<TOther>(TOther value)
where TOther : INumberBase<TOther>
{
int result;
if (typeof(TOther) == typeof(int))
{
result = (int)(object)value;
}
else if (!TryConvertFromTruncating(value, out result) && !TOther.TryConvertToTruncating(value, out result))
{
ThrowHelper.ThrowNotSupportedException();
}
return result;
}
/// <inheritdoc cref="INumberBase{TSelf}.IsCanonical(TSelf)" />
static bool INumberBase<int>.IsCanonical(int value) => true;
/// <inheritdoc cref="INumberBase{TSelf}.IsComplexNumber(TSelf)" />
static bool INumberBase<int>.IsComplexNumber(int value) => false;
/// <inheritdoc cref="INumberBase{TSelf}.IsEvenInteger(TSelf)" />
public static bool IsEvenInteger(int value) => (value & 1) == 0;
/// <inheritdoc cref="INumberBase{TSelf}.IsFinite(TSelf)" />
static bool INumberBase<int>.IsFinite(int value) => true;
/// <inheritdoc cref="INumberBase{TSelf}.IsImaginaryNumber(TSelf)" />
static bool INumberBase<int>.IsImaginaryNumber(int value) => false;
/// <inheritdoc cref="INumberBase{TSelf}.IsInfinity(TSelf)" />
static bool INumberBase<int>.IsInfinity(int value) => false;
/// <inheritdoc cref="INumberBase{TSelf}.IsInteger(TSelf)" />
static bool INumberBase<int>.IsInteger(int value) => true;
/// <inheritdoc cref="INumberBase{TSelf}.IsNaN(TSelf)" />
static bool INumberBase<int>.IsNaN(int value) => false;
/// <inheritdoc cref="INumberBase{TSelf}.IsNegative(TSelf)" />
public static bool IsNegative(int value) => value < 0;
/// <inheritdoc cref="INumberBase{TSelf}.IsNegativeInfinity(TSelf)" />
static bool INumberBase<int>.IsNegativeInfinity(int value) => false;
/// <inheritdoc cref="INumberBase{TSelf}.IsNormal(TSelf)" />
static bool INumberBase<int>.IsNormal(int value) => value != 0;
/// <inheritdoc cref="INumberBase{TSelf}.IsOddInteger(TSelf)" />
public static bool IsOddInteger(int value) => (value & 1) != 0;
/// <inheritdoc cref="INumberBase{TSelf}.IsPositive(TSelf)" />
public static bool IsPositive(int value) => value >= 0;
/// <inheritdoc cref="INumberBase{TSelf}.IsPositiveInfinity(TSelf)" />
static bool INumberBase<int>.IsPositiveInfinity(int value) => false;
/// <inheritdoc cref="INumberBase{TSelf}.IsRealNumber(TSelf)" />
static bool INumberBase<int>.IsRealNumber(int value) => true;
/// <inheritdoc cref="INumberBase{TSelf}.IsSubnormal(TSelf)" />
static bool INumberBase<int>.IsSubnormal(int value) => false;
/// <inheritdoc cref="INumberBase{TSelf}.IsZero(TSelf)" />
static bool INumberBase<int>.IsZero(int value) => (value == 0);
/// <inheritdoc cref="INumberBase{TSelf}.MaxMagnitude(TSelf, TSelf)" />
public static int MaxMagnitude(int x, int y)
{
int absX = x;
if (absX < 0)
{
absX = -absX;
if (absX < 0)
{
return x;
}
}
int absY = y;
if (absY < 0)
{
absY = -absY;
if (absY < 0)
{
return y;
}
}
if (absX > absY)
{
return x;
}
if (absX == absY)
{
return IsNegative(x) ? y : x;
}
return y;
}
/// <inheritdoc cref="INumberBase{TSelf}.MaxMagnitudeNumber(TSelf, TSelf)" />
static int INumberBase<int>.MaxMagnitudeNumber(int x, int y) => MaxMagnitude(x, y);
/// <inheritdoc cref="INumberBase{TSelf}.MinMagnitude(TSelf, TSelf)" />
public static int MinMagnitude(int x, int y)
{
int absX = x;
if (absX < 0)
{
absX = -absX;
if (absX < 0)
{
return y;
}
}
int absY = y;
if (absY < 0)
{
absY = -absY;
if (absY < 0)
{
return x;
}
}
if (absX < absY)
{
return x;
}
if (absX == absY)
{
return IsNegative(x) ? x : y;
}
return y;
}
/// <inheritdoc cref="INumberBase{TSelf}.MinMagnitudeNumber(TSelf, TSelf)" />
static int INumberBase<int>.MinMagnitudeNumber(int x, int y) => MinMagnitude(x, y);
/// <inheritdoc cref="INumberBase{TSelf}.TryConvertFromChecked{TOther}(TOther, out TSelf)" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool INumberBase<int>.TryConvertFromChecked<TOther>(TOther value, out int result) => TryConvertFromChecked(value, out result);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryConvertFromChecked<TOther>(TOther value, out int result)
where TOther : INumberBase<TOther>
{
// In order to reduce overall code duplication and improve the inlinabilty of these
// methods for the corelib types we have `ConvertFrom` handle the same sign and
// `ConvertTo` handle the opposite sign. However, since there is an uneven split
// between signed and unsigned types, the one that handles unsigned will also
// handle `Decimal`.
//
// That is, `ConvertFrom` for `int` will handle the other signed types and
// `ConvertTo` will handle the unsigned types
if (typeof(TOther) == typeof(double))
{
double actualValue = (double)(object)value;
result = checked((int)actualValue);
return true;
}
else if (typeof(TOther) == typeof(Half))
{
Half actualValue = (Half)(object)value;
result = checked((int)actualValue);
return true;
}
else if (typeof(TOther) == typeof(short))
{
short actualValue = (short)(object)value;
result = actualValue;
return true;
}
else if (typeof(TOther) == typeof(long))
{
long actualValue = (long)(object)value;
result = checked((int)actualValue);
return true;
}
else if (typeof(TOther) == typeof(Int128))
{
Int128 actualValue = (Int128)(object)value;
result = checked((int)actualValue);
return true;
}
else if (typeof(TOther) == typeof(nint))
{
nint actualValue = (nint)(object)value;
result = checked((int)actualValue);
return true;
}
else if (typeof(TOther) == typeof(sbyte))
{
sbyte actualValue = (sbyte)(object)value;
result = actualValue;
return true;
}
else if (typeof(TOther) == typeof(float))
{
float actualValue = (float)(object)value;
result = checked((int)actualValue);
return true;
}
else
{
result = default;
return false;
}
}
/// <inheritdoc cref="INumberBase{TSelf}.TryConvertFromSaturating{TOther}(TOther, out TSelf)" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool INumberBase<int>.TryConvertFromSaturating<TOther>(TOther value, out int result) => TryConvertFromSaturating(value, out result);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryConvertFromSaturating<TOther>(TOther value, out int result)
where TOther : INumberBase<TOther>
{
// In order to reduce overall code duplication and improve the inlinabilty of these
// methods for the corelib types we have `ConvertFrom` handle the same sign and
// `ConvertTo` handle the opposite sign. However, since there is an uneven split
// between signed and unsigned types, the one that handles unsigned will also
// handle `Decimal`.
//
// That is, `ConvertFrom` for `int` will handle the other signed types and