tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

RefCounted.h (1801B)


      1 /*
      2 * Copyright 2015, Mozilla Foundation and contributors
      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 __RefCount_h__
     18 #define __RefCount_h__
     19 
     20 #include <assert.h>
     21 #include <stdint.h>
     22 
     23 #include <atomic>
     24 
     25 #include "ClearKeyUtils.h"
     26 
     27 // Note: Thread safe.
     28 class RefCounted {
     29 public:
     30  void AddRef() { ++mRefCount; }
     31 
     32  uint32_t Release() {
     33    uint32_t newCount = --mRefCount;
     34    if (!newCount) {
     35      delete this;
     36    }
     37    return newCount;
     38  }
     39 
     40 protected:
     41  RefCounted() : mRefCount(0) {}
     42  virtual ~RefCounted() { assert(!mRefCount); }
     43  std::atomic<uint32_t> mRefCount;
     44 };
     45 
     46 template <class T>
     47 class RefPtr {
     48 public:
     49  RefPtr(const RefPtr& src) { Set(src.mPtr); }
     50 
     51  explicit RefPtr(T* aPtr) { Set(aPtr); }
     52  RefPtr() { Set(nullptr); }
     53 
     54  ~RefPtr() { Set(nullptr); }
     55  T* operator->() const { return mPtr; }
     56  T** operator&() { return &mPtr; }
     57  T* operator->() { return mPtr; }
     58  operator T*() { return mPtr; }
     59 
     60  T* Get() const { return mPtr; }
     61 
     62  RefPtr& operator=(T* aVal) {
     63    Set(aVal);
     64    return *this;
     65  }
     66 
     67 private:
     68  T* Set(T* aPtr) {
     69    if (mPtr == aPtr) {
     70      return aPtr;
     71    }
     72    if (mPtr) {
     73      mPtr->Release();
     74    }
     75    mPtr = aPtr;
     76    if (mPtr) {
     77      aPtr->AddRef();
     78    }
     79    return mPtr;
     80  }
     81 
     82  T* mPtr = nullptr;
     83 };
     84 
     85 #endif  // __RefCount_h__