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 
6 // See http://www.boost.org/libs/iostreams for documentation.
7 
8 #ifndef BOOST_IOSTREAMS_DETAIL_COUNTED_ARRAY_HPP_INCLUDED
9 #define BOOST_IOSTREAMS_DETAIL_COUNTED_ARRAY_HPP_INCLUDED
10 
11 #include <algorithm>                               // min.
12 #include <cstddef>                                 // size_t
13 #include <string>                                  // char_traits
14 #include <boost/iostreams/categories.hpp>
15 #include <boost/iostreams/detail/char_traits.hpp>
16 #include <boost/iostreams/detail/ios.hpp>          // streamsize.
17 
18 namespace boost { namespace iostreams { namespace detail {
19 
20 template<typename Ch>
21 class counted_array_source {
22 public:
23     typedef Ch          char_type;
24     typedef source_tag  category;
counted_array_source(const Ch * buf,std::streamsize size)25     counted_array_source(const Ch* buf, std::streamsize size)
26         : buf_(buf), ptr_(0), end_(size)
27         { }
read(Ch * s,std::streamsize n)28     std::streamsize read(Ch* s, std::streamsize n)
29     {
30         using namespace std;
31         streamsize result = (std::min)(n, end_ - ptr_);
32         char_traits<char_type>::copy(
33             s,
34             buf_ + ptr_,
35             static_cast<size_t>(result)
36         );
37         ptr_ += result;
38         return result;
39     }
count() const40     std::streamsize count() const { return ptr_; }
41 private:
42     const Ch*        buf_;
43     std::streamsize  ptr_, end_;
44 };
45 
46 template<typename Ch>
47 struct counted_array_sink {
48 public:
49     typedef Ch        char_type;
50     typedef sink_tag  category;
counted_array_sinkboost::iostreams::detail::counted_array_sink51     counted_array_sink(Ch* buf, std::streamsize size)
52         : buf_(buf), ptr_(0), end_(size)
53         { }
writeboost::iostreams::detail::counted_array_sink54         std::streamsize write(const Ch* s, std::streamsize n)
55     {
56         using namespace std;
57         std::streamsize result = (std::min)(n, end_ - ptr_);
58         char_traits<char_type>::copy(
59             buf_ + ptr_,
60             s,
61             static_cast<size_t>(result)
62         );
63         ptr_ += result;
64         return result;
65     }
countboost::iostreams::detail::counted_array_sink66     std::streamsize count() const { return ptr_; }
67 private:
68     Ch*              buf_;
69     std::streamsize  ptr_, end_;
70 };
71 
72 } } } // End namespaces iostreams, boost.
73 
74 #endif // #ifndef BOOST_IOSTREAMS_DETAIL_COUNTED_ARRAY_HPP_INCLUDED
75