Common C++ classes and routines used by my applications such as argument parser, IO and conversion utilities
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.6 KiB

8 years ago
#ifndef IOUTILITIES_COPY_H
#define IOUTILITIES_COPY_H
#include "../global.h"
8 years ago
#include <functional>
#include <iostream>
8 years ago
namespace IoUtilities {
/*!
* \class IoUtilities::CopyHelper
* \brief The CopyHelper class helps to copy bytes from one stream to another.
8 years ago
* \tparam Specifies the buffer size.
*/
template <std::size_t bufferSize> class CPP_UTILITIES_EXPORT CopyHelper {
8 years ago
public:
CopyHelper();
void copy(std::istream &input, std::ostream &output, std::size_t count);
void callbackCopy(std::istream &input, std::ostream &output, std::size_t count, const std::function<bool(void)> &isAborted,
const std::function<void(double)> &callback);
char *buffer();
8 years ago
private:
char m_buffer[bufferSize];
};
/*!
* \brief Constructs a new copy helper.
*/
template <std::size_t bufferSize> CopyHelper<bufferSize>::CopyHelper()
{
}
8 years ago
/*!
* \brief Copies \a count bytes from \a input to \a output.
* \remarks Set an exception mask using std::ios::exceptions() to get a std::ios_base::failure exception
* when an IO error occurs.
8 years ago
*/
template <std::size_t bufferSize> void CopyHelper<bufferSize>::copy(std::istream &input, std::ostream &output, std::size_t count)
8 years ago
{
while (count > bufferSize) {
8 years ago
input.read(m_buffer, bufferSize);
output.write(m_buffer, bufferSize);
count -= bufferSize;
}
input.read(m_buffer, count);
output.write(m_buffer, count);
}
/*!
* \brief Copies \a count bytes from \a input to \a output. The procedure might be aborted and
* progress updates will be reported.
8 years ago
*
* Copying is aborted when \a isAborted returns true. The current progress is reported by calling
* the specified \a callback function.
8 years ago
*
* \remarks Set an exception mask using std::ios::exceptions() to get a std::ios_base::failure exception
* when an IO error occurs.
8 years ago
*/
template <std::size_t bufferSize>
void CopyHelper<bufferSize>::callbackCopy(std::istream &input, std::ostream &output, std::size_t count, const std::function<bool(void)> &isAborted,
const std::function<void(double)> &callback)
8 years ago
{
const std::size_t totalBytes = count;
while (count > bufferSize) {
8 years ago
input.read(m_buffer, bufferSize);
output.write(m_buffer, bufferSize);
count -= bufferSize;
if (isAborted()) {
8 years ago
return;
}
callback(static_cast<double>(totalBytes - count) / totalBytes);
}
input.read(m_buffer, count);
output.write(m_buffer, count);
callback(1.0);
}
/*!
* \brief Returns the internal buffer.
*/
template <std::size_t bufferSize> char *CopyHelper<bufferSize>::buffer()
{
return m_buffer;
}
} // namespace IoUtilities
8 years ago
#endif // IOUTILITIES_COPY_H