From: Krzysztof Opasiak Date: Mon, 29 Jun 2015 12:10:56 +0000 (+0200) Subject: Add simple reference counting structure X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=6afdef3ba187b01fd63e8b9e4f0cadf288cdaca2;p=platform%2Fcore%2Fapi%2Fusb-host.git Add simple reference counting structure Based on kernel struct kref but with embedded pointer to release method instead of passing it in put() methods. Change-Id: Ib4a7463c5461180b9145596c3b986123f60a56bd Signed-off-by: Krzysztof Opasiak --- diff --git a/include/uref.h b/include/uref.h new file mode 100644 index 0000000..d7b09a4 --- /dev/null +++ b/include/uref.h @@ -0,0 +1,65 @@ +/* + * uref.h + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UREF_H +#define UREF_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* This is not thread safe! */ +struct uref { + unsigned refcnt; + void (*release)(struct uref *); +}; + +static inline void uref_init(struct uref *uref, void (*release)(struct uref *)) +{ + uref->refcnt = 1; + uref->release = release; +} + +static inline void uref_set_release(struct uref *uref, + void (*release)(struct uref *)) +{ + assert(uref->refcnt > 0); + uref->release = release; +} + +static inline void uref_get(struct uref *uref) +{ + assert(uref->refcnt > 0); + uref->refcnt++; +} + +static inline void uref_sub(struct uref *uref, unsigned count) +{ + assert(uref->refcnt >= count); + uref->refcnt -= count; +} + +static inline void uref_put(struct uref *uref) +{ + uref_sub(uref, 1); +} + +#ifdef __cplusplus +} +#endif + +#endif /* UREF_H */