• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_SRC_CORE_LIB_SLICE_SLICE_REFCOUNT_H
16 #define GRPC_SRC_CORE_LIB_SLICE_SLICE_REFCOUNT_H
17 
18 #include <grpc/support/port_platform.h>
19 #include <inttypes.h>
20 #include <stddef.h>
21 
22 #include <atomic>
23 
24 #include "src/core/lib/debug/trace.h"
25 #include "src/core/util/debug_location.h"
26 
27 // grpc_slice_refcount : A reference count for grpc_slice.
28 struct grpc_slice_refcount {
29  public:
30   typedef void (*DestroyerFn)(grpc_slice_refcount*);
31 
NoopRefcountgrpc_slice_refcount32   static grpc_slice_refcount* NoopRefcount() {
33     return reinterpret_cast<grpc_slice_refcount*>(1);
34   }
35 
36   grpc_slice_refcount() = default;
37 
38   // Regular constructor for grpc_slice_refcount.
39   //
40   // Parameters:
41   //  1. DestroyerFn destroyer_fn
42   //  Called when the refcount goes to 0, with 'this' as parameter.
grpc_slice_refcountgrpc_slice_refcount43   explicit grpc_slice_refcount(DestroyerFn destroyer_fn)
44       : destroyer_fn_(destroyer_fn) {}
45 
Refgrpc_slice_refcount46   void Ref(grpc_core::DebugLocation location) {
47     auto prev_refs = ref_.fetch_add(1, std::memory_order_relaxed);
48     GRPC_TRACE_LOG(slice_refcount, INFO)
49             .AtLocation(location.file(), location.line())
50         << "REF " << this << " " << prev_refs << "->" << prev_refs + 1;
51   }
Unrefgrpc_slice_refcount52   void Unref(grpc_core::DebugLocation location) {
53     auto prev_refs = ref_.fetch_sub(1, std::memory_order_acq_rel);
54     GRPC_TRACE_LOG(slice_refcount, INFO)
55             .AtLocation(location.file(), location.line())
56         << "UNREF " << this << " " << prev_refs << "->" << prev_refs - 1;
57     if (prev_refs == 1) {
58       destroyer_fn_(this);
59     }
60   }
61 
62   // Is this the only instance?
63   // For this to be useful the caller needs to ensure that if this is the only
64   // instance, no other instance could be created during this call.
IsUniquegrpc_slice_refcount65   bool IsUnique() const { return ref_.load(std::memory_order_relaxed) == 1; }
66 
67  private:
68   std::atomic<size_t> ref_{1};
69   DestroyerFn destroyer_fn_ = nullptr;
70 };
71 
72 #endif  // GRPC_SRC_CORE_LIB_SLICE_SLICE_REFCOUNT_H
73