tudocomp
– The TU Dortmund Compression Framework
ViewStream.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <iostream>
4 #include <memory>
5 #include <utility>
6 #include <streambuf>
7 
8 namespace tdc {
9 namespace io {
10 
12 
13 class ViewStream {
14  struct membuf: public std::streambuf {
15  inline membuf(char* begin, size_t size) {
16  setg(begin, begin, begin + size);
17  }
18 
19  // TODO: Figure out if there are actual ways to move the streambuf
20  // even under older compiler versions.
21 
22  inline membuf(const membuf& other):
23  membuf(other.eback(), other.egptr() - other.eback()) {}
24 
25  inline membuf(membuf&& other):
26  membuf(other.eback(), other.egptr() - other.eback()) {}
27 
28  virtual inline std::streampos seekpos(std::streampos sp,
29  std::ios_base::openmode which) override
30  {
31  DCHECK(which == (std::ios_base::in | std::ios_base::out));
32 
33  auto begin = eback();
34  auto end = egptr();
35  if ((size_t(begin) + sp) > size_t(end)) {
36  return std::streampos(std::streamoff(-1));
37  }
38  auto current = begin + sp;
39  setg(begin, current, end);
40  return sp;
41  }
42 
43  virtual inline std::streampos seekoff(std::streamoff off,
44  std::ios_base::seekdir way,
45  std::ios_base::openmode which) override
46  {
47  auto begin = eback();
48  auto current = gptr();
49  auto end = egptr();
50  auto size = end - begin;
51 
52  std::streampos abs_pos = current - begin;
53 
54  if (way == std::ios_base::beg) {
55  abs_pos = off;
56  } else if (way == std::ios_base::cur) {
57  abs_pos += off;
58  } else /* way == std::ios_base::end */ {
59  abs_pos = size - off;
60  }
61  return seekpos(abs_pos, which);
62  }
63 
64  };
65 
66  char* m_begin;
67  size_t m_size;
68  std::unique_ptr<membuf> m_mb;
69  std::unique_ptr<std::istream> m_stream;
70 
71 public:
72  inline ViewStream(char* begin, size_t size):
73  m_begin(begin),
74  m_size(size),
75  m_mb(std::make_unique<membuf>(membuf { begin, size })),
76  m_stream(std::unique_ptr<std::istream>(new std::istream(&*m_mb))) {}
77 
78  inline ViewStream(View view): ViewStream((char*) view.data(), view.size()) {}
79 
80  inline ViewStream(const ViewStream& other):
81  ViewStream(other.m_begin, other.m_size) {}
82 
83  inline ViewStream(ViewStream&& other):
84  m_begin(other.m_begin),
85  m_size(other.m_size),
86  m_mb(std::move(other.m_mb)),
87  m_stream(std::move(other.m_stream)) {}
88 
89  inline std::istream& stream() {
90  return *m_stream;
91  }
92 };
93 
95 
96 }}
97 
Contains the text compression and encoding framework.
Definition: namespaces.hpp:11
ByteView View
Definition: View.hpp:25