blob: 4780c16169c8933c934ccc33c7b759acb6918b59 [file] [log] [blame]
Jeff Thompson86b6d642013-10-17 15:01:56 -07001// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
2// (C) Copyright 2005-2007 Jonathan Turkanis
3// Distributed under the Boost Software License, Version 1.0. (See accompanying
4// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
5
6// See http://www.boost.org/libs/iostreams for documentation.
7
8#ifndef NDNBOOST_IOSTREAMS_COUNTER_HPP_INCLUDED
9#define NDNBOOST_IOSTREAMS_COUNTER_HPP_INCLUDED
10
11#if defined(_MSC_VER) && (_MSC_VER >= 1020)
12# pragma once
13#endif
14
15#include <algorithm> // count.
16#include <ndnboost/iostreams/categories.hpp>
17#include <ndnboost/iostreams/char_traits.hpp>
18#include <ndnboost/iostreams/operations.hpp>
19#include <ndnboost/iostreams/pipeline.hpp>
20
21// Must come last.
22#include <ndnboost/iostreams/detail/config/disable_warnings.hpp> // VC7.1 C4244.
23
24namespace ndnboost { namespace iostreams {
25
26//
27// Template name: basic_counter.
28// Template parameters:
29// Ch - The character type.
30// Description: Filter which counts lines and characters.
31//
32template<typename Ch>
33class basic_counter {
34public:
35 typedef Ch char_type;
36 struct category
37 : dual_use,
38 filter_tag,
39 multichar_tag,
40 optimally_buffered_tag
41 { };
42 explicit basic_counter(int first_line = 0, int first_char = 0)
43 : lines_(first_line), chars_(first_char)
44 { }
45 int lines() const { return lines_; }
46 int characters() const { return chars_; }
47 std::streamsize optimal_buffer_size() const { return 0; }
48
49 template<typename Source>
50 std::streamsize read(Source& src, char_type* s, std::streamsize n)
51 {
52 std::streamsize result = iostreams::read(src, s, n);
53 if (result == -1)
54 return -1;
55 lines_ += std::count(s, s + result, char_traits<Ch>::newline());
56 chars_ += result;
57 return result;
58 }
59
60 template<typename Sink>
61 std::streamsize write(Sink& snk, const char_type* s, std::streamsize n)
62 {
63 std::streamsize result = iostreams::write(snk, s, n);
64 lines_ += std::count(s, s + result, char_traits<Ch>::newline());
65 chars_ += result;
66 return result;
67 }
68private:
69 int lines_;
70 int chars_;
71};
72NDNBOOST_IOSTREAMS_PIPABLE(basic_counter, 1)
73
74
75typedef basic_counter<char> counter;
76typedef basic_counter<wchar_t> wcounter;
77
78} } // End namespaces iostreams, boost.
79
80#include <ndnboost/iostreams/detail/config/enable_warnings.hpp>
81
82#endif // #ifndef NDNBOOST_IOSTREAMS_COUNTER_HPP_INCLUDED