My Project  + 80db3
restrict.hpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2013-2019 Daniel Scharrer
3  *
4  * This software is provided 'as-is', without any express or implied
5  * warranty. In no event will the author(s) be held liable for any damages
6  * arising from the use of this software.
7  *
8  * Permission is granted to anyone to use this software for any purpose,
9  * including commercial applications, and to alter it and redistribute it
10  * freely, subject to the following restrictions:
11  *
12  * 1. The origin of this software must not be misrepresented; you must not
13  * claim that you wrote the original software. If you use this software
14  * in a product, an acknowledgment in the product documentation would be
15  * appreciated but is not required.
16  * 2. Altered source versions must be plainly marked as such, and must not be
17  * misrepresented as being the original software.
18  * 3. This notice may not be removed or altered from any source distribution.
19  */
20 
27 #ifndef INNOEXTRACT_STREAM_RESTRICT_HPP
28 #define INNOEXTRACT_STREAM_RESTRICT_HPP
29 
30 #include <boost/cstdint.hpp>
31 #include <boost/iostreams/concepts.hpp>
32 #include <boost/iostreams/read.hpp>
33 
34 namespace stream {
35 
37 template <typename BaseSource>
38 class restricted_source : public boost::iostreams::source {
39 
40  BaseSource & base;
41  boost::uint64_t remaining;
42 
43 public:
44 
46  : base(o.base), remaining(o.remaining) { }
47 
48  restricted_source(BaseSource & source, boost::uint64_t size)
49  : base(source), remaining(size) { }
50 
51  std::streamsize read(char * buffer, std::streamsize bytes) {
52 
53  if(bytes <= 0) {
54  return 0;
55  }
56 
57  // Restrict the number of bytes to read
58  bytes = std::streamsize(std::min(boost::uint64_t(bytes), remaining));
59  if(bytes == 0) {
60  return -1; // End of the restricted source reached
61  }
62 
63  std::streamsize nread = boost::iostreams::read(base, buffer, bytes);
64 
65  // Remember how many bytes were read so far
66  if(nread > 0) {
67  remaining -= std::min(boost::uint64_t(nread), remaining);
68  }
69 
70  return nread;
71  }
72 
73 };
74 
81 template <typename BaseSource>
82 restricted_source<BaseSource> restrict(BaseSource & source, boost::uint64_t size) {
83  return restricted_source<BaseSource>(source, size);
84 }
85 
86 } // namespace stream
87 
88 #endif // INNOEXTRACT_STREAM_RESTRICT_HPP
std::streamsize read(char *buffer, std::streamsize bytes)
Definition: restrict.hpp:51
restricted_source< BaseSource > restrict(BaseSource &source, boost::uint64_t size)
Restricts a source to a specific size from the current position and makes it non-seekable.
Definition: restrict.hpp:82
restricted_source(const restricted_source &o)
Definition: restrict.hpp:45
Definition: block.cpp:49
restricted_source(BaseSource &source, boost::uint64_t size)
Definition: restrict.hpp:48
Like boost::iostreams::restriction, but always has a 64-bit counter.
Definition: restrict.hpp:38