counted_array.hpp 2.3 KB

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