Debian Codegraph @

yo/concrete/streambuf/fdstreambuf/fdstreambuf.h

raw
1 #include <unistd.h>
2 #include <streambuf>
3 #include <ios>
4 #include <algorithm>
5
6 using namespace std;
7
8 class fdstreambuf: public std::streambuf
9 {
10 public:
11 fdstreambuf(int fd, size_t bufsize, size_t minimum,
12 std::ios::openmode mode = std::ios::in | std::ios::out)
13 :
14 fd(fd),
15 bufsize(bufsize),
16 minimum(minimum),
17 buffer(new char[bufsize])
18 {
19 /*
20 initialize buffer from minimum position to beyond, set
21 gptr() to beyond, so the buffer is filled immediately
22
23 Assume bufsize - minimum > minimum
24 */
25 if (mode & std::ios::in)
26 setg(buffer + minimum, buffer + bufsize, buffer + bufsize);
27 }
28
29 ~fdstreambuf()
30 {
31 delete buffer;
32 }
33
34 int underflow() // inspects the character
35 {
36 if (gptr() < egptr())
37 return static_cast<unsigned char>(*gptr());
38 // return next char waiting in the buffer
39
40 /*
41 Now that the buffer is refilled, what do we have?
42 buffer eback() gptr() == egptr()
43 ^ ^ ^
44 -------------------------------
45 n m <= bufsize - minimum
46
47 n characters at chars before gptr() are moved left,
48 eback() is moved left over n
49 filling starts are buffer + minimum
50 */
51
52 size_t
53 n2move = min(minimum, (size_t)(gptr() - eback()));
54
55 memcpy(buffer, egptr() - n2move, n2move);
56
57 /*
58 Read chars to the area beyond the unget-buffer
59 */
60 int
61 nread = read(fd, buffer + minimum, bufsize - minimum);
62
63 if (nread <= 0) // none read ->
64 return EOF;
65
66 setg(buffer + minimum - n2move,
67 buffer + minimum,
68 buffer + minimum + nread);
69
70 return static_cast<unsigned char>(*gptr());
71 }
72
73 private:
74 int fd;
75 size_t bufsize;
76 size_t minimum;
77 char* buffer;
78 };