Debian Codegraph @

src/core/lib/slice/slice.h

raw
1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef GRPC_CORE_LIB_SLICE_SLICE_H
16 #define GRPC_CORE_LIB_SLICE_SLICE_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <string.h>
21
22 #include <cstdint>
23 #include <string>
24 #include <utility>
25
26 #include "absl/strings/string_view.h"
27
28 #include <grpc/slice.h>
29 #include <grpc/support/log.h>
30
31 #include "src/core/lib/gpr/string.h"
32 #include "src/core/lib/slice/slice_internal.h"
33 #include "src/core/lib/slice/slice_refcount.h"
34
35 // Herein lies grpc_core::Slice and its team of thin wrappers around grpc_slice.
36 // They aim to keep you safe by providing strong guarantees around lifetime and
37 // mutability.
38 //
39 // The team:
40 // Slice - provides a wrapper around an unknown type of slice.
41 // Immutable (since we don't know who else might be referencing
42 // it), and potentially ref counted.
43 // StaticSlice - provides a wrapper around a static slice. Not refcounted,
44 // fast to copy.
45 // MutableSlice - provides a guarantee of unique ownership, meaning the
46 // underlying data can be mutated safely.
47
48 // This slice implementation is an extension of the event engine Slice
49 // implementation defined in <grpc/event_engine/slice.h>. Changes to this
50 // implementation might warrant changes to the public event engine Slice
51 // type as well.
52
53 namespace grpc_core {
54
55 inline const grpc_slice& CSliceRef(const grpc_slice& slice) {
56 if (reinterpret_cast<uintptr_t>(slice.refcount) > 1) {
57 slice.refcount->Ref();
58 }
59 return slice;
60 }
61
62 inline void CSliceUnref(const grpc_slice& slice) {
63 if (reinterpret_cast<uintptr_t>(slice.refcount) > 1) {
64 slice.refcount->Unref();
65 }
66 }
67
68 namespace slice_detail {
69
70 // Returns an empty slice.
71 static constexpr grpc_slice EmptySlice() { return {nullptr, {}}; }
72
73 // BaseSlice holds the grpc_slice object, but does not apply refcounting policy.
74 // It does export immutable access into the slice, such that this can be shared
75 // by all storage policies.
76 class BaseSlice {
77 public:
78 BaseSlice(const BaseSlice&) = delete;
79 BaseSlice& operator=(const BaseSlice&) = delete;
80 BaseSlice(BaseSlice&& other) = delete;
81 BaseSlice& operator=(BaseSlice&& other) = delete;
82
83 // Iterator access to the underlying bytes
84 const uint8_t* begin() const { return GRPC_SLICE_START_PTR(c_slice()); }
85 const uint8_t* end() const { return GRPC_SLICE_END_PTR(c_slice()); }
86 const uint8_t* cbegin() const { return GRPC_SLICE_START_PTR(c_slice()); }
87 const uint8_t* cend() const { return GRPC_SLICE_END_PTR(c_slice()); }
88
89 // Retrieve a borrowed reference to the underlying grpc_slice.
90 const grpc_slice& c_slice() const { return slice_; }
91
92 // Retrieve the underlying grpc_slice, and replace the one in this object with
93 // EmptySlice().
94 grpc_slice TakeCSlice() {
95 grpc_slice out = slice_;
96 slice_ = EmptySlice();
97 return out;
98 }
99
100 // As other things... borrowed references.
101 absl::string_view as_string_view() const {
102 return absl::string_view(reinterpret_cast<const char*>(data()), size());
103 }
104
105 // Array access
106 uint8_t operator[](size_t i) const {
107 return GRPC_SLICE_START_PTR(c_slice())[i];
108 }
109
110 // Access underlying data
111 const uint8_t* data() const { return GRPC_SLICE_START_PTR(c_slice()); }
112
113 // Size of the slice
114 size_t size() const { return GRPC_SLICE_LENGTH(c_slice()); }
115 size_t length() const { return size(); }
116 bool empty() const { return size() == 0; }
117
118 // For inlined slices - are these two slices equal?
119 // For non-inlined slices - do these two slices refer to the same block of
120 // memory?
121 bool is_equivalent(const BaseSlice& other) const {
122 return grpc_slice_is_equivalent(slice_, other.slice_);
123 }
124
125 uint32_t Hash() const { return grpc_slice_hash(slice_); }
126
127 protected:
128 BaseSlice() : slice_(EmptySlice()) {}
129 explicit BaseSlice(const grpc_slice& slice) : slice_(slice) {}
130 ~BaseSlice() = default;
131
132 void Swap(BaseSlice* other) { std::swap(slice_, other->slice_); }
133 void SetCSlice(const grpc_slice& slice) { slice_ = slice; }
134
135 uint8_t* mutable_data() { return GRPC_SLICE_START_PTR(slice_); }
136
137 grpc_slice* c_slice_ptr() { return &slice_; }
138
139 private:
140 grpc_slice slice_;
141 };
142
143 inline bool operator==(const BaseSlice& a, const BaseSlice& b) {
144 return grpc_slice_eq(a.c_slice(), b.c_slice()) != 0;
145 }
146
147 inline bool operator!=(const BaseSlice& a, const BaseSlice& b) {
148 return grpc_slice_eq(a.c_slice(), b.c_slice()) == 0;
149 }
150
151 inline bool operator==(const BaseSlice& a, absl::string_view b) {
152 return a.as_string_view() == b;
153 }
154
155 inline bool operator!=(const BaseSlice& a, absl::string_view b) {
156 return a.as_string_view() != b;
157 }
158
159 inline bool operator==(absl::string_view a, const BaseSlice& b) {
160 return a == b.as_string_view();
161 }
162
163 inline bool operator!=(absl::string_view a, const BaseSlice& b) {
164 return a != b.as_string_view();
165 }
166
167 inline bool operator==(const BaseSlice& a, const grpc_slice& b) {
168 return grpc_slice_eq(a.c_slice(), b) != 0;
169 }
170
171 inline bool operator!=(const BaseSlice& a, const grpc_slice& b) {
172 return grpc_slice_eq(a.c_slice(), b) == 0;
173 }
174
175 inline bool operator==(const grpc_slice& a, const BaseSlice& b) {
176 return grpc_slice_eq(a, b.c_slice()) != 0;
177 }
178
179 inline bool operator!=(const grpc_slice& a, const BaseSlice& b) {
180 return grpc_slice_eq(a, b.c_slice()) == 0;
181 }
182
183 template <typename Out>
184 struct CopyConstructors {
185 static Out FromCopiedString(const char* s) {
186 return FromCopiedBuffer(s, strlen(s));
187 }
188 static Out FromCopiedString(absl::string_view s) {
189 return FromCopiedBuffer(s.data(), s.size());
190 }
191 static Out FromCopiedString(std::string s) {
192 return Out(grpc_slice_from_cpp_string(std::move(s)));
193 }
194 static Out FromCopiedBuffer(const char* p, size_t len) {
195 return Out(grpc_slice_from_copied_buffer(p, len));
196 }
197
198 template <typename Buffer>
199 static Out FromCopiedBuffer(const Buffer& buffer) {
200 return FromCopiedBuffer(reinterpret_cast<const char*>(buffer.data()),
201 buffer.size());
202 }
203
204 static Out FromInt64(int64_t i) {
205 char buffer[GPR_LTOA_MIN_BUFSIZE];
206 gpr_ltoa(i, buffer);
207 return FromCopiedString(buffer);
208 }
209 };
210
211 template <typename Out>
212 struct StaticConstructors {
213 static Out FromStaticString(const char* s) {
214 return FromStaticBuffer(s, strlen(s));
215 }
216
217 static Out FromStaticString(absl::string_view s) {
218 return FromStaticBuffer(s.data(), s.size());
219 }
220
221 static Out FromStaticBuffer(const void* s, size_t len) {
222 grpc_slice slice;
223 slice.refcount = grpc_slice_refcount::NoopRefcount();
224 slice.data.refcounted.bytes =
225 const_cast<uint8_t*>(static_cast<const uint8_t*>(s));
226 slice.data.refcounted.length = len;
227 return Out(slice);
228 }
229 };
230
231 } // namespace slice_detail
232
233 class StaticSlice : public slice_detail::BaseSlice,
234 public slice_detail::StaticConstructors<StaticSlice> {
235 public:
236 StaticSlice() = default;
237 explicit StaticSlice(const grpc_slice& slice)
238 : slice_detail::BaseSlice(slice) {
239 GPR_DEBUG_ASSERT(slice.refcount == grpc_slice_refcount::NoopRefcount());
240 }
241
242 StaticSlice(const StaticSlice& other)
243 : slice_detail::BaseSlice(other.c_slice()) {}
244 StaticSlice& operator=(const StaticSlice& other) {
245 SetCSlice(other.c_slice());
246 return *this;
247 }
248 StaticSlice(StaticSlice&& other) noexcept
249 : slice_detail::BaseSlice(other.TakeCSlice()) {}
250 StaticSlice& operator=(StaticSlice&& other) noexcept {
251 Swap(&other);
252 return *this;
253 }
254 };
255
256 class MutableSlice : public slice_detail::BaseSlice,
257 public slice_detail::CopyConstructors<MutableSlice> {
258 public:
259 MutableSlice() = default;
260 explicit MutableSlice(const grpc_slice& slice)
261 : slice_detail::BaseSlice(slice) {
262 GPR_DEBUG_ASSERT(slice.refcount == nullptr || slice.refcount->IsUnique());
263 }
264 ~MutableSlice() { CSliceUnref(c_slice()); }
265
266 MutableSlice(const MutableSlice&) = delete;
267 MutableSlice& operator=(const MutableSlice&) = delete;
268 MutableSlice(MutableSlice&& other) noexcept
269 : slice_detail::BaseSlice(other.TakeCSlice()) {}
270 MutableSlice& operator=(MutableSlice&& other) noexcept {
271 Swap(&other);
272 return *this;
273 }
274
275 static MutableSlice CreateUninitialized(size_t length) {
276 return MutableSlice(grpc_slice_malloc(length));
277 }
278
279 // Return a sub slice of this one. Leaves this slice in an indeterminate but
280 // valid state.
281 MutableSlice TakeSubSlice(size_t pos, size_t n) {
282 return MutableSlice(grpc_slice_sub_no_ref(TakeCSlice(), pos, pos + n));
283 }
284
285 // Iterator access to the underlying bytes
286 uint8_t* begin() { return mutable_data(); }
287 uint8_t* end() { return mutable_data() + size(); }
288 uint8_t* data() { return mutable_data(); }
289
290 // Array access
291 uint8_t& operator[](size_t i) { return mutable_data()[i]; }
292 };
293
294 class Slice : public slice_detail::BaseSlice,
295 public slice_detail::CopyConstructors<Slice>,
296 public slice_detail::StaticConstructors<Slice> {
297 public:
298 Slice() = default;
299 ~Slice() { CSliceUnref(c_slice()); }
300
301 explicit Slice(const grpc_slice& slice) : slice_detail::BaseSlice(slice) {}
302 explicit Slice(slice_detail::BaseSlice&& other)
303 : slice_detail::BaseSlice(other.TakeCSlice()) {}
304
305 Slice(const Slice&) = delete;
306 Slice& operator=(const Slice&) = delete;
307 Slice(Slice&& other) noexcept : slice_detail::BaseSlice(other.TakeCSlice()) {}
308 Slice& operator=(Slice&& other) noexcept {
309 Swap(&other);
310 return *this;
311 }
312
313 // A slice might refer to some memory that we keep a refcount to (this is
314 // owned), or some memory that's inlined into the slice (also owned), or some
315 // other block of memory that we know will be available for the lifetime of
316 // some operation in the common case (not owned). In the *less common* case
317 // that we need to keep that slice text for longer than our API's guarantee us
318 // access, we need to take a copy and turn this into something that we do own.
319
320 // TakeOwned returns an owned slice regardless of current ownership, and
321 // leaves the current slice in a valid but externally unpredictable state - in
322 // doing so it can avoid adding a ref to the underlying slice.
323 Slice TakeOwned() {
324 if (c_slice().refcount == nullptr) {
325 return Slice(c_slice());
326 }
327 if (c_slice().refcount == grpc_slice_refcount::NoopRefcount()) {
328 return Slice(grpc_slice_copy(c_slice()));
329 }
330 return Slice(TakeCSlice());
331 }
332
333 // AsOwned returns an owned slice but does not mutate the current slice,
334 // meaning that it may add a reference to the underlying slice.
335 Slice AsOwned() const {
336 if (c_slice().refcount == nullptr) {
337 return Slice(c_slice());
338 }
339 if (c_slice().refcount == grpc_slice_refcount::NoopRefcount()) {
340 return Slice(grpc_slice_copy(c_slice()));
341 }
342 return Ref();
343 }
344
345 // TakeMutable returns a MutableSlice, and leaves the current slice in an
346 // indeterminate but valid state.
347 // A mutable slice requires only one reference to the bytes of the slice -
348 // this can be achieved either with inlined storage or with a single
349 // reference.
350 // If the current slice is refcounted and there are more than one references
351 // to that slice, then the slice is copied in order to achieve a mutable
352 // version.
353 MutableSlice TakeMutable() {
354 if (c_slice().refcount == nullptr) {
355 return MutableSlice(c_slice());
356 }
357 if (c_slice().refcount != grpc_slice_refcount::NoopRefcount() &&
358 c_slice().refcount->IsUnique()) {
359 return MutableSlice(TakeCSlice());
360 }
361 return MutableSlice(grpc_slice_copy(c_slice()));
362 }
363
364 // Return a sub slice of this one. Leaves this slice in an indeterminate but
365 // valid state.
366 Slice TakeSubSlice(size_t pos, size_t n) {
367 return Slice(grpc_slice_sub_no_ref(TakeCSlice(), pos, pos + n));
368 }
369
370 // Return a sub slice of this one. Adds a reference to the underlying slice.
371 Slice RefSubSlice(size_t pos, size_t n) const {
372 return Slice(grpc_slice_sub(c_slice(), pos, pos + n));
373 }
374
375 // Split this slice, returning a new slice containing (split:end] and
376 // leaving this slice with [begin:split).
377 Slice Split(size_t split) {
378 return Slice(grpc_slice_split_tail(c_slice_ptr(), split));
379 }
380
381 Slice Ref() const { return Slice(CSliceRef(c_slice())); }
382
383 Slice Copy() const { return Slice(grpc_slice_copy(c_slice())); }
384
385 static Slice FromRefcountAndBytes(grpc_slice_refcount* r,
386 const uint8_t* begin, const uint8_t* end) {
387 grpc_slice out;
388 out.refcount = r;
389 if (r != grpc_slice_refcount::NoopRefcount()) r->Ref();
390 out.data.refcounted.bytes = const_cast<uint8_t*>(begin);
391 out.data.refcounted.length = end - begin;
392 return Slice(out);
393 }
394
395 static Slice FromExternalString(absl::string_view str) {
396 return FromStaticString(str);
397 }
398 };
399
400 } // namespace grpc_core
401
402 #endif // GRPC_CORE_LIB_SLICE_SLICE_H