1 /*
2  *          Copyright Andrey Semashev 2007 - 2015.
3  * Distributed under the Boost Software License, Version 1.0.
4  *    (See accompanying file LICENSE_1_0.txt or copy at
5  *          http://www.boost.org/LICENSE_1_0.txt)
6  */
7 /*!
8  * \file   format.hpp
9  * \author Andrey Semashev
10  * \date   15.11.2012
11  *
12  * \brief  This header is the Boost.Log library implementation, see the library documentation
13  *         at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
14  */
15 
16 #ifndef BOOST_LOG_DETAIL_FORMAT_HPP_INCLUDED_
17 #define BOOST_LOG_DETAIL_FORMAT_HPP_INCLUDED_
18 
19 #include <string>
20 #include <vector>
21 #include <iosfwd>
22 #include <boost/assert.hpp>
23 #include <boost/move/core.hpp>
24 #include <boost/move/utility.hpp>
25 #include <boost/log/detail/config.hpp>
26 #include <boost/log/detail/unhandled_exception_count.hpp>
27 #include <boost/log/detail/cleanup_scope_guard.hpp>
28 #include <boost/log/utility/formatting_ostream.hpp>
29 #include <boost/log/detail/header.hpp>
30 
31 #ifdef BOOST_HAS_PRAGMA_ONCE
32 #pragma once
33 #endif
34 
35 namespace boost {
36 
37 BOOST_LOG_OPEN_NAMESPACE
38 
39 namespace aux {
40 
41 //! An element (either literal or placeholder) of the format string
42 struct format_element
43 {
44     //! Argument placeholder number or -1 if it's not a placeholder (i.e. a literal)
45     int arg_number;
46     //! If the element describes a constant literal, the starting character and length of the literal
47     unsigned int literal_start_pos, literal_len;
48 
format_elementboost::aux::format_element49     format_element() : arg_number(0), literal_start_pos(0), literal_len(0)
50     {
51     }
52 
literalboost::aux::format_element53     static format_element literal(unsigned int start_pos, unsigned int len)
54     {
55         format_element el;
56         el.arg_number = -1;
57         el.literal_start_pos = start_pos;
58         el.literal_len = len;
59         return el;
60     }
61 
positional_argumentboost::aux::format_element62     static format_element positional_argument(unsigned int arg_n)
63     {
64         format_element el;
65         el.arg_number = arg_n;
66         return el;
67     }
68 };
69 
70 //! Parsed format string description
71 template< typename CharT >
72 struct format_description
73 {
74     BOOST_COPYABLE_AND_MOVABLE_ALT(format_description)
75 
76 public:
77     //! Character type
78     typedef CharT char_type;
79     //! String type
80     typedef std::basic_string< char_type > string_type;
81 
82     //! Array of format element descriptors
83     typedef std::vector< format_element > format_element_list;
84 
85     //! Characters of all literal parts of the format string
86     string_type literal_chars;
87     //! Format element descriptors
88     format_element_list format_elements;
89 
format_descriptionboost::aux::format_description90     BOOST_DEFAULTED_FUNCTION(format_description(), {})
91 
92     format_description(format_description const& that) : literal_chars(that.literal_chars), format_elements(that.format_elements)
93     {
94     }
95 
format_descriptionboost::aux::format_description96     format_description(BOOST_RV_REF(format_description) that)
97     {
98         literal_chars.swap(that.literal_chars);
99         format_elements.swap(that.format_elements);
100     }
101 
operator =boost::aux::format_description102     format_description& operator= (format_description that)
103     {
104         literal_chars.swap(that.literal_chars);
105         format_elements.swap(that.format_elements);
106         return *this;
107     }
108 };
109 
110 //! Parses format string
111 template< typename CharT >
112 BOOST_LOG_API format_description< CharT > parse_format(const CharT* begin, const CharT* end);
113 
114 //! Parses format string
115 template< typename CharT >
parse_format(const CharT * begin)116 BOOST_FORCEINLINE format_description< CharT > parse_format(const CharT* begin)
117 {
118     return parse_format(begin, begin + std::char_traits< CharT >::length(begin));
119 }
120 
121 //! Parses format string
122 template< typename CharT, typename TraitsT, typename AllocatorT >
parse_format(std::basic_string<CharT,TraitsT,AllocatorT> const & fmt)123 BOOST_FORCEINLINE format_description< CharT > parse_format(std::basic_string< CharT, TraitsT, AllocatorT > const& fmt)
124 {
125     const CharT* begin = fmt.c_str();
126     return parse_format(begin, begin + fmt.size());
127 }
128 
129 //! Formatter object
130 template< typename CharT >
131 class basic_format
132 {
133 public:
134     //! Character type
135     typedef CharT char_type;
136     //! String type
137     typedef std::basic_string< char_type > string_type;
138     //! Stream type
139     typedef basic_formatting_ostream< char_type > stream_type;
140     //! Format description type
141     typedef format_description< char_type > format_description_type;
142 
143     //! The pump receives arguments and formats them into strings. At destruction the pump composes the final string in the attached stream.
144     class pump;
145     friend class pump;
146 
147 private:
148     //! Formatting params for a single placeholder in the format string
149     struct formatting_params
150     {
151         //! Formatting element index in the format description
152         unsigned int element_idx;
153         //! Formatting result
154         string_type target;
155 
formatting_paramsboost::aux::basic_format::formatting_params156         formatting_params() : element_idx(~0u) {}
157     };
158     typedef std::vector< formatting_params > formatting_params_list;
159 
160 private:
161     //! Format string description
162     format_description_type m_format;
163     //! Formatting parameters for all placeholders
164     formatting_params_list m_formatting_params;
165     //! Current formatting position
166     unsigned int m_current_idx;
167 
168 public:
169     //! Initializing constructor
basic_format(string_type const & fmt)170     explicit basic_format(string_type const& fmt) : m_format(aux::parse_format(fmt)), m_current_idx(0)
171     {
172         init_params();
173     }
174     //! Initializing constructor
basic_format(const char_type * fmt)175     explicit basic_format(const char_type* fmt) : m_format(aux::parse_format(fmt)), m_current_idx(0)
176     {
177         init_params();
178     }
179 
180     //! Clears all formatted strings and resets the current formatting position
clear()181     void clear() BOOST_NOEXCEPT
182     {
183         for (typename formatting_params_list::iterator it = m_formatting_params.begin(), end = m_formatting_params.end(); it != end; ++it)
184         {
185             it->target.clear();
186         }
187         m_current_idx = 0;
188     }
189 
190     //! Creates a pump that will receive all format arguments and put the formatted string into the stream
make_pump(stream_type & strm)191     pump make_pump(stream_type& strm) BOOST_NOEXCEPT
192     {
193         return pump(*this, strm);
194     }
195 
196     //! Composes the final string from the formatted pieces
compose(string_type & str) const197     void compose(string_type& str) const
198     {
199         typename format_description_type::format_element_list::const_iterator it = m_format.format_elements.begin(), end = m_format.format_elements.end();
200         for (; it != end; ++it)
201         {
202             if (it->arg_number >= 0)
203             {
204                 // This is a placeholder
205                 str.append(m_formatting_params[it->arg_number].target);
206             }
207             else
208             {
209                 // This is a literal
210                 const char_type* p = m_format.literal_chars.c_str() + it->literal_start_pos;
211                 str.append(p, it->literal_len);
212             }
213         }
214     }
215 
216     //! Composes the final string from the formatted pieces
str() const217     string_type str() const
218     {
219         string_type result;
220         compose(result);
221         return boost::move(result);
222     }
223 
224 private:
225     //! Initializes the formatting params
init_params()226     void init_params()
227     {
228         typename format_description_type::format_element_list::const_iterator it = m_format.format_elements.begin(), end = m_format.format_elements.end();
229         for (; it != end; ++it)
230         {
231             if (it->arg_number >= 0)
232             {
233                 if (static_cast< unsigned int >(it->arg_number) >= m_formatting_params.size())
234                     m_formatting_params.resize(it->arg_number + 1);
235                 m_formatting_params[it->arg_number].element_idx = static_cast< unsigned int >(it - m_format.format_elements.begin());
236             }
237         }
238     }
239 };
240 
241 //! The pump receives arguments and formats them into strings. At destruction the pump composes the final string in the attached stream.
242 template< typename CharT >
243 class basic_format< CharT >::pump
244 {
245     BOOST_MOVABLE_BUT_NOT_COPYABLE(pump)
246 
247 private:
248     //! The guard temporarily replaces storage string in the specified stream
249     struct scoped_storage
250     {
scoped_storageboost::aux::basic_format::pump::scoped_storage251         scoped_storage(stream_type& strm, string_type& storage) : m_stream(strm), m_storage_backup(*strm.rdbuf()->storage())
252         {
253             strm.attach(storage);
254         }
~scoped_storageboost::aux::basic_format::pump::scoped_storage255         ~scoped_storage()
256         {
257             m_stream.attach(m_storage_backup);
258         }
259 
260     private:
261         stream_type& m_stream;
262         string_type& m_storage_backup;
263     };
264 
265 private:
266     //! Reference to the owner
267     basic_format* m_owner;
268     //! Reference to the stream
269     stream_type* m_stream;
270     //! Unhandled exception count
271     const unsigned int m_exception_count;
272 
273 public:
274     //! Initializing constructor
pump(basic_format & owner,stream_type & strm)275     pump(basic_format& owner, stream_type& strm) BOOST_NOEXCEPT : m_owner(&owner), m_stream(&strm), m_exception_count(unhandled_exception_count())
276     {
277     }
278 
279     //! Move constructor
pump(BOOST_RV_REF (pump)that)280     pump(BOOST_RV_REF(pump) that) BOOST_NOEXCEPT : m_owner(that.m_owner), m_stream(that.m_stream), m_exception_count(that.m_exception_count)
281     {
282         that.m_owner = NULL;
283         that.m_stream = NULL;
284     }
285 
286     //! Destructor
BOOST_NOEXCEPT_IF(false)287     ~pump() BOOST_NOEXCEPT_IF(false)
288     {
289         if (m_owner)
290         {
291             // Whether or not the destructor is called because of an exception, the format object has to be cleared
292             boost::log::aux::cleanup_guard< basic_format< char_type > > cleanup1(*m_owner);
293 
294             BOOST_ASSERT(m_stream != NULL);
295             if (m_exception_count >= unhandled_exception_count())
296             {
297                 // Compose the final string in the stream buffer
298                 m_stream->flush();
299                 m_owner->compose(*m_stream->rdbuf()->storage());
300             }
301         }
302     }
303 
304     /*!
305      * Puts an argument to the formatter. Note the pump has to be returned by value and not by reference in order this to
306      * work with Boost.Phoenix expressions. Otherwise the pump that is returned from \c basic_format::make_pump is
307      * destroyed after the first call to \c operator%, and the returned reference becomes dangling.
308      */
309     template< typename T >
operator %(T const & val)310     pump operator% (T const& val)
311     {
312         BOOST_ASSERT_MSG(m_owner != NULL && m_stream != NULL, "Boost.Log: This basic_format::pump has already been moved from");
313 
314         if (m_owner->m_current_idx < m_owner->m_formatting_params.size())
315         {
316             scoped_storage storage_guard(*m_stream, m_owner->m_formatting_params[m_owner->m_current_idx].target);
317 
318             *m_stream << val;
319             m_stream->flush();
320 
321             ++m_owner->m_current_idx;
322         }
323 
324         return boost::move(*this);
325     }
326 };
327 
328 } // namespace aux
329 
330 BOOST_LOG_CLOSE_NAMESPACE // namespace log
331 
332 } // namespace boost
333 
334 #include <boost/log/detail/footer.hpp>
335 
336 #endif // BOOST_LOG_DETAIL_FORMAT_HPP_INCLUDED_
337