Skip to content

Commit

Permalink
Add at_address() to etl::unaligned_type
Browse files Browse the repository at this point in the history
  • Loading branch information
rolandreichweinbmw committed Dec 21, 2024
1 parent 99d7537 commit 97f2321
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
22 changes: 22 additions & 0 deletions include/etl/unaligned_type.h
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,28 @@ namespace etl
}
}
};

//*******************************************
/// at_address
///\brief Helps to reinterprete memory as unaligned_type. Overload for write access.
///\tparam address Pointer to memory to be reinterpreted.
///\return Reference to unaligned_type object at location specified by address
//*******************************************
static unaligned_type<T, Endian_>& at_address(void* address)
{
return *reinterpret_cast<unaligned_type<T, Endian_>*>(address);
}

//*******************************************
/// at_address
///\brief Helps to reinterprete memory as unaligned_type. Overload for read only access to const memory.
///\tparam address Pointer to memory to be reinterpreted.
///\return Reference to unaligned_type object at location specified by address
//*******************************************
static const unaligned_type<T, Endian_>& at_address(const void* address)
{
return *reinterpret_cast<const unaligned_type<T, Endian_>*>(address);
}
};

template <typename T, int Endian_>
Expand Down
20 changes: 20 additions & 0 deletions test/test_unaligned_type.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -981,6 +981,26 @@ namespace
CHECK_EQUAL(0x12, bev0);
CHECK_EQUAL(0x34, bev1);
}

//*************************************************************************
TEST(test_at_address)
{
uint8_t data[] = {0x01, 0x02, 0x03, 0x04};

CHECK_EQUAL(etl::be_uint32_t::at_address(data), 0x01020304);
CHECK_EQUAL(etl::le_uint32_t::at_address(data), 0x04030201);

etl::be_uint32_t::at_address(data) = 0x12345678;
CHECK_EQUAL(etl::le_uint32_t::at_address(data), 0x78563412);
}

TEST(test_const_at_address)
{
const uint8_t data[] = {0x01, 0x02, 0x03, 0x04};

CHECK_EQUAL(etl::be_uint32_t::at_address(data), 0x01020304);
CHECK_EQUAL(etl::le_uint32_t::at_address(data), 0x04030201);
}
};
}

Expand Down

0 comments on commit 97f2321

Please sign in to comment.