Home | History | Annotate | Download | only in cutils
      1 /*
      2  * Copyright (C) 2013 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef _CUTILS_AREF_H_
     18 #define _CUTILS_AREF_H_
     19 
     20 #include <stddef.h>
     21 #include <sys/cdefs.h>
     22 
     23 #ifdef ANDROID_SMP
     24 #include <cutils/atomic-inline.h>
     25 #else
     26 #include <cutils/atomic.h>
     27 #endif
     28 
     29 __BEGIN_DECLS
     30 
     31 #define AREF_TO_ITEM(aref, container, member) \
     32     (container *) (((char*) (aref)) - offsetof(container, member))
     33 
     34 struct aref
     35 {
     36     volatile int32_t count;
     37 };
     38 
     39 static inline void aref_init(struct aref *r)
     40 {
     41     r->count = 1;
     42 }
     43 
     44 static inline int32_t aref_count(struct aref *r)
     45 {
     46     return r->count;
     47 }
     48 
     49 static inline void aref_get(struct aref *r)
     50 {
     51     android_atomic_inc(&r->count);
     52 }
     53 
     54 static inline void aref_put(struct aref *r, void (*release)(struct aref *))
     55 {
     56     if (android_atomic_dec(&r->count) == 1)
     57         release(r);
     58 }
     59 
     60 __END_DECLS
     61 
     62 #endif // _CUTILS_AREF_H_
     63