| 1 | #ifndef AWS_COMMON_REF_COUNT_H |
| 2 | #define AWS_COMMON_REF_COUNT_H |
| 3 | |
| 4 | /** |
| 5 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 6 | * SPDX-License-Identifier: Apache-2.0. |
| 7 | */ |
| 8 | #include <aws/common/common.h> |
| 9 | |
| 10 | #include <aws/common/atomics.h> |
| 11 | #include <aws/common/shutdown_types.h> |
| 12 | |
| 13 | AWS_PUSH_SANE_WARNING_LEVEL |
| 14 | |
| 15 | /* |
| 16 | * A utility type for making ref-counted types, reminiscent of std::shared_ptr in C++ |
| 17 | */ |
| 18 | struct aws_ref_count { |
| 19 | struct aws_atomic_var ref_count; |
| 20 | void *object; |
| 21 | aws_simple_completion_callback *on_zero_fn; |
| 22 | }; |
| 23 | |
| 24 | AWS_EXTERN_C_BEGIN |
| 25 | |
| 26 | /** |
| 27 | * Initializes a ref-counter structure. After initialization, the ref count will be 1. |
| 28 | * |
| 29 | * @param ref_count ref-counter to initialize |
| 30 | * @param object object being ref counted |
| 31 | * @param on_zero_fn function to invoke when the ref count reaches zero |
| 32 | */ |
| 33 | AWS_COMMON_API void aws_ref_count_init( |
| 34 | struct aws_ref_count *ref_count, |
| 35 | void *object, |
| 36 | aws_simple_completion_callback *on_zero_fn); |
| 37 | |
| 38 | /** |
| 39 | * Increments a ref-counter's ref count |
| 40 | * |
| 41 | * @param ref_count ref-counter to increment the count for |
| 42 | * @return the object being ref-counted |
| 43 | */ |
| 44 | AWS_COMMON_API void *aws_ref_count_acquire(struct aws_ref_count *ref_count); |
| 45 | |
| 46 | /** |
| 47 | * Decrements a ref-counter's ref count. Invokes the on_zero callback if the ref count drops to zero |
| 48 | * @param ref_count ref-counter to decrement the count for |
| 49 | * @return the value of the decremented ref count |
| 50 | */ |
| 51 | AWS_COMMON_API size_t aws_ref_count_release(struct aws_ref_count *ref_count); |
| 52 | |
| 53 | AWS_EXTERN_C_END |
| 54 | AWS_POP_SANE_WARNING_LEVEL |
| 55 | |
| 56 | #endif /* AWS_COMMON_REF_COUNT_H */ |