C
C#5w ago
Foxtrek_64

INumberBase<>.TryConvertFromTruncating()

I have a Bit type which wraps bool and implements INumberBase and IComparable. I need to implement the TryConvertFromTruncating method Should I just reimplement my FromSaturating method which returns Bit.One if the value is not zero, otherwise Bit.Zero? Or is there another better implementation. I do have int.CreateTruncating() in the body temporarily but this naturally creates unexpected limitations in the type The purpose of this type is just to test a case for my SSN type where it should throw if converting to a numeric type that doesn't support 0-9, and no such built in type satisfies this, but it is at least good practice for building an integral numeric type.
4 Replies
reflectronic
reflectronic5w ago
i mean, the implementation you "want" is basically n & 1 == 1 that truncates your n-bit value to a 1-bit value
Foxtrek_64
Foxtrek_645w ago
Doesn't look like INumberBase supports the & operator so value & TOther.One doesn't work
reflectronic
reflectronic5w ago
yes, because it has to be an IBinaryInteger
Foxtrek_64
Foxtrek_645w ago
Changed the base type of bit to be an IBinaryInteger because I felt it fit better Still trying to figure this one out though
static bool INumberBase<Bit>.TryConvertFromChecked<TOther>(TOther value, out Bit result)
{
result = FromNumber(value);
return true;
}

INumberBase<Bit>.TryConvertFromSaturating<TOther>(TOther value, out Bit result)
{
result = value != TOther.Zero ? One : Zero;
return true;
}

INumberBase<Bit>.TryConvertFromTruncating<TOther>(TOther value, out Bit result)
{
}

internal static Bit FromNumber<TNumber>(TNumber value)
where TNumber : INumberBase<TNumber>
=> TryFromNumber(value, out Bit? result)
? result
: ThrowOverflowException<Bit>();

internal static bool TryFromNumber<TNumber>(TNumber value, [NotNullWhen(true)] out Bit? result)
where TNumber : INumberBase<TNumber>
{
result = null;
if (value == TNumber.Zero)
{
result = Zero;
return true;
}
if (value == TNumber.One)
{
result = One;
return true;
}

return false;
}
static bool INumberBase<Bit>.TryConvertFromChecked<TOther>(TOther value, out Bit result)
{
result = FromNumber(value);
return true;
}

INumberBase<Bit>.TryConvertFromSaturating<TOther>(TOther value, out Bit result)
{
result = value != TOther.Zero ? One : Zero;
return true;
}

INumberBase<Bit>.TryConvertFromTruncating<TOther>(TOther value, out Bit result)
{
}

internal static Bit FromNumber<TNumber>(TNumber value)
where TNumber : INumberBase<TNumber>
=> TryFromNumber(value, out Bit? result)
? result
: ThrowOverflowException<Bit>();

internal static bool TryFromNumber<TNumber>(TNumber value, [NotNullWhen(true)] out Bit? result)
where TNumber : INumberBase<TNumber>
{
result = null;
if (value == TNumber.Zero)
{
result = Zero;
return true;
}
if (value == TNumber.One)
{
result = One;
return true;
}

return false;
}