AUI Framework  master
Cross-platform base for C++ UI apps
Loading...
Searching...
No Matches
bit.h
    1/*
    2 * AUI Framework - Declarative UI toolkit for modern C++20
    3 * Copyright (C) 2020-2025 Alex2772 and Contributors
    4 *
    5 * SPDX-License-Identifier: MPL-2.0
    6 *
    7 * This Source Code Form is subject to the terms of the Mozilla Public
    8 * License, v. 2.0. If a copy of the MPL was not distributed with this
    9 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
   10 */
   11
   12#pragma once
   13
   14// android again lacks C++20 features.
   15// this header implements #include <bit> (notably, std::bit_ceil)
   16
   17#include <concepts>
   18#include <bit>
   19#include "concepts.h"
   20
   21namespace aui {
   22
   23template <aui::unsigned_integral T>
   24    requires(!aui::same_as<T, bool>) && (!aui::same_as<T, char>) && (!aui::same_as<T, char8_t>) &&
   25            (!aui::same_as<T, char16_t>) && (!aui::same_as<T, char32_t>) && (!aui::same_as<T, wchar_t>)
   26constexpr T bit_width(T x) noexcept {
   27    return std::numeric_limits<T>::digits - std::countl_zero(x);
   28}
   29
   30template <aui::unsigned_integral T>
   31    requires(!aui::same_as<T, bool>) && (!aui::same_as<T, char>) && (!aui::same_as<T, char8_t>) &&
   32            (!aui::same_as<T, char16_t>) && (!aui::same_as<T, char32_t>) && (!aui::same_as<T, wchar_t>)
   33constexpr T bit_ceil(T x) noexcept {
   34    if (x <= 1u)
   35        return T(1);
   36    if constexpr (aui::same_as<T, decltype(+x)>)
   37        return T(1) << aui::bit_width(T(x - 1));
   38    else {   // for types subject to integral promotion
   39        constexpr int offset_for_ub = std::numeric_limits<unsigned>::digits - std::numeric_limits<T>::digits;
   40        return T(1u << (aui::bit_width(T(x - 1)) + offset_for_ub) >> offset_for_ub);
   41    }
   42}
   43
   44template <aui::unsigned_integral T>
   45    requires(!std::same_as<T, bool>) && (!std::same_as<T, char>) && (!std::same_as<T, char8_t>) &&
   46            (!std::same_as<T, char16_t>) && (!std::same_as<T, char32_t>) && (!std::same_as<T, wchar_t>)
   47constexpr T bit_floor(T x) noexcept {
   48    if (x != 0)
   49        return T { 1 } << (aui::bit_width(x) - 1);
   50    return 0;
   51}
   52
   53}   // namespace aui