-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabuffer.cpp
More file actions
73 lines (60 loc) · 1.51 KB
/
databuffer.cpp
File metadata and controls
73 lines (60 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "databuffer.h"
/**
* @brief DataBuffer - 线程安全的环形数据缓冲区实现
*
* Requirements: 2.1, 2.2, 2.3, 2.4
*/
DataBuffer::DataBuffer(int capacity, QObject *parent)
: QObject(parent)
, m_capacity(capacity > 0 ? capacity : 65536)
{
m_buffer.reserve(m_capacity);
}
void DataBuffer::write(const QByteArray &data)
{
if (data.isEmpty()) {
return;
}
QMutexLocker locker(&m_mutex);
// 如果新数据本身就超过容量,只保留最新的 capacity 字节
if (data.size() >= m_capacity) {
m_buffer = data.right(m_capacity);
return;
}
// 追加新数据
m_buffer.append(data);
// 如果超过容量,移除最旧的数据(保留最新数据)
// Requirements: 2.2 - 覆盖最旧数据,保留最新数据
if (m_buffer.size() > m_capacity) {
int excess = m_buffer.size() - m_capacity;
m_buffer.remove(0, excess);
}
}
QByteArray DataBuffer::readAll()
{
QMutexLocker locker(&m_mutex);
// Requirements: 2.4 - FIFO 顺序返回数据
QByteArray result = m_buffer;
m_buffer.clear();
return result;
}
bool DataBuffer::isEmpty() const
{
QMutexLocker locker(&m_mutex);
return m_buffer.isEmpty();
}
int DataBuffer::size() const
{
QMutexLocker locker(&m_mutex);
return m_buffer.size();
}
void DataBuffer::clear()
{
QMutexLocker locker(&m_mutex);
m_buffer.clear();
}
int DataBuffer::capacity() const
{
// capacity 在构造后不变,无需加锁
return m_capacity;
}