barrier/lib/io/CBufferedOutputStream.cpp

105 lines
1.9 KiB
C++
Raw Normal View History

2002-08-02 19:57:46 +00:00
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file COPYING that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
2001-10-06 14:13:28 +00:00
#include "CBufferedOutputStream.h"
#include "XIO.h"
2001-10-06 14:13:28 +00:00
#include "CLock.h"
#include "CMutex.h"
#include "CThread.h"
#include "IJob.h"
//
// CBufferedOutputStream
//
CBufferedOutputStream::CBufferedOutputStream(
CMutex* mutex, IJob* adoptedFillCB, IJob* adoptedCloseCB) :
m_mutex(mutex),
m_fillCB(adoptedFillCB),
m_closeCB(adoptedCloseCB),
m_empty(mutex, true),
m_closed(false)
2001-10-06 14:13:28 +00:00
{
assert(m_mutex != NULL);
}
CBufferedOutputStream::~CBufferedOutputStream()
{
delete m_closeCB;
delete m_fillCB;
2001-10-06 14:13:28 +00:00
}
const void*
2002-06-17 13:31:21 +00:00
CBufferedOutputStream::peek(UInt32 n)
2001-10-06 14:13:28 +00:00
{
return m_buffer.peek(n);
}
void
2002-06-17 13:31:21 +00:00
CBufferedOutputStream::pop(UInt32 n)
2001-10-06 14:13:28 +00:00
{
m_buffer.pop(n);
if (m_buffer.getSize() == 0) {
m_empty.broadcast();
}
2001-10-06 14:13:28 +00:00
}
UInt32
CBufferedOutputStream::getSize() const
2001-10-06 14:13:28 +00:00
{
return m_buffer.getSize();
}
void
CBufferedOutputStream::close()
2001-10-06 14:13:28 +00:00
{
CLock lock(m_mutex);
if (m_closed) {
throw XIOClosed();
}
m_closed = true;
if (m_closeCB != NULL) {
2001-10-06 14:13:28 +00:00
m_closeCB->run();
}
}
UInt32
CBufferedOutputStream::write(const void* buffer, UInt32 n)
2001-10-06 14:13:28 +00:00
{
CLock lock(m_mutex);
if (m_closed) {
throw XIOClosed();
}
bool wasEmpty = (m_buffer.getSize() == 0);
m_buffer.write(buffer, n);
if (wasEmpty && n > 0) {
if (m_fillCB != NULL) {
m_fillCB->run();
}
}
2001-10-06 14:13:28 +00:00
return n;
}
void
CBufferedOutputStream::flush()
2001-10-06 14:13:28 +00:00
{
// wait until all data is written
CLock lock(m_mutex);
while (m_buffer.getSize() > 0) {
m_empty.wait();
}
2001-10-06 14:13:28 +00:00
}