2bf2b0f499f04ad77e71dc89b6d9b713cc85f5a2
[platform/upstream/grpc.git] / src / core / lib / slice / slice.cc
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/slice/slice_internal.h"
22
23 #include <grpc/slice.h>
24 #include <grpc/support/alloc.h>
25 #include <grpc/support/log.h>
26
27 #include <string.h>
28
29 #include "src/core/lib/gprpp/memory.h"
30 #include "src/core/lib/gprpp/ref_counted.h"
31 #include "src/core/lib/iomgr/exec_ctx.h"
32
33 char* grpc_slice_to_c_string(grpc_slice slice) {
34   char* out = static_cast<char*>(gpr_malloc(GRPC_SLICE_LENGTH(slice) + 1));
35   memcpy(out, GRPC_SLICE_START_PTR(slice), GRPC_SLICE_LENGTH(slice));
36   out[GRPC_SLICE_LENGTH(slice)] = 0;
37   return out;
38 }
39
40 grpc_slice grpc_empty_slice(void) {
41   grpc_slice out;
42   out.refcount = nullptr;
43   out.data.inlined.length = 0;
44   return out;
45 }
46
47 grpc_slice grpc_slice_copy(grpc_slice s) {
48   grpc_slice out = GRPC_SLICE_MALLOC(GRPC_SLICE_LENGTH(s));
49   memcpy(GRPC_SLICE_START_PTR(out), GRPC_SLICE_START_PTR(s),
50          GRPC_SLICE_LENGTH(s));
51   return out;
52 }
53
54 /* Public API */
55 grpc_slice grpc_slice_ref(grpc_slice slice) {
56   return grpc_slice_ref_internal(slice);
57 }
58
59 /* Public API */
60 void grpc_slice_unref(grpc_slice slice) {
61   if (grpc_core::ExecCtx::Get() == nullptr) {
62     grpc_core::ExecCtx exec_ctx;
63     grpc_slice_unref_internal(slice);
64   } else {
65     grpc_slice_unref_internal(slice);
66   }
67 }
68
69 /* grpc_slice_from_static_string support structure - a refcount that does
70    nothing */
71 static grpc_slice_refcount NoopRefcount;
72
73 size_t grpc_slice_memory_usage(grpc_slice s) {
74   if (s.refcount == nullptr || s.refcount == &NoopRefcount) {
75     return 0;
76   } else {
77     return s.data.refcounted.length;
78   }
79 }
80
81 grpc_slice grpc_slice_from_static_buffer(const void* s, size_t len) {
82   grpc_slice slice;
83   slice.refcount = &NoopRefcount;
84   slice.data.refcounted.bytes = (uint8_t*)s;
85   slice.data.refcounted.length = len;
86   return slice;
87 }
88
89 grpc_slice grpc_slice_from_static_string(const char* s) {
90   return grpc_slice_from_static_buffer(s, strlen(s));
91 }
92
93 namespace grpc_core {
94
95 /* grpc_slice_new support structures - we create a refcount object extended
96    with the user provided data pointer & destroy function */
97 class NewSliceRefcount {
98  public:
99   static void Destroy(void* arg) {
100     Delete(static_cast<NewSliceRefcount*>(arg));
101   }
102
103   NewSliceRefcount(void (*destroy)(void*), void* user_data)
104       : rc_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this, &rc_),
105         user_destroy_(destroy),
106         user_data_(user_data) {}
107
108   GPRC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE
109
110   grpc_slice_refcount* base_refcount() { return &rc_; }
111
112  private:
113   ~NewSliceRefcount() { user_destroy_(user_data_); }
114
115   grpc_slice_refcount rc_;
116   RefCount refs_;
117   void (*user_destroy_)(void*);
118   void* user_data_;
119 };
120
121 }  // namespace grpc_core
122
123 grpc_slice grpc_slice_new_with_user_data(void* p, size_t len,
124                                          void (*destroy)(void*),
125                                          void* user_data) {
126   grpc_slice slice;
127   slice.refcount =
128       grpc_core::New<grpc_core::NewSliceRefcount>(destroy, user_data)
129           ->base_refcount();
130   slice.data.refcounted.bytes = static_cast<uint8_t*>(p);
131   slice.data.refcounted.length = len;
132   return slice;
133 }
134
135 grpc_slice grpc_slice_new(void* p, size_t len, void (*destroy)(void*)) {
136   /* Pass "p" to *destroy when the slice is no longer needed. */
137   return grpc_slice_new_with_user_data(p, len, destroy, p);
138 }
139
140 namespace grpc_core {
141 /* grpc_slice_new_with_len support structures - we create a refcount object
142    extended with the user provided data pointer & destroy function */
143
144 class NewWithLenSliceRefcount {
145  public:
146   static void Destroy(void* arg) {
147     Delete(static_cast<NewWithLenSliceRefcount*>(arg));
148   }
149
150   NewWithLenSliceRefcount(void (*destroy)(void*, size_t), void* user_data,
151                           size_t user_length)
152       : rc_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this, &rc_),
153         user_data_(user_data),
154         user_length_(user_length),
155         user_destroy_(destroy) {}
156
157   GPRC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE
158
159   grpc_slice_refcount* base_refcount() { return &rc_; }
160
161  private:
162   ~NewWithLenSliceRefcount() { user_destroy_(user_data_, user_length_); }
163
164   grpc_slice_refcount rc_;
165   RefCount refs_;
166   void* user_data_;
167   size_t user_length_;
168   void (*user_destroy_)(void*, size_t);
169 };
170
171 }  // namespace grpc_core
172
173 grpc_slice grpc_slice_new_with_len(void* p, size_t len,
174                                    void (*destroy)(void*, size_t)) {
175   grpc_slice slice;
176   slice.refcount =
177       grpc_core::New<grpc_core::NewWithLenSliceRefcount>(destroy, p, len)
178           ->base_refcount();
179   slice.data.refcounted.bytes = static_cast<uint8_t*>(p);
180   slice.data.refcounted.length = len;
181   return slice;
182 }
183
184 grpc_slice grpc_slice_from_copied_buffer(const char* source, size_t length) {
185   if (length == 0) return grpc_empty_slice();
186   grpc_slice slice = GRPC_SLICE_MALLOC(length);
187   memcpy(GRPC_SLICE_START_PTR(slice), source, length);
188   return slice;
189 }
190
191 grpc_slice grpc_slice_from_copied_string(const char* source) {
192   return grpc_slice_from_copied_buffer(source, strlen(source));
193 }
194
195 namespace {
196
197 class MallocRefCount {
198  public:
199   static void Destroy(void* arg) {
200     MallocRefCount* r = static_cast<MallocRefCount*>(arg);
201     r->~MallocRefCount();
202     gpr_free(r);
203   }
204
205   MallocRefCount()
206       : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
207               &base_) {}
208   ~MallocRefCount() = default;
209
210   grpc_slice_refcount* base_refcount() { return &base_; }
211
212  private:
213   grpc_slice_refcount base_;
214   grpc_core::RefCount refs_;
215 };
216
217 }  // namespace
218
219 grpc_slice grpc_slice_malloc_large(size_t length) {
220   grpc_slice slice;
221
222   /* Memory layout used by the slice created here:
223
224      +-----------+----------------------------------------------------------+
225      | refcount  | bytes                                                    |
226      +-----------+----------------------------------------------------------+
227
228      refcount is a malloc_refcount
229      bytes is an array of bytes of the requested length
230      Both parts are placed in the same allocation returned from gpr_malloc */
231   auto* rc =
232       static_cast<MallocRefCount*>(gpr_malloc(sizeof(MallocRefCount) + length));
233
234   /* Initial refcount on rc is 1 - and it's up to the caller to release
235      this reference. */
236   new (rc) MallocRefCount();
237
238   /* Build up the slice to be returned. */
239   /* The slices refcount points back to the allocated block. */
240   slice.refcount = rc->base_refcount();
241   /* The data bytes are placed immediately after the refcount struct */
242   slice.data.refcounted.bytes = reinterpret_cast<uint8_t*>(rc + 1);
243   /* And the length of the block is set to the requested length */
244   slice.data.refcounted.length = length;
245   return slice;
246 }
247
248 grpc_slice grpc_slice_malloc(size_t length) {
249   grpc_slice slice;
250
251   if (length > sizeof(slice.data.inlined.bytes)) {
252     return grpc_slice_malloc_large(length);
253   } else {
254     /* small slice: just inline the data */
255     slice.refcount = nullptr;
256     slice.data.inlined.length = static_cast<uint8_t>(length);
257   }
258   return slice;
259 }
260
261 grpc_slice grpc_slice_sub_no_ref(grpc_slice source, size_t begin, size_t end) {
262   grpc_slice subset;
263
264   GPR_ASSERT(end >= begin);
265
266   if (source.refcount) {
267     /* Enforce preconditions */
268     GPR_ASSERT(source.data.refcounted.length >= end);
269
270     /* Build the result */
271     subset.refcount = source.refcount->sub_refcount();
272     /* Point into the source array */
273     subset.data.refcounted.bytes = source.data.refcounted.bytes + begin;
274     subset.data.refcounted.length = end - begin;
275   } else {
276     /* Enforce preconditions */
277     GPR_ASSERT(source.data.inlined.length >= end);
278     subset.refcount = nullptr;
279     subset.data.inlined.length = static_cast<uint8_t>(end - begin);
280     memcpy(subset.data.inlined.bytes, source.data.inlined.bytes + begin,
281            end - begin);
282   }
283   return subset;
284 }
285
286 grpc_slice grpc_slice_sub(grpc_slice source, size_t begin, size_t end) {
287   grpc_slice subset;
288
289   if (end - begin <= sizeof(subset.data.inlined.bytes)) {
290     subset.refcount = nullptr;
291     subset.data.inlined.length = static_cast<uint8_t>(end - begin);
292     memcpy(subset.data.inlined.bytes, GRPC_SLICE_START_PTR(source) + begin,
293            end - begin);
294   } else {
295     subset = grpc_slice_sub_no_ref(source, begin, end);
296     /* Bump the refcount */
297     subset.refcount->Ref();
298   }
299   return subset;
300 }
301
302 grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice* source, size_t split,
303                                            grpc_slice_ref_whom ref_whom) {
304   grpc_slice tail;
305
306   if (source->refcount == nullptr) {
307     /* inlined data, copy it out */
308     GPR_ASSERT(source->data.inlined.length >= split);
309     tail.refcount = nullptr;
310     tail.data.inlined.length =
311         static_cast<uint8_t>(source->data.inlined.length - split);
312     memcpy(tail.data.inlined.bytes, source->data.inlined.bytes + split,
313            tail.data.inlined.length);
314     source->data.inlined.length = static_cast<uint8_t>(split);
315   } else {
316     size_t tail_length = source->data.refcounted.length - split;
317     GPR_ASSERT(source->data.refcounted.length >= split);
318     if (tail_length < sizeof(tail.data.inlined.bytes) &&
319         ref_whom != GRPC_SLICE_REF_TAIL) {
320       /* Copy out the bytes - it'll be cheaper than refcounting */
321       tail.refcount = nullptr;
322       tail.data.inlined.length = static_cast<uint8_t>(tail_length);
323       memcpy(tail.data.inlined.bytes, source->data.refcounted.bytes + split,
324              tail_length);
325       source->refcount = source->refcount->sub_refcount();
326     } else {
327       /* Build the result */
328       switch (ref_whom) {
329         case GRPC_SLICE_REF_TAIL:
330           tail.refcount = source->refcount->sub_refcount();
331           source->refcount = &NoopRefcount;
332           break;
333         case GRPC_SLICE_REF_HEAD:
334           tail.refcount = &NoopRefcount;
335           source->refcount = source->refcount->sub_refcount();
336           break;
337         case GRPC_SLICE_REF_BOTH:
338           tail.refcount = source->refcount->sub_refcount();
339           source->refcount = source->refcount->sub_refcount();
340           /* Bump the refcount */
341           tail.refcount->Ref();
342           break;
343       }
344       /* Point into the source array */
345       tail.data.refcounted.bytes = source->data.refcounted.bytes + split;
346       tail.data.refcounted.length = tail_length;
347     }
348     source->data.refcounted.length = split;
349   }
350
351   return tail;
352 }
353
354 grpc_slice grpc_slice_split_tail(grpc_slice* source, size_t split) {
355   return grpc_slice_split_tail_maybe_ref(source, split, GRPC_SLICE_REF_BOTH);
356 }
357
358 grpc_slice grpc_slice_split_head(grpc_slice* source, size_t split) {
359   grpc_slice head;
360
361   if (source->refcount == nullptr) {
362     GPR_ASSERT(source->data.inlined.length >= split);
363
364     head.refcount = nullptr;
365     head.data.inlined.length = static_cast<uint8_t>(split);
366     memcpy(head.data.inlined.bytes, source->data.inlined.bytes, split);
367     source->data.inlined.length =
368         static_cast<uint8_t>(source->data.inlined.length - split);
369     memmove(source->data.inlined.bytes, source->data.inlined.bytes + split,
370             source->data.inlined.length);
371   } else if (split < sizeof(head.data.inlined.bytes)) {
372     GPR_ASSERT(source->data.refcounted.length >= split);
373
374     head.refcount = nullptr;
375     head.data.inlined.length = static_cast<uint8_t>(split);
376     memcpy(head.data.inlined.bytes, source->data.refcounted.bytes, split);
377     source->refcount = source->refcount->sub_refcount();
378     source->data.refcounted.bytes += split;
379     source->data.refcounted.length -= split;
380   } else {
381     GPR_ASSERT(source->data.refcounted.length >= split);
382
383     /* Build the result */
384     head.refcount = source->refcount->sub_refcount();
385     /* Bump the refcount */
386     head.refcount->Ref();
387     /* Point into the source array */
388     head.data.refcounted.bytes = source->data.refcounted.bytes;
389     head.data.refcounted.length = split;
390     source->refcount = source->refcount->sub_refcount();
391     source->data.refcounted.bytes += split;
392     source->data.refcounted.length -= split;
393   }
394
395   return head;
396 }
397
398 int grpc_slice_default_eq_impl(grpc_slice a, grpc_slice b) {
399   if (GRPC_SLICE_LENGTH(a) != GRPC_SLICE_LENGTH(b)) return false;
400   if (GRPC_SLICE_LENGTH(a) == 0) return true;
401   return 0 == memcmp(GRPC_SLICE_START_PTR(a), GRPC_SLICE_START_PTR(b),
402                      GRPC_SLICE_LENGTH(a));
403 }
404
405 int grpc_slice_eq(grpc_slice a, grpc_slice b) {
406   if (a.refcount && b.refcount &&
407       a.refcount->GetType() == b.refcount->GetType()) {
408     return a.refcount->Eq(a, b);
409   }
410   return grpc_slice_default_eq_impl(a, b);
411 }
412
413 int grpc_slice_cmp(grpc_slice a, grpc_slice b) {
414   int d = static_cast<int>(GRPC_SLICE_LENGTH(a) - GRPC_SLICE_LENGTH(b));
415   if (d != 0) return d;
416   return memcmp(GRPC_SLICE_START_PTR(a), GRPC_SLICE_START_PTR(b),
417                 GRPC_SLICE_LENGTH(a));
418 }
419
420 int grpc_slice_str_cmp(grpc_slice a, const char* b) {
421   size_t b_length = strlen(b);
422   int d = static_cast<int>(GRPC_SLICE_LENGTH(a) - b_length);
423   if (d != 0) return d;
424   return memcmp(GRPC_SLICE_START_PTR(a), b, b_length);
425 }
426
427 int grpc_slice_is_equivalent(grpc_slice a, grpc_slice b) {
428   if (a.refcount == nullptr || b.refcount == nullptr) {
429     return grpc_slice_eq(a, b);
430   }
431   return a.data.refcounted.length == b.data.refcounted.length &&
432          a.data.refcounted.bytes == b.data.refcounted.bytes;
433 }
434
435 int grpc_slice_buf_start_eq(grpc_slice a, const void* b, size_t len) {
436   if (GRPC_SLICE_LENGTH(a) < len) return 0;
437   return 0 == memcmp(GRPC_SLICE_START_PTR(a), b, len);
438 }
439
440 int grpc_slice_rchr(grpc_slice s, char c) {
441   const char* b = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(s);
442   int i;
443   for (i = static_cast<int> GRPC_SLICE_LENGTH(s) - 1; i != -1 && b[i] != c; i--)
444     ;
445   return i;
446 }
447
448 int grpc_slice_chr(grpc_slice s, char c) {
449   const char* b = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(s);
450   const char* p = static_cast<const char*>(memchr(b, c, GRPC_SLICE_LENGTH(s)));
451   return p == nullptr ? -1 : static_cast<int>(p - b);
452 }
453
454 int grpc_slice_slice(grpc_slice haystack, grpc_slice needle) {
455   size_t haystack_len = GRPC_SLICE_LENGTH(haystack);
456   const uint8_t* haystack_bytes = GRPC_SLICE_START_PTR(haystack);
457   size_t needle_len = GRPC_SLICE_LENGTH(needle);
458   const uint8_t* needle_bytes = GRPC_SLICE_START_PTR(needle);
459
460   if (haystack_len == 0 || needle_len == 0) return -1;
461   if (haystack_len < needle_len) return -1;
462   if (haystack_len == needle_len)
463     return grpc_slice_eq(haystack, needle) ? 0 : -1;
464   if (needle_len == 1)
465     return grpc_slice_chr(haystack, static_cast<char>(*needle_bytes));
466
467   const uint8_t* last = haystack_bytes + haystack_len - needle_len;
468   for (const uint8_t* cur = haystack_bytes; cur != last; ++cur) {
469     if (0 == memcmp(cur, needle_bytes, needle_len)) {
470       return static_cast<int>(cur - haystack_bytes);
471     }
472   }
473   return -1;
474 }
475
476 grpc_slice grpc_slice_dup(grpc_slice a) {
477   grpc_slice copy = GRPC_SLICE_MALLOC(GRPC_SLICE_LENGTH(a));
478   memcpy(GRPC_SLICE_START_PTR(copy), GRPC_SLICE_START_PTR(a),
479          GRPC_SLICE_LENGTH(a));
480   return copy;
481 }