使用C ++用户定义的文字来初始化数组 [英] Using a C++ user-defined literal to initialise an array
问题描述
我有一堆测试向量,以十六进制字符串形式表示:
I have a bunch of test vectors, presented in the form of hexadecimal strings:
MSG: 6BC1BEE22E409F96E93D7E117393172A
MAC: 070A16B46B4D4144F79BDD9DD04A287C
MSG: 6BC1BEE22E409F96E93D7E117393172AAE2D8A57
MAC: 7D85449EA6EA19C823A7BF78837DFADE
等我需要以某种方式将它们放入C ++程序中,而无需进行过多的编辑.有多种选择:
etc. I need to get these into a C++ program somehow, without too much editing required. There are various options:
- 手动将测试向量编辑为
0x6B,0xC1,0xBE,...
形式
- 手动将测试向量编辑为"6BC1BEE22E409F96E93D7E117393172A"的形式,并编写一个在运行时将其转换为字节数组的函数.
- 编写一个程序以解析测试向量并输出C ++代码.
- Edit the test vectors by hand into the form
0x6B,0xC1,0xBE,...
- Edit the test vectors by hand into the form "6BC1BEE22E409F96E93D7E117393172A" and write a function to convert that into a byte array at run time.
- Write a program to parse the test vectors and output C++ code.
但是我最终使用的是:
- 用户定义的文字,
因为很有趣.我定义了一个帮助程序类HexByteArray
和一个用户定义的文字运算符HexByteArray operator "" _$ (const char* s)
,该运算符解析格式为"0xXX...XX"
的字符串,其中XX...XX
是十六进制数的偶数. HexByteArray
包括对const uint8_t*
和std::vector<uint8_t>
的转换运算符.所以现在我可以写例如
because fun. I defined a helper class HexByteArray
and a user-defined literal operator HexByteArray operator "" _$ (const char* s)
that parses a string of the form "0xXX...XX"
, where XX...XX
is an even number of hex digits. HexByteArray
includes conversion operators to const uint8_t*
and std::vector<uint8_t>
. So now I can write e.g.
struct {
std::vector<uint8_t> MSG ;
uint8_t* MAC ;
} Test1 = {
0x6BC1BEE22E409F96E93D7E117393172A_$,
0x070A16B46B4D4144F79BDD9DD04A287C_$
} ;
哪个效果很好.但是现在这是我的问题:我也可以对数组执行此操作吗?例如:
Which works nicely. But now here is my question: Can I do this for arrays as well? For instance:
uint8_t MAC[16] = 0x070A16B46B4D4144F79BDD9DD04A287C_$ ;
甚至
uint8_t MAC[] = 0x070A16B46B4D4144F79BDD9DD04A287C_$ ;
我看不到如何进行这项工作.要初始化数组,我似乎需要std::initializer_list
.但据我所知,只有编译器才能实例化此类内容.有什么想法吗?
I can't see how to make this work. To initialise an array, I would seem to need an std::initializer_list
. But as far as I can tell, only the compiler can instantiate such a thing. Any ideas?
这是我的代码:
HexByteArray.h
#include <cstdint>
#include <vector>
class HexByteArray
{
public:
HexByteArray (const char* s) ;
~HexByteArray() { delete[] a ; }
operator const uint8_t*() && { const uint8_t* t = a ; a = 0 ; return t ; }
operator std::vector<uint8_t>() &&
{
std::vector<uint8_t> v ( a, a + len ) ;
a = 0 ;
return v ;
}
class ErrorInvalidPrefix { } ;
class ErrorHexDigit { } ;
class ErrorOddLength { } ;
private:
const uint8_t* a = 0 ;
size_t len ;
} ;
inline HexByteArray operator "" _$ (const char* s)
{
return HexByteArray (s) ;
}
HexByteArray.cpp
#include "HexByteArray.h"
#include <cctype>
#include <cstring>
HexByteArray::HexByteArray (const char* s)
{
if (s[0] != '0' || toupper (s[1]) != 'X') throw ErrorInvalidPrefix() ;
s += 2 ;
// Special case: 0x0_$ is an empty array (because 0x_$ is invalid C++ syntax)
if (!strcmp (s, "0"))
{
a = nullptr ; len = 0 ;
}
else
{
for (len = 0 ; s[len] ; len++) if (!isxdigit (s[len])) throw ErrorHexDigit() ;
if (len & 1) throw ErrorOddLength() ;
len /= 2 ;
uint8_t* t = new uint8_t[len] ;
for (size_t i = 0 ; i < len ; i++, s += 2)
sscanf (s, "%2hhx", &t[i]) ;
a = t ;
}
}
推荐答案
使用数字文字运算符模板,其签名为:
template <char...>
result_type operator "" _x();
此外,由于数据是在编译时已知的,因此我们最好将所有内容都设为constexpr
.请注意,我们使用 std::array
代替C样式的数组:>
Also, since the data is known at compile-time, we might as well make everything constexpr
. Note that we use std::array
instead of C-style arrays:
#include <cstdint>
#include <array>
#include <vector>
// Constexpr hex parsing algorithm follows:
struct InvalidHexDigit {};
struct InvalidPrefix {};
struct OddLength {};
constexpr std::uint8_t hex_value(char c)
{
if ('0' <= c && c <= '9') return c - '0';
// This assumes ASCII:
if ('A' <= c && c <= 'F') return c - 'A' + 10;
if ('a' <= c && c <= 'f') return c - 'a' + 10;
// In constexpr-land, this is a compile-time error if execution reaches it:
// The weird `if (c == c)` is to work around gcc 8.2 erroring out here even though
// execution doesn't reach it.
if (c == c) throw InvalidHexDigit{};
}
constexpr std::uint8_t parse_single(char a, char b)
{
return (hex_value(a) << 4) | hex_value(b);
}
template <typename Iter, typename Out>
constexpr auto parse_hex(Iter begin, Iter end, Out out)
{
if (end - begin <= 2) throw InvalidPrefix{};
if (begin[0] != '0' || begin[1] != 'x') throw InvalidPrefix{};
if ((end - begin) % 2 != 0) throw OddLength{};
begin += 2;
while (begin != end)
{
*out = parse_single(*begin, *(begin + 1));
begin += 2;
++out;
}
return out;
}
// Make this a template to defer evaluation until later
template <char... cs>
struct HexByteArray {
static constexpr auto to_array()
{
constexpr std::array<char, sizeof...(cs)> data{cs...};
std::array<std::uint8_t, (sizeof...(cs) / 2 - 1)> result{};
parse_hex(data.begin(), data.end(), result.begin());
return result;
}
constexpr operator std::array<std::uint8_t, (sizeof...(cs) / 2)>() const
{
return to_array();
}
operator std::vector<std::uint8_t>() const
{
constexpr auto tmp = to_array();
return std::vector<std::uint8_t>{tmp.begin(), tmp.end()};
}
};
template <char... cs>
constexpr auto operator"" _$()
{
static_assert(sizeof...(cs) % 2 == 0, "Must be an even number of chars");
return HexByteArray<cs...>{};
}
示例用法:
auto data_array = 0x6BC1BEE22E409F96E93D7E117393172A_$ .to_array();
std::vector<std::uint8_t> data_vector = 0x6BC1BEE22E409F96E93D7E117393172A_$;
请注意, identifier 中的$
实际上是gcc扩展,因此它是非标准的C ++.考虑使用_$
以外的UDL.
As a side note, $
in an identifier is actually a gcc extension, so it's non-standard C++. Consider using a UDL other than _$
.
这篇关于使用C ++用户定义的文字来初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!