// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace CommunityToolkit.HighPerformance;
///
/// Helpers for working with the type.
///
public static class BoolExtensions
{
///
/// Converts the given value into a .
///
/// The input value to convert.
/// 1 if is , 0 otherwise.
/// This method does not contain branching instructions.
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe byte ToByte(this bool flag)
{
// Whenever we need to take the address of an argument, we make a local copy first.
// This will be removed by the JIT anyway, but it can help produce better codegen and
// remove unwanted stack spills if the caller is using constant arguments. This is
// because taking the address of an argument can interfere with some of the flow
// analysis executed by the JIT, which can in some cases block constant propagation.
bool copy = flag;
return *(byte*)©
}
///
/// Converts the given value to an mask with
/// all bits representing the value of the input flag (either 0xFFFFFFFF or 0x00000000).
///
/// The input value to convert.
/// 0xFFFFFFFF if is , 0x00000000 otherwise.
///
/// This method does not contain branching instructions, and it is only guaranteed to work with
/// values being either 0 or 1. Operations producing a result,
/// such as numerical comparisons, always result in a valid value. If the value is
/// produced by fields with a custom ,
/// or by using or other unsafe APIs to directly manipulate the underlying
/// data though, it is responsibility of the caller to ensure the validity of the provided value.
///
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int ToBitwiseMask32(this bool flag)
{
bool copy = flag;
byte rangeFlag = *(byte*)©
int negativeFlag = rangeFlag - 1;
int mask = ~negativeFlag;
return mask;
}
///
/// Converts the given value to a mask with
/// all bits representing the value of the input flag (either all 1s or 0s).
///
/// The input value to convert.
/// All 1s if is , all 0s otherwise.
/// This method does not contain branching instructions. See additional note in .
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe long ToBitwiseMask64(this bool flag)
{
bool copy = flag;
byte rangeFlag = *(byte*)©
long negativeFlag = (long)rangeFlag - 1;
long mask = ~negativeFlag;
return mask;
}
}