forked from Elleo/libQtSpotify
-
Notifications
You must be signed in to change notification settings - Fork 3
/
qspotifyringbuffer.cpp
85 lines (74 loc) · 1.97 KB
/
qspotifyringbuffer.cpp
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
74
75
76
77
78
79
80
81
82
83
84
85
#include "qspotifyringbuffer.h"
#include <cstring>
#include <algorithm>
QSpotifyRingbuffer::QSpotifyRingbuffer() :
m_readPos{}, m_writePos{}, m_size{}, m_isOpen{}
{
m_data = new char[BUF_SIZE];
memset(m_data, 0, BUF_SIZE);
}
QSpotifyRingbuffer::~QSpotifyRingbuffer()
{
if(m_data) delete[] m_data;
}
void QSpotifyRingbuffer::close()
{
memset(m_data, 0, BUF_SIZE);
m_readPos = 0;
m_writePos = 0;
m_size = 0;
m_isOpen = false;
}
void QSpotifyRingbuffer::reset()
{
memset(m_data, 0, BUF_SIZE);
m_readPos = 0;
m_writePos = 0;
m_size = 0;
m_isOpen = true;
}
void QSpotifyRingbuffer::open()
{
memset(m_data, 0, BUF_SIZE);
m_isOpen = true;
}
int QSpotifyRingbuffer::read(char *data, int numBytes)
{
if(!m_data) return 0;
numBytes = std::min(numBytes, m_size);
if(numBytes > 0) {
if(m_readPos + numBytes >= BUF_SIZE) {
int firstBytes = BUF_SIZE - m_readPos;
int secondBytes = numBytes - firstBytes;
memcpy(&data[0], &m_data[m_readPos], firstBytes);
memcpy(&data[firstBytes], &m_data[0], secondBytes);
m_readPos = secondBytes;
} else {
memcpy(&data[0], &m_data[m_readPos], numBytes);
m_readPos += numBytes;
}
m_size -= numBytes;
}
return numBytes;
}
int QSpotifyRingbuffer::write(const char *data, int numBytes)
{
if(!m_data) return 0;
numBytes = std::min(numBytes, BUF_SIZE - m_size);
if(m_writePos + numBytes >= BUF_SIZE) {
int firstBytes = BUF_SIZE - m_writePos;
int secondBytes = numBytes - firstBytes;
memcpy(&m_data[m_writePos], &data[0], firstBytes);
memcpy(&m_data[0], &data[firstBytes], secondBytes);
m_writePos = secondBytes;
} else {
memcpy(&m_data[m_writePos], &data[0], numBytes);
m_writePos += numBytes;
}
m_size += numBytes;
return numBytes;
}
int QSpotifyRingbuffer::freeBytes()
{
return BUF_SIZE - m_size;
}