wibble 1.1
posix.h
Go to the documentation of this file.
1#ifndef WIBBLE_STREAM_POSIX_H
2#define WIBBLE_STREAM_POSIX_H
3
4#include <wibble/exception.h>
5#include <streambuf>
6#include <unistd.h>
7#include <cstdio>
8
9// http://www.icce.rug.nl/documents/cplusplus/cplusplus21.html#CONCRETE
10// 21.2.1: Classes for output operations
11
12namespace wibble {
13namespace stream {
14
15class PosixBuf : public std::streambuf
16{
17private:
18 // The output buffer
19 char* m_buf;
20 size_t m_buf_size;
21 int m_fd;
22
23 // Disallow copy
24 PosixBuf(const PosixBuf&);
25 PosixBuf& operator=(const PosixBuf&);
26
27public:
28 // PosixBuf functions
29
30 PosixBuf() : m_buf(0), m_buf_size(0), m_fd(-1) {}
31 PosixBuf(int fd, size_t bufsize = 4096) : m_buf(0), m_buf_size(0), m_fd(-1)
32 {
34 }
36 {
37 if (m_buf)
38 {
39 sync();
40 delete[] m_buf;
41 }
42 if (m_fd != -1)
43 {
44 ::close(m_fd);
45 }
46 }
47
54 void attach(int fd, size_t bufsize = 4096)
55 {
56 m_buf = new char[1024];
57 if (!m_buf)
58 throw wibble::exception::Consistency("allocating 1024 bytes for posix stream buffer", "allocation failed");
59 m_fd = fd;
60 m_buf_size = 1024;
61 setp(m_buf, m_buf + m_buf_size);
62 }
63
71 int detach()
72 {
73 sync();
74 int res = m_fd;
75 delete[] m_buf;
76 m_buf = 0;
77 m_buf_size = 0;
78 m_fd = -1;
79 // TODO: setp or anything like that, to tell the streambuf that there's
80 // no buffer anymore?
81 setp(0, 0);
82 return res;
83 }
84
86 int fd() const { return m_fd; }
87
88
89 // Functions from strbuf
90
91 int overflow(int c)
92 {
93 sync();
94 if (c != EOF)
95 {
96 *pptr() = c;
97 pbump(1);
98 }
99 return c;
100 }
101 int sync()
102 {
103 if (pptr() > pbase())
104 {
105 int amount = pptr() - pbase();
106 int res = ::write(m_fd, m_buf, amount);
107 if (res != amount)
108 throw wibble::exception::System("writing to file");
109 setp(m_buf, m_buf + m_buf_size);
110 }
111 return 0;
112 }
113};
114
115}
116}
117
118#endif
Exception thrown when some consistency check fails.
Definition exception.h:255
Base class for system exceptions.
Definition exception.h:397
Definition posix.h:16
int detach()
Sync the PosixBuf and detach it from the file descriptor.
Definition posix.h:71
int sync()
Definition posix.h:101
PosixBuf()
Definition posix.h:30
PosixBuf(int fd, size_t bufsize=4096)
Definition posix.h:31
~PosixBuf()
Definition posix.h:35
int overflow(int c)
Definition posix.h:91
int fd() const
Access the underlying file descriptor.
Definition posix.h:86
void attach(int fd, size_t bufsize=4096)
Attach the stream to a file descriptor, using the given stream size.
Definition posix.h:54
Definition amorph.h:17
Definition amorph.h:30