Qx v0.6.2
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 Q_UNUSED(endianness);
53 // Ensures true -> 0x01 and false -> 0x00
54 return primitive ? QByteArray(1, '\x01') : QByteArray(1, '\x00');
55 }
56
57 template<typename T>
58 requires arithmetic<T>
60 {
61 if(endianness == QSysInfo::LittleEndian)
62 {
63 if(ba.size() < sizeof(T))
64 ba.append(sizeof(T) - ba.size(),'\x00');
65 return qFromLittleEndian<T>(ba);
66 }
67 else
68 {
69 if(ba.size() < sizeof(T))
70 ba.prepend(sizeof(T) - ba.size(),'\x00');
71 return qFromBigEndian<T>(ba);
72 }
73 }
74};
75
76}
77
78#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:59
Specifies that a type is an arithmetic type.
Definition qx-concepts.h:483
The Qx namespace is the main namespace through which all non-global functionality of the Qx library i...
Definition qx-abstracterror.cpp:13
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...