drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
data_ref.h
1/* Drizzle
2 * Copyright (C) 2011 Olaf van der Spek
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#pragma once
19
20#include <cstddef>
21#include <cstring>
22#include <ostream>
23#include <string>
24
25template <class T>
26class data_ref_basic
27{
28public:
29 data_ref_basic()
30 {
31 clear();
32 }
33
34 template <class U>
35 data_ref_basic(const U& c)
36 {
37 assign(&*c.begin(), &*c.end());
38 }
39
40 data_ref_basic(const void* b, const void* e)
41 {
42 assign(b, e);
43 }
44
45 data_ref_basic(const void* b, size_t sz)
46 {
47 assign(b, sz);
48 }
49
50 explicit data_ref_basic(const char* b)
51 {
52 assign(b, strlen(b));
53 }
54
55 void clear()
56 {
57 begin_ = end_ = reinterpret_cast<T>("");
58 }
59
60 void assign(const void* b, const void* e)
61 {
62 begin_ = reinterpret_cast<T>(b);
63 end_ = reinterpret_cast<T>(e);
64 }
65
66 void assign(const void* b, size_t sz)
67 {
68 begin_ = reinterpret_cast<T>(b);
69 end_ = begin_ + sz;
70 }
71
72 T begin() const
73 {
74 return begin_;
75 }
76
77 T end() const
78 {
79 return end_;
80 }
81
82 T data() const
83 {
84 return begin();
85 }
86
87 size_t size() const
88 {
89 return end() - begin();
90 }
91
92 bool empty() const
93 {
94 return begin() == end();
95 }
96
97 char front() const
98 {
99 return *begin();
100 }
101
102 char back() const
103 {
104 return end()[-1];
105 }
106
107 void pop_front()
108 {
109 begin_++;
110 }
111
112 void pop_back()
113 {
114 end_--;
115 }
116
117 operator std::string() const
118 {
119 return to_string(*this);
120 }
121private:
122 T begin_;
123 T end_;
124};
125
127typedef data_ref_basic<const char*> str_ref;
128
129inline std::ostream& operator<<(std::ostream& os, str_ref v)
130{
131 return os.write(v.data(), v.size());
132}
133
134inline std::string to_string(str_ref v)
135{
136 return std::string(v.data(), v.size());
137}