1 /*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
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 RUNTIME_INCLUDE_TAIHE_COMMON_H_
16 #define RUNTIME_INCLUDE_TAIHE_COMMON_H_
17 // NOLINTBEGIN
18
19 #include <stdbool.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23
24 #define TH_NONNULL __attribute__((nonnull))
25
26 #define TH_ASSERT(condition, message) \
27 do { \
28 if (!(condition)) { \
29 fprintf(stderr, \
30 "Assertion failed: (%s), function %s, file %s, line %d.\n" \
31 "Message: %s\n", \
32 #condition, __FUNCTION__, __FILE__, __LINE__, message); \
33 abort(); \
34 } \
35 } while (0)
36
37 #ifdef __cplusplus
38 #define TH_EXPORT extern "C" __attribute__((visibility("default")))
39 #else
40 #define TH_EXPORT extern __attribute__((visibility("default")))
41 #endif
42
43 #ifdef __cplusplus
44 #define TH_INLINE inline
45 #else
46 #define TH_INLINE static inline
47 #endif
48
49 // REFERENCE COUNTING //
50
51 typedef uint32_t TRefCount;
52
53 // Sets the counter to a fixed value.
tref_set(TRefCount * c,TRefCount i)54 TH_INLINE void tref_set(TRefCount *c, TRefCount i)
55 {
56 __atomic_store_n(c, i, __ATOMIC_SEQ_CST);
57 }
58
59 // Increments the refcount and returns the *original* value before add.
tref_inc(TRefCount * c)60 TH_INLINE TRefCount tref_inc(TRefCount *c)
61 {
62 return __atomic_fetch_add(c, 1, __ATOMIC_SEQ_CST);
63 }
64
65 // Decrements the refcount and returns whether the memory should be freed.
tref_dec(TRefCount * c)66 TH_INLINE int tref_dec(TRefCount *c)
67 {
68 return __atomic_sub_fetch(c, 1, __ATOMIC_SEQ_CST) == 0;
69 }
70 // NOLINTEND
71 #endif // RUNTIME_INCLUDE_TAIHE_COMMON_H_