File: posix.h

package info (click to toggle)
libwibble 1.1-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 1,040 kB
  • ctags: 2,721
  • sloc: cpp: 14,542; makefile: 196; perl: 87; sh: 26
file content (118 lines) | stat: -rw-r--r-- 2,261 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#ifndef WIBBLE_STREAM_POSIX_H
#define WIBBLE_STREAM_POSIX_H

#include <wibble/exception.h>
#include <streambuf>
#include <unistd.h>
#include <cstdio>

// http://www.icce.rug.nl/documents/cplusplus/cplusplus21.html#CONCRETE
// 21.2.1: Classes for output operations

namespace wibble {
namespace stream {

class PosixBuf : public std::streambuf
{
private:
	// The output buffer
	char* m_buf;
	size_t m_buf_size;
	int m_fd;

	// Disallow copy
	PosixBuf(const PosixBuf&);
	PosixBuf& operator=(const PosixBuf&);

public:
	// PosixBuf functions

	PosixBuf() : m_buf(0), m_buf_size(0), m_fd(-1) {}
	PosixBuf(int fd, size_t bufsize = 4096) : m_buf(0), m_buf_size(0), m_fd(-1)
	{
		attach(fd, bufsize);
	}
	~PosixBuf()
	{
		if (m_buf)
		{
			sync();
			delete[] m_buf;
		}
		if (m_fd != -1)
		{
			::close(m_fd);
		}
	}

	/**
	 * Attach the stream to a file descriptor, using the given stream size.
	 *
	 * Management of the file descriptor will be taken over by the PosixBuf,
	 * and the file descriptor will be closed with PosixBuf goes out of scope.
	 */
	void attach(int fd, size_t bufsize = 4096)
	{
		m_buf = new char[1024];
		if (!m_buf)
			throw wibble::exception::Consistency("allocating 1024 bytes for posix stream buffer", "allocation failed");
		m_fd = fd;
		m_buf_size = 1024;
		setp(m_buf, m_buf + m_buf_size);
	}

	/**
	 * Sync the PosixBuf and detach it from the file descriptor.  PosixBuf will
	 * not touch the file descriptor anymore, and it is the responsibility of
	 * the caller to close it.
	 *
	 * @returns The file descriptor
	 */
	int detach()
	{
		sync();
		int res = m_fd;
		delete[] m_buf;
		m_buf = 0;
		m_buf_size = 0;
		m_fd = -1;
		// TODO: setp or anything like that, to tell the streambuf that there's
		// no buffer anymore?
		setp(0, 0);
		return res;
	}

	/// Access the underlying file descriptor
	int fd() const { return m_fd; }


	// Functions from strbuf

	int overflow(int c)
	{
		sync();
		if (c != EOF)
		{
			*pptr() = c;
			pbump(1);
		}
		return c;
	}
	int sync()
	{
		if (pptr() > pbase())
		{
			int amount = pptr() - pbase();
			int res = ::write(m_fd, m_buf, amount);
			if (res != amount)
				throw wibble::exception::System("writing to file");
			setp(m_buf, m_buf + m_buf_size);
		}
		return 0;
	}
}; 

}
}

#endif