1/*
2 * Copyright (c) 2012,2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25#ifndef _SECCFRELEASE_H_
26#define _SECCFRELEASE_H_
27
28#include <CoreFoundation/CFBase.h>
29
30// Retains its argument unless it's NULL.  Always returns its argument.
31#define CFRetainSafe(CF) ({ __typeof__(CF) _cf = (CF); _cf ? (CFRetain(_cf), _cf) : _cf; })
32
33// Assume CF is NULL or an already retained object and CFReleaseSafe VAR and assigns CF to VAR. Returns CF.
34#define CFAssignRetained(VAR,CF) ({ \
35    __typeof__(VAR) *const _pvar = &(VAR); \
36    __typeof__(CF) _cf = (CF); \
37    (*_pvar) = *_pvar ? (CFRelease(*_pvar), _cf) : _cf; \
38})
39
40// CFRetainSafe CF and CFReleaseSafe VAR and assigns CF to VAR. Returns CF.
41#define CFRetainAssign(VAR,CF) ({ \
42    __typeof__(VAR) *const _pvar = &(VAR); \
43    __typeof__(CF) _cf = (CF); \
44    (((*_pvar) == _cf) ? _cf \
45    : ((*_pvar) = (_cf ? (CFRetain(_cf), (*_pvar ? (CFRelease(*_pvar), _cf) : _cf)) \
46                   : (CFRelease(*_pvar), ((__typeof__(_cf))0))))); \
47})
48
49// Releases CF unless it's NULL.  Always returns NULL, for your convenience and constructs like:
50// return CFReleaseSafe(foo);
51#define CFReleaseSafe(CF) ({ __typeof__(CF) _cf = (CF); (_cf ? (CFRelease(_cf), ((__typeof__(CF))0)) : _cf); })
52
53// Assigns NULL to CF. Releases the value stored at CF unless it was NULL.  Always returns NULL, for your convenience
54#define CFReleaseNull(CF) ({ __typeof__(CF) *const _pcf = &(CF), _cf = *_pcf; (_cf ? (*_pcf) = ((__typeof__(CF))0), (CFRelease(_cf), ((__typeof__(CF))0)) : _cf); })
55
56
57#endif /* _SECCFRELEASE_H_ */
58