ascii: add UDL for vector and array conversions

This commit is contained in:
Danny Robson 2018-01-23 18:51:37 +11:00
parent 007add45f2
commit dda3a4a8e7
2 changed files with 42 additions and 3 deletions

View File

@ -11,11 +11,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2016 Danny Robson <danny@nerdcruft.net>
* Copyright 2016-2018 Danny Robson <danny@nerdcruft.net>
*/
#ifndef __CRUFT_UTIL_ASCII_HPP
#define __CRUFT_UTIL_ASCII_HPP
#ifndef CRUFT_UTIL_ASCII_HPP
#define CRUFT_UTIL_ASCII_HPP
#include "annotation.hpp"
@ -125,4 +125,40 @@ namespace util::ascii {
}
}
///////////////////////////////////////////////////////////////////////////////
#include "debug.hpp"
#include <vector>
/// convert an ascii string of hex digits into a vector of uint8
std::vector<std::uint8_t>
inline
operator"" _hex2u8 (const char *str, size_t len)
{
CHECK_MOD (len, 2);
std::vector<uint8_t> res (len/2);
for (size_t i = 0; i < len; i += 2)
res[i/2] = util::ascii::from_hex (str[i]) << 4 | util::ascii::from_hex (str[i+1]);
return res;
};
///////////////////////////////////////////////////////////////////////////////
template <typename CharT, CharT ...StrV>
constexpr auto
operator"" _hex2array (void)
{
static_assert (sizeof ...(StrV) % 2 == 0);
std::array<std::uint8_t,sizeof...(StrV)/2> res {};
constexpr CharT literal[] = { StrV... };
for (size_t i = 0; i < res.size (); ++i)
res[i] = util::ascii::from_hex (literal[i*2+0]) << 4 |
util::ascii::from_hex (literal[i*2+1]);
return res;
}
#endif

View File

@ -75,5 +75,8 @@ main (int, char**)
);
}
tap.expect_eq ("6a"_hex2u8, std::vector<uint8_t>({0x6a}), "hex2u8, 1 byte");
tap.expect_eq ("a6"_hex2array, std::array<uint8_t,1> ({0xa6}), "hex2array, 1 byte");
return tap.status ();
}