Skip to content

Commit

Permalink
✨ Add compile time bit_value::insert
Browse files Browse the repository at this point in the history
Add bit_value::insert API that can take a bit field and value as
template arguments resulting in a completely compile time value.

Set bit_value template to default std::uint32_t for ease of use.
  • Loading branch information
kammce committed Apr 29, 2024
1 parent 83a02bd commit 74340b7
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion include/libhal-util/bit.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ constexpr auto bit_extract(bit_mask p_field,
return static_cast<T>(masked);
}

template<std::unsigned_integral T>
template<std::unsigned_integral T = std::uint32_t>
class bit_value
{
public:
Expand Down Expand Up @@ -373,6 +373,22 @@ class bit_value
return *this;
}

template<bit_mask p_field, std::unsigned_integral auto p_value>
constexpr auto& insert()
{
// AND value with mask to remove any bits beyond the specified width.
// Shift masked value into bit position and OR with target value.
auto shifted_field = static_cast<T>(p_value) << p_field.position;
auto new_value = shifted_field & p_field.value<T>();

// Clear width's number of bits in the target value at the bit position
// specified.
m_value = m_value & ~p_field.value<T>();
m_value = m_value | static_cast<T>(new_value);

return *this;
}

template<std::integral U>
[[nodiscard]] constexpr auto to()
{
Expand Down

0 comments on commit 74340b7

Please sign in to comment.