1 // Copyright 2010 Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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.
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.
29 #include "utils/format/formatter.hpp"
35 #include "utils/format/exceptions.hpp"
36 #include "utils/sanity.hpp"
37 #include "utils/text/exceptions.hpp"
38 #include "utils/text/operations.ipp"
40 namespace format
= utils::format
;
41 namespace text
= utils::text
;
47 /// Finds the next placeholder in a string.
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
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.
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
)
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 %");
77 std::string::size_type end
= begin
+ 1;
78 while (end
< expansion
.length() && expansion
[end
] != 's')
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 '" +
85 return std::make_pair(begin
, placeholder
);
89 /// Converts a string to an integer.
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.
96 /// \return An integer representing the input string.
98 to_int(const std::string
& format
, const std::string
& str
, const char* what
)
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
) +
109 /// Constructs an std::ostringstream based on a formatting placeholder.
111 /// \param format The format placeholder; may be empty.
113 /// \return A new std::ostringstream that is prepared to format a single
114 /// object in the manner specified by the format placeholder.
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
)
121 std::auto_ptr
< std::ostringstream
> output(new std::ostringstream());
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.
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
132 std::string partial
= format
.substr(1, format
.length() - 2);
133 if (partial
[0] == '0') {
137 if (!partial
.empty()) {
138 const std::string::size_type dot
= partial
.find('.');
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),
149 return output
.release();
153 /// Replaces '%%' by '%' in a given string range.
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.
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
)
164 std::string part
= in
.substr(begin
, end
- begin
);
167 std::string::size_type pos
= part
.find("%%");
168 while (pos
!= std::string::npos
) {
171 pos
= part
.find("%%", pos
+ 1);
174 return std::make_pair(in
.substr(0, begin
) + part
+ in
.substr(end
), removed
);
178 } // anonymous namespace
181 /// Performs internal initialization of the formatter.
183 /// This is separate from the constructor just because it is shared by different
184 /// overloaded constructors.
186 format::formatter::init(void)
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
);
193 _oss
= new_ostringstream(placeholder
.second
);
195 _expansion
= no_percents
.first
;
196 _placeholder_pos
= placeholder
.first
- no_percents
.second
;
197 _placeholder
= placeholder
.second
;
201 /// Constructs a new formatter object (internal).
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
) :
213 _expansion(expansion
),
221 /// Constructs a new formatter object.
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
) :
236 format::formatter::~formatter(void)
242 /// Returns the formatted string.
244 format::formatter::str(void) const
250 /// Automatic conversion of formatter objects to strings.
252 /// This is provided to allow painless injection of formatter objects into
253 /// streams, without having to manually call the str() method.
254 format::formatter::operator const std::string
&(void) const
260 /// Specialization of operator% for booleans.
262 /// \param value The boolean to inject into the format string.
264 /// \return A new formatter that has one less format placeholder.
266 format::formatter::operator%(const bool& value
) const
268 (*_oss
) << (value
? "true" : "false");
269 return replace(_oss
->str());
273 /// Replaces the first formatting placeholder with a value.
275 /// \param arg The replacement string.
277 /// \return A new formatter in which the first formatting placeholder has been
278 /// replaced by arg and is ready to replace the next item.
280 /// \throw utils::format::extra_args_error If there are no more formatting
281 /// placeholders in the input string, or if the placeholder is invalid.
283 format::formatter::replace(const std::string
& arg
) const
285 if (_placeholder_pos
== _expansion
.length())
286 throw format::extra_args_error(_format
, arg
);
288 const std::string expansion
= _expansion
.substr(0, _placeholder_pos
)
289 + arg
+ _expansion
.substr(_placeholder_pos
+ _placeholder
.length());
290 return formatter(_format
, expansion
, _placeholder_pos
+ arg
.length());