Qx v0.5.7
Qt Extensions Library
Loading...
Searching...
No Matches
qx-bytearray.h
1#ifndef QX_BYTEARRAY_H
2#define QX_BYTEARRAY_H
3
4// Shared Lib Support
5#include "qx/core/qx_core_export.h"
6
7// Standard Library Includes
8#include <concepts>
9
10// Qt Includes
11#include <QByteArray>
12#include <QtEndian>
13
14// Extra-component Includes
16
17namespace Qx
18{
19
20class QX_CORE_EXPORT ByteArray
21{
22//-Class Functions----------------------------------------------------------------------------------------------
23public:
24 template<typename T>
25 requires arithmetic<T>
27 {
28 // Ensure correct byte order
29 if(endianness == QSysInfo::LittleEndian)
30 primitive = qToLittleEndian(primitive);
31 else
32 primitive = qToBigEndian(primitive);
33
34 // Return QByteArray constructed from primitive viewed as a char array
35 return QByteArray(reinterpret_cast<const char*>(&primitive), sizeof(T));
36 }
37
38 /*
39 * This is valid C++17 syntax for explicit template specialization, but due to an outstanding
40 * bug this won't compile with GCC: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85282
41 *
42 * The workaround is to fake partial template specialization using a dummy template parameter.
43 */
44#if defined __GNUC__ && !defined __clang__ // If using G++
45 template<typename>
46 inline QByteArray fromPrimitive(bool primitive, QSysInfo::Endian endianness)
47#else
48 template<>
49 inline QByteArray fromPrimitive<bool>(bool primitive, QSysInfo::Endian endianness)
50#endif
51 {
52 // Ensures true -> 0x01 and false -> 0x00
53 return primitive ? QByteArray(1, '\x01') : QByteArray(1, '\x00');
54 }
55
56 template<typename T>
57 requires arithmetic<T>
59 {
60 if(endianness == QSysInfo::LittleEndian)
61 {
62 if(ba.size() < sizeof(T))
63 ba.append(sizeof(T) - ba.size(),'\x00');
64 return qFromLittleEndian<T>(ba);
65 }
66 else
67 {
68 if(ba.size() < sizeof(T))
69 ba.prepend(sizeof(T) - ba.size(),'\x00');
70 return qFromBigEndian<T>(ba);
71 }
72 }
73};
74
75}
76
77#endif // QX_BYTEARRAY_H
The ByteArray class is a collection of static functions pertaining to QByteArray.
Definition qx-bytearray.h:21
static QByteArray fromPrimitive(T primitive, QSysInfo::Endian endianness=QSysInfo::ByteOrder)
Definition qx-bytearray.h:26
static T toPrimitive(QByteArray ba, QSysInfo::Endian endianness=QSysInfo::ByteOrder)
Definition qx-bytearray.h:58
Specifies that a type is an arithmetic type.
Definition qx-concepts.h:497
The Qx namespace is the main namespace through which all non-global functionality of the Qx library i...
Definition qx-processwaiter.cpp:5
QByteArray & append(QByteArrayView data)
QByteArray & prepend(QByteArrayView ba)
qsizetype size() const const
The qx-concepts header file provides a library of general purpose concepts as an extension of the sta...