Skip to content

Commit 0c464e5

Browse files
authored
Merge pull request #603 from elbeno/field-fitting
✨ Add `can_hold` to `field`
2 parents 924cab6 + 066e932 commit 0c464e5

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

include/msg/field.hpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,8 @@ template <bits_locator... BLs> struct field_locator_t {
274274
template <typename T> constexpr static auto extent_in() -> std::size_t {
275275
return std::max({std::size_t{}, BLs::template extent_in<T>()...});
276276
}
277+
278+
constexpr static auto size = (std::size_t{} + ... + BLs::size);
277279
};
278280
} // namespace detail
279281

@@ -451,6 +453,10 @@ class field_t : public field_spec_t<Name, T, detail::field_size<Ats...>>,
451453
return format("{}: 0x{:x}"_sc, spec_t::name, v);
452454
}
453455

456+
constexpr static auto can_hold(value_type v) -> bool {
457+
return locator_t::size >= static_cast<std::size_t>(stdx::bit_width(v));
458+
}
459+
454460
// ======================================================================
455461
// default construction values
456462
template <T V>

test/msg/field_insert.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,18 @@ TEST_CASE("trivially_copyable field type ", "[field insert]") {
121121
F::insert(data, custom_t{17});
122122
CHECK(17 == stdx::bit_cast<custom_t>(data[0]).v);
123123
}
124+
125+
TEST_CASE("value fits in field", "[field insert]") {
126+
using F = field<"", std::uint32_t>::located<at{0_dw, 3_msb, 0_lsb}>;
127+
static_assert(F::can_hold(15));
128+
CHECK(F::can_hold(15));
129+
CHECK(not F::can_hold(16));
130+
}
131+
132+
TEST_CASE("value fits in split field", "[field insert]") {
133+
using F = field<"", std::uint32_t>::located<at{0_dw, 1_msb, 0_lsb},
134+
at{0_dw, 7_msb, 6_lsb}>;
135+
static_assert(F::can_hold(15));
136+
CHECK(F::can_hold(15));
137+
CHECK(not F::can_hold(16));
138+
}

0 commit comments

Comments
 (0)