1 // Copyright (C) 2014 The Android Open Source Project
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 #include "emugl/common/smart_ptr.h"
18 #define WIN32_LEAN_AND_MEAN
24 // Thread-safe atomic reference-counting type.
27 RefCount() : mCount(1) {}
30 // Technically not thread-safe, use only for testing.
31 int count() const { return (int)mCount; }
35 InterlockedIncrement(&mCount);
37 __sync_fetch_and_add(&mCount, 1);
43 return InterlockedDecrement(&mCount) == 0;
45 return __sync_add_and_fetch(&mCount, -1) == 0;
58 // SmartPtrBase implementation.
60 SmartPtrBase::SmartPtrBase(void* ptr) : mPtr(ptr), mRefCount(NULL) {
62 mRefCount = new RefCount();
66 SmartPtrBase::SmartPtrBase(const SmartPtrBase& other)
67 : mPtr(other.mPtr), mRefCount(other.mRefCount) {
69 mRefCount->increment();
73 int SmartPtrBase::getRefCount() const {
74 return mRefCount ? mRefCount->count() : 0;
78 void SmartPtrBase::addRef() {
80 mRefCount->increment();
84 void* SmartPtrBase::copyFrom(const SmartPtrBase& other) {
85 void* old_ptr = release();
88 mRefCount = other.mRefCount;
90 mRefCount->increment();
96 void* SmartPtrBase::release() {
98 RefCount* old_refcount = mRefCount;
104 if (old_refcount->decrement()) {