Skip to content

Commit

Permalink
add random access range member functions to bit_span
Browse files Browse the repository at this point in the history
Change-Id: I765c657b65dfa246b67e20c73c90f05c9b49c5c3
  • Loading branch information
oliverlee committed Sep 21, 2023
1 parent b369178 commit d27c8d9
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
4 changes: 2 additions & 2 deletions huffman/src/bit_span.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

namespace starflate::huffman {
/// A non-owning span of bits. Allows for iteration over the individual bits.
class bit_span
class bit_span : public std::ranges::view_interface<bit_span>
{
const std::byte* data_;
std::size_t bit_size_;
Expand Down Expand Up @@ -53,7 +53,7 @@ class bit_span
{
const auto newOffset = static_cast<difference_type>(offset_) + n;
assert(newOffset >= 0);
offset_ = static_cast<size_t>(newOffset);
offset_ = static_cast<std::size_t>(newOffset);
return *this;
}

Expand Down
3 changes: 1 addition & 2 deletions huffman/src/detail/iterator_interface.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ namespace starflate::huffman::detail {
template <class D>
struct iterator_interface
{

template <class I = D>
constexpr auto operator->() const -> typename I::pointer
{
Expand Down Expand Up @@ -75,7 +74,7 @@ struct iterator_interface
constexpr auto
operator[](typename I::difference_type n) const -> typename I::reference
{
return *(*this + n);
return *(static_cast<const I&>(*this) + n);
}

template <std::same_as<D> I>
Expand Down
28 changes: 28 additions & 0 deletions huffman/test/bit_span_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,32 @@ auto main() -> int
return huffman::bit{c};
})));
};

test("indexable") = [] {
static constexpr auto data =
std::array{std::byte{0b10101010}, std::byte{0xff}};
constexpr auto bs = huffman::bit_span{data};

// NOLINTBEGIN(readability-magic-numbers)

static_assert(bs[0] == 1_b);
static_assert(bs[1] == 0_b);
static_assert(bs[2] == 1_b);
static_assert(bs[3] == 0_b);
static_assert(bs[4] == 1_b);
static_assert(bs[5] == 0_b);
static_assert(bs[6] == 1_b);
static_assert(bs[7] == 0_b);

expect(bs[8] == 1_b);
expect(bs[9] == 1_b);
expect(bs[10] == 1_b);
expect(bs[11] == 1_b);
expect(bs[12] == 1_b);
expect(bs[13] == 1_b);
expect(bs[14] == 1_b);
expect(bs[15] == 1_b);

// NOLINTEND(readability-magic-numbers)
};
}

0 comments on commit d27c8d9

Please sign in to comment.