diff --git a/include/etl/unaligned_type.h b/include/etl/unaligned_type.h index 9b4ae6629..426c5c780 100644 --- a/include/etl/unaligned_type.h +++ b/include/etl/unaligned_type.h @@ -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& at_address(void* address) + { + return *reinterpret_cast*>(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& at_address(const void* address) + { + return *reinterpret_cast*>(address); + } }; template diff --git a/test/test_unaligned_type.cpp b/test/test_unaligned_type.cpp index 16fb31b22..5c07a7665 100644 --- a/test/test_unaligned_type.cpp +++ b/test/test_unaligned_type.cpp @@ -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); + } }; }