Skip to content

Commit

Permalink
define stream insertion for std::byte in tests
Browse files Browse the repository at this point in the history
Change-Id: I5dca691416482ae27ab31bc176fd5217b8e3fd8f
  • Loading branch information
oliverlee committed Nov 23, 2023
1 parent 6fddc29 commit 0803a3a
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
21 changes: 21 additions & 0 deletions test_ut/test_ut_example.cpp
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
#include <boost/ut.hpp>

#include <array>
#include <cstddef>
#include <ranges>
#include <sstream>

auto main() -> int
{
using ::boost::ut::eq;
using ::boost::ut::expect;
using ::boost::ut::range_eq;
using ::boost::ut::test;

// all of these tests are intended to fail in order to demonstrate information
// printed on test failure

test("test range eq, lhs smaller") = [] {
constexpr auto data1 = std::array{1, 2, 3};
constexpr auto data2 = std::views::iota(1, 5);
Expand All @@ -29,4 +35,19 @@ auto main() -> int

expect(range_eq(data1, data2));
};

test("print byte") = [] {
constexpr auto expected = "01100000";

const auto actual = (std::stringstream{} << std::byte{0b1110'0000}).str();

expect(eq(expected, actual));
};

test("print byte array") = [] {
constexpr auto data1 = std::array{std::byte{0xDEU}, std::byte{0xADU}};
constexpr auto data2 = std::array{std::byte{0xBEU}, std::byte{0xEFU}};

expect(eq(data1, data2));
};
}
39 changes: 39 additions & 0 deletions ut.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,50 @@
#include <include/boost/ut.hpp>

#include <algorithm>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <ostream>
#include <ranges>
#include <type_traits>

namespace starflate::test::detail {

template <class Printer>
auto& print(Printer& p, std::byte b)
{
using U = std::uint8_t;

const auto value = static_cast<std::uint8_t>(b);

for (auto mask = U{0x80U}; mask != U{}; mask >>= 1U) {
p << (static_cast<bool>(value & mask) ? '1' : '0');
}

return p;
}

} // namespace starflate::test::detail

template <
class Ostream,
class = std::enable_if_t<
std::derived_from<std::remove_cvref_t<Ostream>, std::ostream>>>
auto operator<<(Ostream&& os, std::byte b)
-> decltype(os << char{}, std::forward<Ostream>(os))
{
::starflate::test::detail::print(os, b);
return std::forward<Ostream>(os);
}

namespace boost::ut {

auto& operator<<(printer& p, std::byte b)
{
return ::starflate::test::detail::print(p, b);
}

namespace detail {

template <class TLhs, class TRhs>
Expand Down

0 comments on commit 0803a3a

Please sign in to comment.