counted_array.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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_DETAIL_COUNTED_ARRAY_HPP_INCLUDED
  7. #define BOOST_IOSTREAMS_DETAIL_COUNTED_ARRAY_HPP_INCLUDED
  8. #include <algorithm> // min.
  9. #include <boost/iostreams/categories.hpp>
  10. #include <boost/iostreams/detail/char_traits.hpp>
  11. #include <boost/iostreams/detail/ios.hpp> // streamsize.
  12. namespace boost { namespace iostreams { namespace detail {
  13. template<typename Ch>
  14. class counted_array_source {
  15. public:
  16. typedef Ch char_type;
  17. typedef source_tag category;
  18. counted_array_source(const Ch* buf, std::streamsize size)
  19. : buf_(buf), ptr_(0), end_(size)
  20. { }
  21. std::streamsize read(Ch* s, std::streamsize n)
  22. {
  23. std::streamsize result = (std::min)(n, end_ - ptr_);
  24. BOOST_IOSTREAMS_CHAR_TRAITS(char_type)::copy
  25. (s, buf_ + ptr_, result);
  26. ptr_ += result;
  27. return result;
  28. }
  29. std::streamsize count() const { return ptr_; }
  30. private:
  31. const Ch* buf_;
  32. std::streamsize ptr_, end_;
  33. };
  34. template<typename Ch>
  35. struct counted_array_sink {
  36. public:
  37. typedef Ch char_type;
  38. typedef sink_tag category;
  39. counted_array_sink(Ch* buf, std::streamsize size)
  40. : buf_(buf), ptr_(0), end_(size)
  41. { }
  42. std::streamsize write(const Ch* s, std::streamsize n)
  43. {
  44. std::streamsize result = (std::min)(n, end_ - ptr_);
  45. BOOST_IOSTREAMS_CHAR_TRAITS(char_type)::copy
  46. (buf_ + ptr_, s, result);
  47. ptr_ += result;
  48. return result;
  49. }
  50. std::streamsize count() const { return ptr_; }
  51. private:
  52. Ch* buf_;
  53. std::streamsize ptr_, end_;
  54. };
  55. } } } // End namespaces iostreams, boost.
  56. #endif // #ifndef BOOST_IOSTREAMS_DETAIL_COUNTED_ARRAY_HPP_INCLUDED