xref: /freebsd/contrib/kyua/utils/format/formatter.cpp (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1 // Copyright 2010 The Kyua Authors.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 //   notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright
11 //   notice, this list of conditions and the following disclaimer in the
12 //   documentation and/or other materials provided with the distribution.
13 // * Neither the name of Google Inc. nor the names of its contributors
14 //   may be used to endorse or promote products derived from this software
15 //   without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 
29 #include "utils/format/formatter.hpp"
30 
31 #include <memory>
32 #include <string>
33 #include <utility>
34 
35 #include "utils/format/exceptions.hpp"
36 #include "utils/sanity.hpp"
37 #include "utils/text/exceptions.hpp"
38 #include "utils/text/operations.ipp"
39 
40 namespace format = utils::format;
41 namespace text = utils::text;
42 
43 
44 namespace {
45 
46 
47 /// Finds the next placeholder in a string.
48 ///
49 /// \param format The original format string provided by the user; needed for
50 ///     error reporting purposes only.
51 /// \param expansion The string containing the placeholder to look for.  Any
52 ///     '%%' in the string will be skipped, and they must be stripped later by
53 ///     strip_double_percent().
54 /// \param begin The position from which to start looking for the next
55 ///     placeholder.
56 ///
57 /// \return The position in the string in which the placeholder is located and
58 /// the placeholder itself.  If there are no placeholders left, this returns
59 /// the length of the string and an empty string.
60 ///
61 /// \throw bad_format_error If the input string contains a trailing formatting
62 ///     character.  We cannot detect any other kind of invalid formatter because
63 ///     we do not implement a full parser for them.
64 static std::pair< std::string::size_type, std::string >
65 find_next_placeholder(const std::string& format,
66                       const std::string& expansion,
67                       std::string::size_type begin)
68 {
69     begin = expansion.find('%', begin);
70     while (begin != std::string::npos && expansion[begin + 1] == '%')
71         begin = expansion.find('%', begin + 2);
72     if (begin == std::string::npos)
73         return std::make_pair(expansion.length(), "");
74     if (begin == expansion.length() - 1)
75         throw format::bad_format_error(format, "Trailing %");
76 
77     std::string::size_type end = begin + 1;
78     while (end < expansion.length() && expansion[end] != 's')
79         end++;
80     const std::string placeholder = expansion.substr(begin, end - begin + 1);
81     if (end == expansion.length() ||
82         placeholder.find('%', 1) != std::string::npos)
83         throw format::bad_format_error(format, "Unterminated placeholder '" +
84                                        placeholder + "'");
85     return std::make_pair(begin, placeholder);
86 }
87 
88 
89 /// Converts a string to an integer.
90 ///
91 /// \param format The format string; for error reporting purposes only.
92 /// \param str The string to conver.
93 /// \param what The name of the field this integer belongs to; for error
94 ///     reporting purposes only.
95 ///
96 /// \return An integer representing the input string.
97 inline int
98 to_int(const std::string& format, const std::string& str, const char* what)
99 {
100     try {
101         return text::to_type< int >(str);
102     } catch (const text::value_error& e) {
103         throw format::bad_format_error(format, "Invalid " + std::string(what) +
104                                        "specifier");
105     }
106 }
107 
108 
109 /// Constructs an std::ostringstream based on a formatting placeholder.
110 ///
111 /// \param format The format placeholder; may be empty.
112 ///
113 /// \return A new std::ostringstream that is prepared to format a single
114 /// object in the manner specified by the format placeholder.
115 ///
116 /// \throw bad_format_error If the format string is bad.  We do minimal
117 ///     validation on this string though.
118 static std::ostringstream*
119 new_ostringstream(const std::string& format)
120 {
121     std::auto_ptr< std::ostringstream > output(new std::ostringstream());
122 
123     if (format.length() <= 2) {
124         // If the format is empty, we create a new stream so that we don't have
125         // to check for NULLs later on.  We rarely should hit this condition
126         // (and when we do it's a bug in the caller), so this is not a big deal.
127         //
128         // Otherwise, if the format is a regular '%s', then we don't have to do
129         // any processing for additional formatters.  So this is just a "fast
130         // path".
131     } else {
132         std::string partial = format.substr(1, format.length() - 2);
133         if (partial[0] == '0') {
134             output->fill('0');
135             partial.erase(0, 1);
136         }
137         if (!partial.empty()) {
138             const std::string::size_type dot = partial.find('.');
139             if (dot != 0)
140                 output->width(to_int(format, partial.substr(0, dot), "width"));
141             if (dot != std::string::npos) {
142                 output->setf(std::ios::fixed, std::ios::floatfield);
143                 output->precision(to_int(format, partial.substr(dot + 1),
144                                          "precision"));
145             }
146         }
147     }
148 
149     return output.release();
150 }
151 
152 
153 /// Replaces '%%' by '%' in a given string range.
154 ///
155 /// \param in The input string to be rewritten.
156 /// \param begin The position at which to start the replacement.
157 /// \param end The position at which to end the replacement.
158 ///
159 /// \return The modified string and the amount of characters removed.
160 static std::pair< std::string, int >
161 strip_double_percent(const std::string& in, const std::string::size_type begin,
162                      std::string::size_type end)
163 {
164     std::string part = in.substr(begin, end - begin);
165 
166     int removed = 0;
167     std::string::size_type pos = part.find("%%");
168     while (pos != std::string::npos) {
169         part.erase(pos, 1);
170         ++removed;
171         pos = part.find("%%", pos + 1);
172     }
173 
174     return std::make_pair(in.substr(0, begin) + part + in.substr(end), removed);
175 }
176 
177 
178 }  // anonymous namespace
179 
180 
181 /// Performs internal initialization of the formatter.
182 ///
183 /// This is separate from the constructor just because it is shared by different
184 /// overloaded constructors.
185 void
186 format::formatter::init(void)
187 {
188     const std::pair< std::string::size_type, std::string > placeholder =
189         find_next_placeholder(_format, _expansion, _last_pos);
190     const std::pair< std::string, int > no_percents =
191         strip_double_percent(_expansion, _last_pos, placeholder.first);
192 
193     _oss = new_ostringstream(placeholder.second);
194 
195     _expansion = no_percents.first;
196     _placeholder_pos = placeholder.first - no_percents.second;
197     _placeholder = placeholder.second;
198 }
199 
200 
201 /// Constructs a new formatter object (internal).
202 ///
203 /// \param format The format string.
204 /// \param expansion The format string with any replacements performed so far.
205 /// \param last_pos The position from which to start looking for formatting
206 ///     placeholders.  This must be maintained in case one of the replacements
207 ///     introduced a new placeholder, which must be ignored.  Think, for
208 ///     example, replacing a "%s" string with "foo %s".
209 format::formatter::formatter(const std::string& format,
210                              const std::string& expansion,
211                              const std::string::size_type last_pos) :
212     _format(format),
213     _expansion(expansion),
214     _last_pos(last_pos),
215     _oss(NULL)
216 {
217     init();
218 }
219 
220 
221 /// Constructs a new formatter object.
222 ///
223 /// \param format The format string.  The formatters in the string are not
224 ///     validated during construction, but will cause errors when used later if
225 ///     they are invalid.
226 format::formatter::formatter(const std::string& format) :
227     _format(format),
228     _expansion(format),
229     _last_pos(0),
230     _oss(NULL)
231 {
232     init();
233 }
234 
235 
236 format::formatter::~formatter(void)
237 {
238     delete _oss;
239 }
240 
241 
242 /// Returns the formatted string.
243 ///
244 /// \return A string representation of the formatted string.
245 const std::string&
246 format::formatter::str(void) const
247 {
248     return _expansion;
249 }
250 
251 
252 /// Automatic conversion of formatter objects to strings.
253 ///
254 /// This is provided to allow painless injection of formatter objects into
255 /// streams, without having to manually call the str() method.
256 format::formatter::operator const std::string&(void) const
257 {
258     return _expansion;
259 }
260 
261 
262 /// Specialization of operator% for booleans.
263 ///
264 /// \param value The boolean to inject into the format string.
265 ///
266 /// \return A new formatter that has one less format placeholder.
267 format::formatter
268 format::formatter::operator%(const bool& value) const
269 {
270     (*_oss) << (value ? "true" : "false");
271     return replace(_oss->str());
272 }
273 
274 
275 /// Replaces the first formatting placeholder with a value.
276 ///
277 /// \param arg The replacement string.
278 ///
279 /// \return A new formatter in which the first formatting placeholder has been
280 ///     replaced by arg and is ready to replace the next item.
281 ///
282 /// \throw utils::format::extra_args_error If there are no more formatting
283 ///     placeholders in the input string, or if the placeholder is invalid.
284 format::formatter
285 format::formatter::replace(const std::string& arg) const
286 {
287     if (_placeholder_pos == _expansion.length())
288         throw format::extra_args_error(_format, arg);
289 
290     const std::string expansion = _expansion.substr(0, _placeholder_pos)
291         + arg + _expansion.substr(_placeholder_pos + _placeholder.length());
292     return formatter(_format, expansion, _placeholder_pos + arg.length());
293 }
294