| 1 | /* |
| 2 | * Copyright (C) 2016 The Qt Company Ltd. |
| 3 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 4 | * |
| 5 | * SPDX-License-Identifier: MIT |
| 6 | */ |
| 7 | |
| 8 | #pragma once |
| 9 | |
| 10 | #include <bitset> |
| 11 | #include <cstdio> |
| 12 | #include <cstdint> |
| 13 | |
| 14 | #include <yoga/YGEnums.h> |
| 15 | |
| 16 | QT_YOGA_NAMESPACE_BEGIN |
| 17 | |
| 18 | namespace facebook { |
| 19 | namespace yoga { |
| 20 | |
| 21 | namespace detail { |
| 22 | |
| 23 | // std::bitset with one bit for each option defined in YG_ENUM_SEQ_DECL |
| 24 | template <typename Enum> |
| 25 | using EnumBitset = std::bitset<facebook::yoga::enums::count<Enum>()>; |
| 26 | |
| 27 | constexpr size_t log2ceilFn(size_t n) { |
| 28 | return n < 1 ? 0 : (1 + log2ceilFn(n: n / 2)); |
| 29 | } |
| 30 | |
| 31 | constexpr int mask(size_t bitWidth, size_t index) { |
| 32 | return ((1 << bitWidth) - 1) << index; |
| 33 | } |
| 34 | |
| 35 | // The number of bits necessary to represent enums defined with YG_ENUM_SEQ_DECL |
| 36 | template <typename Enum> |
| 37 | constexpr size_t bitWidthFn() { |
| 38 | static_assert( |
| 39 | enums::count<Enum>() > 0, "Enums must have at least one entries" ); |
| 40 | return log2ceilFn(enums::count<Enum>() - 1); |
| 41 | } |
| 42 | |
| 43 | template <typename Enum> |
| 44 | constexpr Enum getEnumData(int flags, size_t index) { |
| 45 | return static_cast<Enum>((flags & mask(bitWidthFn<Enum>(), index)) >> index); |
| 46 | } |
| 47 | |
| 48 | template <typename Enum> |
| 49 | void setEnumData(uint32_t& flags, size_t index, int newValue) { |
| 50 | flags = (flags & ~mask(bitWidthFn<Enum>(), index)) | |
| 51 | ((newValue << index) & (mask(bitWidthFn<Enum>(), index))); |
| 52 | } |
| 53 | |
| 54 | template <typename Enum> |
| 55 | void setEnumData(uint8_t& flags, size_t index, int newValue) { |
| 56 | flags = (flags & ~static_cast<uint8_t>(mask(bitWidthFn<Enum>(), index))) | |
| 57 | ((newValue << index) & |
| 58 | (static_cast<uint8_t>(mask(bitWidthFn<Enum>(), index)))); |
| 59 | } |
| 60 | |
| 61 | constexpr bool getBooleanData(int flags, size_t index) { |
| 62 | return (flags >> index) & 1; |
| 63 | } |
| 64 | |
| 65 | inline void setBooleanData(uint8_t& flags, size_t index, bool value) { |
| 66 | if (value) { |
| 67 | flags |= 1 << index; |
| 68 | } else { |
| 69 | flags &= ~(1 << index); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | } // namespace detail |
| 74 | } // namespace yoga |
| 75 | } // namespace facebook |
| 76 | |
| 77 | QT_YOGA_NAMESPACE_END |
| 78 | |