1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#ifndef QDATABUFFER_P_H
5#define QDATABUFFER_P_H
6
7//
8// W A R N I N G
9// -------------
10//
11// This file is not part of the Qt API. It exists for the convenience
12// of other Qt classes. This header file may change from version to
13// version without notice, or even be removed.
14//
15// We mean it.
16//
17
18#include <QtGui/private/qtguiglobal_p.h>
19#include "QtCore/qbytearray.h"
20
21#include <stdlib.h>
22
23QT_BEGIN_NAMESPACE
24
25template <typename Type> class QDataBuffer
26{
27 Q_DISABLE_COPY_MOVE(QDataBuffer)
28public:
29 explicit QDataBuffer(qsizetype res)
30 {
31 capacity = res;
32 if (res) {
33 QT_WARNING_PUSH
34 QT_WARNING_DISABLE_GCC("-Walloc-size-larger-than=")
35 buffer = (Type*) malloc(size: capacity * sizeof(Type));
36 QT_WARNING_POP
37 Q_CHECK_PTR(buffer);
38 } else {
39 buffer = nullptr;
40 }
41 siz = 0;
42 }
43
44 ~QDataBuffer()
45 {
46 if (buffer)
47 free(buffer);
48 }
49
50 inline void reset() { siz = 0; }
51
52 inline bool isEmpty() const { return siz==0; }
53
54 qsizetype size() const { return siz; }
55 inline Type *data() const { return buffer; }
56
57 Type &at(qsizetype i) { Q_ASSERT(i >= 0 && i < siz); return buffer[i]; }
58 const Type &at(qsizetype i) const { Q_ASSERT(i >= 0 && i < siz); return buffer[i]; }
59 inline Type &last() { Q_ASSERT(!isEmpty()); return buffer[siz-1]; }
60 inline const Type &last() const { Q_ASSERT(!isEmpty()); return buffer[siz-1]; }
61 inline Type &first() { Q_ASSERT(!isEmpty()); return buffer[0]; }
62 inline const Type &first() const { Q_ASSERT(!isEmpty()); return buffer[0]; }
63
64 inline void add(const Type &t) {
65 reserve(size: siz + 1);
66 buffer[siz] = t;
67 ++siz;
68 }
69
70 inline void pop_back() {
71 Q_ASSERT(siz > 0);
72 --siz;
73 }
74
75 void resize(qsizetype size) {
76 reserve(size);
77 siz = size;
78 }
79
80 void reserve(qsizetype size) {
81 if (size > capacity) {
82 if (capacity == 0)
83 capacity = 1;
84 while (capacity < size)
85 capacity *= 2;
86 buffer = (Type*) realloc(ptr: static_cast<void*>(buffer), size: capacity * sizeof(Type));
87 Q_CHECK_PTR(buffer);
88 }
89 }
90
91 void shrink(qsizetype size) {
92 Q_ASSERT(capacity >= size);
93 capacity = size;
94 if (size) {
95 buffer = (Type*) realloc(ptr: static_cast<void*>(buffer), size: capacity * sizeof(Type));
96 Q_CHECK_PTR(buffer);
97 siz = std::min(a: siz, b: size);
98 } else {
99 free(buffer);
100 buffer = nullptr;
101 siz = 0;
102 }
103 }
104
105 inline void swap(QDataBuffer<Type> &other) {
106 qSwap(capacity, other.capacity);
107 qSwap(siz, other.siz);
108 qSwap(buffer, other.buffer);
109 }
110
111 inline QDataBuffer &operator<<(const Type &t) { add(t); return *this; }
112
113private:
114 qsizetype capacity;
115 qsizetype siz;
116 Type *buffer;
117};
118
119QT_END_NAMESPACE
120
121#endif // QDATABUFFER_P_H
122

source code of qtbase/src/gui/painting/qdatabuffer_p.h