counter.hpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // (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. // See http://www.boost.org/libs/iostreams for documentation.
  6. #ifndef BOOST_IOSTREAMS_COUNTER_HPP_INCLUDED
  7. #define BOOST_IOSTREAMS_COUNTER_HPP_INCLUDED
  8. #if defined(_MSC_VER)
  9. # pragma once
  10. #endif
  11. #include <algorithm> // count.
  12. #include <boost/iostreams/categories.hpp>
  13. #include <boost/iostreams/char_traits.hpp>
  14. #include <boost/iostreams/operations.hpp>
  15. #include <boost/iostreams/pipeline.hpp>
  16. // Must come last.
  17. #include <boost/iostreams/detail/config/disable_warnings.hpp> // VC7.1 C4244.
  18. namespace boost { namespace iostreams {
  19. //
  20. // Template name: basic_counter.
  21. // Template parameters:
  22. // Ch - The character type.
  23. // Description: Filter which counts lines and characters.
  24. //
  25. template<typename Ch>
  26. class basic_counter {
  27. public:
  28. typedef Ch char_type;
  29. struct category
  30. : dual_use,
  31. filter_tag,
  32. multichar_tag,
  33. optimally_buffered_tag
  34. { };
  35. explicit basic_counter(int first_line = 0, int first_char = 0)
  36. : lines_(first_line), chars_(first_char)
  37. { }
  38. int lines() const { return lines_; }
  39. int characters() const { return chars_; }
  40. std::streamsize optimal_buffer_size() const { return 0; }
  41. template<typename Source>
  42. std::streamsize read(Source& src, char_type* s, std::streamsize n)
  43. {
  44. std::streamsize result = iostreams::read(src, s, n);
  45. if (result == -1)
  46. return -1;
  47. lines_ += std::count(s, s + result, char_traits<Ch>::newline());
  48. chars_ += result;
  49. return result;
  50. }
  51. template<typename Sink>
  52. std::streamsize write(Sink& snk, const char_type* s, std::streamsize n)
  53. {
  54. std::streamsize result = iostreams::write(snk, s, n);
  55. lines_ += std::count(s, s + result, char_traits<Ch>::newline());
  56. chars_ += result;
  57. return result;
  58. }
  59. private:
  60. int lines_;
  61. int chars_;
  62. };
  63. BOOST_IOSTREAMS_PIPABLE(basic_counter, 1)
  64. typedef basic_counter<char> counter;
  65. typedef basic_counter<wchar_t> wcounter;
  66. } } // End namespaces iostreams, boost.
  67. #include <boost/iostreams/detail/config/enable_warnings.hpp>
  68. #endif // #ifndef BOOST_IOSTREAMS_COUNTER_HPP_INCLUDED