diff --git a/tests/OrdinalsTest.cpp b/tests/OrdinalsTest.cpp new file mode 100644 index 00000000..8360b513 --- /dev/null +++ b/tests/OrdinalsTest.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include + +namespace facebook::yoga { + +TEST(Ordinals, iteration) { + std::deque expectedEdges{ + Edge::Left, + Edge::Top, + Edge::Right, + Edge::Bottom, + Edge::Start, + Edge::End, + Edge::Horizontal, + Edge::Vertical, + Edge::All}; + + for (auto edge : yoga::ordinals()) { + ASSERT_EQ(edge, expectedEdges.front()); + expectedEdges.pop_front(); + } + + ASSERT_TRUE(expectedEdges.empty()); +} + +} // namespace facebook::yoga diff --git a/yoga/enums/YogaEnums.h b/yoga/enums/YogaEnums.h index 7cbf94b7..a3e1191d 100644 --- a/yoga/enums/YogaEnums.h +++ b/yoga/enums/YogaEnums.h @@ -7,6 +7,7 @@ #pragma once +#include #include namespace facebook::yoga { @@ -14,13 +15,52 @@ namespace facebook::yoga { template constexpr inline int32_t ordinalCount(); +/** + * Count of bits needed to represent every ordinal + */ template constexpr inline int32_t bitCount(); -// Polyfill of C++ 23 to_underlying() -// https://en.cppreference.com/w/cpp/utility/to_underlying +/** + * Polyfill of C++ 23 to_underlying() + * https://en.cppreference.com/w/cpp/utility/to_underlying + */ constexpr auto to_underlying(auto e) noexcept { return static_cast>(e); } +/** + * Convenience function to iterate through every value in a Yoga enum as part of + * a range-based for loop. + */ +template +auto ordinals() { + struct Iterator { + EnumT e{}; + + EnumT operator*() const { + return e; + } + + Iterator& operator++() { + e = static_cast(to_underlying(e) + 1); + return *this; + } + + bool operator==(const Iterator& other) const = default; + bool operator!=(const Iterator& other) const = default; + }; + + struct Range { + Iterator begin() const { + return Iterator{}; + } + Iterator end() const { + return Iterator{static_cast(ordinalCount())}; + } + }; + + return Range{}; +} + } // namespace facebook::yoga diff --git a/yoga/style/Style.h b/yoga/style/Style.h index 3eb5cadd..2df44a75 100644 --- a/yoga/style/Style.h +++ b/yoga/style/Style.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include