1
/***************************************************************************
2
* Copyright (C) 2005 - 2007 by *
4
* Max Howell, Last.fm Ltd <max@last.fm> *
6
* This program is free software; you can redistribute it and/or modify *
7
* it under the terms of the GNU General Public License as published by *
8
* the Free Software Foundation; either version 2 of the License, or *
9
* (at your option) any later version. *
11
* This program is distributed in the hope that it will be useful, *
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14
* GNU General Public License for more details. *
16
* You should have received a copy of the GNU General Public License *
17
* along with this program; if not, write to the *
18
* Free Software Foundation, Inc., *
19
* 51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA. *
20
***************************************************************************/
22
#include "RingBuffer.h"
30
RingBuffer::RingBuffer() : m_buffer( 0 ),
35
// A better start value? They'll grow as needed anyway.
36
m_buffer = (char*) malloc( m_size );
41
RingBuffer::write( const QByteArray& buffer )
43
Q_DEBUG_BLOCK << "towrite:" << buffer.size();
44
qDebug() << "used" << used();
45
qDebug() << "free" << free();
46
qDebug() << "size" << size();
48
int length = buffer.size();
49
const char* src = buffer.data();
50
const uint free = this->free();
52
if (length > (int)free)
53
expandBy( length - free + 1 );
55
for (int cnt; length > 0; )
57
cnt = qMin( length, m_size - m_write_index );
58
memcpy( m_buffer + m_write_index, src, cnt );
59
m_write_index = (m_write_index + cnt) % m_size;
67
RingBuffer::read( QByteArray& tofill )
69
Q_DEBUG_BLOCK << "toread:" << tofill.size();
70
qDebug() << "used" << used();
71
qDebug() << "free" << free();
72
qDebug() << "size" << size();
74
if (tofill.size() > used())
75
tofill.resize( used() );
77
int length = tofill.size();
78
char* out = tofill.data();
82
int cnt = qMin( length, m_size - m_read_index );
83
memcpy( out, m_buffer + m_read_index, cnt );
84
m_read_index = (m_read_index + cnt) % m_size;
92
RingBuffer::expandBy( uint amount )
94
//Q_DEBUG_BLOCK << amount;
96
char* tmp = (char*)realloc( m_buffer, sizeof(char) * ( m_size + amount ) );
99
Q_ASSERT( !"Could not reallocate buffer!" );
105
// Don't screw up the read order or ugly noises will ensue
106
if (m_read_index > m_write_index)
108
memmove( m_buffer + m_read_index + amount,
109
m_buffer + m_read_index,
110
m_size - m_read_index );
111
m_read_index += amount;
116
//qDebug() << m_size;