memstream.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #if !defined(INCLUDED_STREAM_MEMSTREAM_H)
00023 #define INCLUDED_STREAM_MEMSTREAM_H
00024
00025 #include "itextstream.h"
00026 #include <algorithm>
00027 #include <vector>
00028 #include <string>
00029
00030 class BufferOutputStream : public TextOutputStream {
00031 std::vector<char> m_buffer;
00032 public:
00033 std::size_t write(const char* buffer, std::size_t length) {
00034 m_buffer.insert(m_buffer.end(), buffer, buffer + length);
00035 return length;
00036 }
00037 const char* data() const {
00038 return &(*m_buffer.begin());
00039 }
00040 std::size_t size() const {
00041 return m_buffer.size();
00042 }
00043 void clear() {
00044 std::vector<char> empty;
00045 std::swap(empty, m_buffer);
00046 }
00047 };
00048
00049 template<typename T>
00050 inline BufferOutputStream& operator<<(BufferOutputStream& ostream, const T& t) {
00051 return ostream_write(ostream, t);
00052 }
00053
00054
00055 class BufferInputStream : public TextInputStream {
00056 const char* m_read;
00057 const char* m_end;
00058 public:
00059 BufferInputStream(const char* buffer, std::size_t length)
00060 : m_read(buffer), m_end(buffer + length) {
00061 }
00062
00063 BufferInputStream(const std::string& buffer)
00064 : m_read(buffer.c_str()), m_end(buffer.c_str() + buffer.size()) {
00065 }
00066 std::size_t read(char* buffer, std::size_t length) {
00067 std::size_t count = std::min(std::size_t(m_end - m_read), length);
00068 const char* end = m_read + count;
00069 while (m_read != end) {
00070 *buffer++ = *m_read++;
00071 }
00072 return count;
00073 }
00074 };
00075
00076 #endif