From 04fe4e760d51dc9bdc1d16257a65edd52caeaa39 Mon Sep 17 00:00:00 2001 From: Thomas Debrunner Date: Mon, 11 Dec 2023 18:13:31 +0100 Subject: [PATCH] utils: use std::copy for pack / unpack --- include/mav/utils.h | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/include/mav/utils.h b/include/mav/utils.h index 65736c1..f18a39e 100644 --- a/include/mav/utils.h +++ b/include/mav/utils.h @@ -203,25 +203,25 @@ namespace mav { } - template - A _packUnpack(B b) { - union U { - A a; - B b; - }; - U u; - u.b = b; - return u.a; + template + To _packUnpack(From o) { + static_assert(sizeof(To) == sizeof(From), "Cannot pack/unpack different sizes"); + static_assert(std::is_trivially_copyable::value, "Cannot pack/unpack non-trivially copyable types"); + static_assert(std::is_trivially_copyable::value, "Cannot pack/unpack non-trivially copyable types"); + To result; + std::memcpy(&result, &o, sizeof(To)); + return result; } + - template - T floatUnpack(float f) { - return _packUnpack(f); + template + To floatUnpack(float f) { + return _packUnpack(f); } - template - float floatPack(T o) { - return _packUnpack(o); + template + float floatPack(From o) { + return _packUnpack(o); }