Repository navigation
Description
Background and motivation
Conceptually, T.AllBitsSet returns an instance of the binary number type T where every bit is set to 1. For example, Int32.AllBitsSet is 0xFFFFFFFF, or -1. This concept is generally useful for masking purposes. For example, Vectors use AllBitsSet often for Conditional Select, as bitwise-anding a number with AllBitsSet will produce the same number, in contrast to bitwise-anding a number with Zero. As brought up by #60882, AllBitsSet would be a nice addition to the IBinaryNumber interface, potentially enabling future generic refactoring of Scalar<T>.
The following types would explicitly implement AllBitsSet: Double, Half, NFloat, Single, Byte, Char, Int16, Int32, Int64, IntPtr, SByte, UInt16, UInt32, UInt64, UIntPtr, BigInteger, Int128, Uint128.
Design of the implementation for all of these types is trivial except for BigInteger. For BigInteger, the most obvious implementation would be to return MinusOne, as despite the internal bit representation not being literally AllBitsSet (due to BigInteger having unbounded size), it behaves as such for bitwise operations.
API Proposal
namespace System.Numerics
{
public partial interface IBinaryNumber<TSelf>
{
static abstract TSelf AllBitsSet { get; }
}
}API Usage
T genericAlgorithm(T input)
where T : IBinaryNumber<T> {
return input + T.AllBitsSet;
}Alternative Designs
When deciding whether a method is implemented explicitly or implicitly for Generic Math, we have used the following rule: if the concept is trivially handled by knowing the concrete type, it's implemented explicitly. In other words, it is not exposed on the concrete type. This way, the implementation is only available when working with the generic interface.
In this case, we follow this logic and implement AllBitsSet explicitly, as knowing the concrete type leads to a trivial implementation (https://source.dot.net/#System.Private.CoreLib/Scalar.cs,11). However, it could be argued that AllBitsSet is conceptually tricky enough for some of these types that a implicit implementation is warranted.
Additional Notes
Currently, refactoring Scalar<T> to take advantage of this is not possible without a language change. More specifically, the language doesn't have a way to "bridge" type constraints. So, since Vector<T> is where T : struct but we'd want Scalar<T> to be where T : struct, IBinaryNumber<T>, we'd need the language to provide some way to allow Vector<T> to use Scalar<T> despite the mismatching type requirements.
Activity
bartonjs commentedon May 31, 2022
Video