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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
|
// file : CCF/CodeGenerationKit/IndentationImplanter.hpp
// author : Boris Kolpackov <boris@dre.vanderbilt.edu>
// cvs-id : $Id$
#ifndef CCF_CODE_GENERATION_KIT_INDENTATION_IMPLANTER
#define CCF_CODE_GENERATION_KIT_INDENTATION_IMPLANTER
#include <ostream>
#include "CCF/CodeGenerationKit/IndentationBuffer.hpp"
namespace Indentation
{
template <typename C>
class ToStreamBufAdapter : public std::basic_streambuf<C>
{
public:
typedef
typename std::basic_streambuf<C>::traits_type
traits_type;
typedef
typename std::basic_streambuf<C>::char_type
char_type;
typedef
typename std::basic_streambuf<C>::int_type
int_type;
public:
ToStreamBufAdapter (Buffer<C>& buffer)
: buffer_ (buffer)
{
}
virtual int_type
overflow (int_type c)
{
return buffer_.put (traits_type::to_char_type (c));
}
virtual int
sync ()
{
return 0;
}
private:
Buffer<C>& buffer_;
};
template <typename C>
class FromStreamBufAdapter : public Buffer<C>
{
public:
typedef
typename Buffer<C>::traits_type
traits_type;
typedef
typename Buffer<C>::char_type
char_type;
typedef
typename Buffer<C>::int_type
int_type;
typedef
typename Buffer<C>::Exception
Exception;
public:
FromStreamBufAdapter (std::basic_streambuf<C>& buffer)
: buffer_ (buffer)
{
}
virtual int_type
put (char_type c) throw (Exception, ExH::System::Exception)
{
return buffer_.sputc (traits_type::to_int_type (c));
}
virtual void
unbuffer () throw (ExH::System::Exception)
{
try
{
if (buffer_.pubsync () == 0) return;
}
catch (std::ios_base::failure const&)
{
}
throw Exception ("underlying std::streambuf::sync failed");
}
private:
std::basic_streambuf<C>& buffer_;
};
template <template <typename> class Buffer, typename C = char>
class Implanter
{
public:
Implanter (std::basic_ostream<C>& os)
: os_ (os),
prev_ (os_.rdbuf ()),
from_adapter_ (*prev_),
buffer_ (from_adapter_),
to_adapter_ (buffer_)
{
os_.rdbuf (&to_adapter_);
}
template <typename Arg0>
Implanter (std::basic_ostream<C>& os, Arg0 a0)
: os_ (os),
prev_ (os_.rdbuf ()),
from_adapter_ (*prev_),
buffer_ (from_adapter_, a0),
to_adapter_ (buffer_)
{
os_.rdbuf (&to_adapter_);
}
~Implanter ()
{
try
{
buffer_.unbuffer ();
}
catch (...)
{
// there is nothing I can do...
}
os_.rdbuf (prev_);
}
private:
std::basic_ostream<C>& os_;
std::basic_streambuf<C>* prev_;
FromStreamBufAdapter<C> from_adapter_;
Buffer<C> buffer_;
ToStreamBufAdapter<C> to_adapter_;
};
}
#endif // CCF_CODE_GENERATION_KIT_INDENTATION_IMPLANTER
|