Vince's CSV Parser
Loading...
Searching...
No Matches
string_view_stream.hpp
1#pragma once
2
3#include <algorithm>
4#include <cstring>
5#include <istream>
6
7#include "common.hpp"
8
9namespace csv {
10 namespace internals {
17 class StringViewStreamBuf : public std::streambuf {
18 public:
20 char* begin = const_cast<char*>(view.data());
21 char* end = begin + view.size();
22 this->setg(begin, begin, end);
23 }
24
25 protected:
26 std::streamsize xsgetn(char* s, std::streamsize count) override {
27 const std::streamsize avail = this->egptr() - this->gptr();
28 const std::streamsize n = std::min(avail, count);
29 if (n > 0) {
30 std::memcpy(s, this->gptr(), static_cast<size_t>(n));
31 this->gbump(static_cast<int>(n));
32 }
33 return n;
34 }
35
36 pos_type seekoff(off_type off, std::ios_base::seekdir dir,
37 std::ios_base::openmode which = std::ios_base::in) override {
38 if (!(which & std::ios_base::in)) {
39 return pos_type(off_type(-1));
40 }
41
42 const auto begin = this->eback();
43 const auto curr = this->gptr();
44 const auto end = this->egptr();
45
46 off_type base = 0;
47 if (dir == std::ios_base::beg) {
48 base = 0;
49 }
50 else if (dir == std::ios_base::cur) {
51 base = static_cast<off_type>(curr - begin);
52 }
53 else if (dir == std::ios_base::end) {
54 base = static_cast<off_type>(end - begin);
55 }
56 else {
57 return pos_type(off_type(-1));
58 }
59
60 const off_type next = base + off;
61 const off_type size = static_cast<off_type>(end - begin);
62 if (next < 0 || next > size) {
63 return pos_type(off_type(-1));
64 }
65
66 this->setg(begin, begin + next, end);
67 return pos_type(next);
68 }
69
70 pos_type seekpos(pos_type pos,
71 std::ios_base::openmode which = std::ios_base::in) override {
72 return this->seekoff(off_type(pos), std::ios_base::beg, which);
73 }
74 };
75
82 class StringViewStream : public std::istream {
83 public:
85 : std::istream(nullptr), _buf(view) {
86 this->rdbuf(&_buf);
87 }
88
89 StringViewStream(const StringViewStream&) = delete;
91 StringViewStream& operator=(const StringViewStream&) = delete;
92 StringViewStream& operator=(StringViewStream&&) = delete;
93
94 private:
96 };
97 }
98}
streambuf adapter over csv::string_view with no data copy.
Lightweight istream over csv::string_view with zero copy.
A standalone header file containing shared code.
The all encompassing namespace.
nonstd::string_view string_view
The string_view class used by this library.
Definition common.hpp:135