project_files/frontlib/util/refcounter.h
changeset 7271 5608ac657362
parent 7230 240620f46dd7
child 7314 6171f0bad318
equal deleted inserted replaced
7269:5b0aeef8ba2a 7271:5608ac657362
     9  */
     9  */
    10 
    10 
    11 #ifndef REFCOUNTER_H_
    11 #ifndef REFCOUNTER_H_
    12 #define REFCOUNTER_H_
    12 #define REFCOUNTER_H_
    13 
    13 
    14 #include "logging.h"
       
    15 #include <stdbool.h>
    14 #include <stdbool.h>
    16 
    15 
    17 static inline void flib_retain(int *referenceCountPtr, const char *objName) {
    16 /**
    18 	if(!referenceCountPtr || !objName) {
    17  * Pass a pointer to the counter variable to be incremented, and the name of the
    19 		flib_log_e("null parameter to flib_retain");
    18  * object for logging purposes. On overflow an error will be logged and the
    20 	} else {
    19  * counter will get "stuck" so neither retain nor release will modify it anymore.
    21 		if((*referenceCountPtr)  >= 0) {
    20  */
    22 			(*referenceCountPtr)++;
    21 void flib_retain(int *referenceCountPtr, const char *objName);
    23 			flib_log_d("retaining %s, now %i references", objName, (*referenceCountPtr));
       
    24 		}
       
    25 		if((*referenceCountPtr) < 0) {
       
    26 			flib_log_e("Memory leak: Reference count overflow in %s object!", objName);
       
    27 		}
       
    28 	}
       
    29 }
       
    30 
    22 
    31 /**
    23 /**
    32  * Returns true if the struct should be freed.
    24  * Pass a pointer to the counter variable to be decremented and the name
       
    25  * of the object for logging purposes.
       
    26  * Returns true if the object should be freed.
    33  */
    27  */
    34 static inline bool flib_release(int *referenceCountPtr, const char *objName) {
    28 bool flib_release(int *referenceCountPtr, const char *objName);
    35 	bool result = false;
       
    36 	if(!referenceCountPtr) {
       
    37 		flib_log_e("null parameter to flib_release");
       
    38 	} else if((*referenceCountPtr) > 0) {
       
    39 		if(--(*referenceCountPtr) == 0) {
       
    40 			flib_log_d("releasing and destroying %s", objName);
       
    41 			result = true;
       
    42 		} else {
       
    43 			flib_log_d("releasing %s, now %i references", objName, (*referenceCountPtr));
       
    44 		}
       
    45 	} else if((*referenceCountPtr) == 0) {
       
    46 		flib_log_e("Attempt to release a %s with zero references!", objName);
       
    47 	}
       
    48 	return result;
       
    49 }
       
    50 
    29 
    51 #endif /* REFCOUNTER_H_ */
    30 #endif /* REFCOUNTER_H_ */