Skip to content

Commit

Permalink
#1839: add an implementation of bit_cast and make sure that the sizes…
Browse files Browse the repository at this point in the history
… of the different bit values are conssistent
  • Loading branch information
nmm0 committed Jun 2, 2022
1 parent 6c2bfed commit 121aa67
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
18 changes: 18 additions & 0 deletions src/vt/utils/bits/bits_packer.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,27 @@

#include <cassert>
#include <cstdlib>
#include <cstring>

namespace vt { namespace utils {

// Non-constexpr C++14 version of bit_cast
// See: https://en.cppreference.com/w/cpp/numeric/bit_cast
template<typename Dst, typename Src>
std::enable_if_t<
sizeof(Dst) == sizeof(Src)
&& std::is_trivially_copyable<Dst>::value
&& std::is_trivially_copyable<Src>::value
&& std::is_trivially_constructible<Dst>::value,
Dst
>
bit_cast(const Src &src) {
Dst dst;
std::memcpy(&dst, &src, sizeof(Dst));
return dst;
}


struct BitPacker {
using FieldType = int64_t;
using FieldUnsignedType = uint64_t;
Expand Down
10 changes: 3 additions & 7 deletions src/vt/utils/bits/bits_packer.impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,9 @@ BitPacker::setFieldDynamic(
using UnsignedBitField = std::make_unsigned_t<BitField>;
auto const nbits = (sizeof(BitField) * 8) - len;
field = field & ~(gen_bit_mask(len) << start);
UnsignedBitField seg;
// Static cast will not work for negative types if we end up with that
std::memcpy(&seg, &segment, sizeof(UnsignedBitField));
auto bits = ((seg << nbits) >> nbits) << start;
BitField field_bits;
std::memcpy(&field_bits, &bits, sizeof(BitField));
field = field | field_bits;
auto seg = bit_cast<UnsignedBitField>(static_cast<BitField>(segment));
UnsignedBitField bits = ((seg << nbits) >> nbits) << start;
field = field | bit_cast<BitField>( bits );
}

template <FieldType start, FieldType len, typename BitField>
Expand Down

0 comments on commit 121aa67

Please sign in to comment.