| 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_REFCOUNT_H |
| 16 |
#define GRPC_CORE_LIB_SLICE_SLICE_REFCOUNT_H |
| 17 |
|
| 18 |
#include <grpc/support/port_platform.h> |
| 19 |
|
| 20 |
#include <stddef.h> |
| 21 |
|
| 22 |
#include <atomic> |
| 23 |
|
| 24 |
// grpc_slice_refcount : A reference count for grpc_slice. |
| 25 |
struct grpc_slice_refcount { |
| 26 |
public: |
| 27 |
typedef void (*DestroyerFn)(grpc_slice_refcount*); |
| 28 |
|
| 29 |
static grpc_slice_refcount* NoopRefcount() { |
| 30 |
return reinterpret_cast<grpc_slice_refcount*>(1); |
| 31 |
} |
| 32 |
|
| 33 |
grpc_slice_refcount() = default; |
| 34 |
|
| 35 |
// Regular constructor for grpc_slice_refcount. |
| 36 |
// |
| 37 |
// Parameters: |
| 38 |
// 1. DestroyerFn destroyer_fn |
| 39 |
// Called when the refcount goes to 0, with 'this' as parameter. |
| 40 |
explicit grpc_slice_refcount(DestroyerFn destroyer_fn) |
| 41 |
: destroyer_fn_(destroyer_fn) {} |
| 42 |
|
| 43 |
void Ref() { ref_.fetch_add(1, std::memory_order_relaxed); } |
| 44 |
void Unref() { |
| 45 |
if (ref_.fetch_sub(1, std::memory_order_acq_rel) == 1) { |
| 46 |
destroyer_fn_(this); |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
// Is this the only instance? |
| 51 |
// For this to be useful the caller needs to ensure that if this is the only |
| 52 |
// instance, no other instance could be created during this call. |
| 53 |
bool IsUnique() const { return ref_.load(std::memory_order_relaxed) == 1; } |
| 54 |
|
| 55 |
private: |
| 56 |
std::atomic<size_t> ref_{1}; |
| 57 |
DestroyerFn destroyer_fn_ = nullptr; |
| 58 |
}; |
| 59 |
|
| 60 |
#endif // GRPC_CORE_LIB_SLICE_SLICE_REFCOUNT_H |