blob: 453a22e8e4f6ac286412a4f864690cbcac7bea52 [file] [log] [blame]
perkj8ff860a2016-10-03 00:30:04 -07001/*
2 * Copyright 2016 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/weak_ptr.h"
perkj8ff860a2016-10-03 00:30:04 -070012
13// The implementation is borrowed from chromium except that it does not
14// implement SupportsWeakPtr.
15
16namespace rtc {
17namespace internal {
18
19WeakReference::Flag::Flag() : is_valid_(true) {
20 // Flags only become bound when checked for validity, or invalidated,
21 // so that we can check that later validity/invalidation operations on
22 // the same Flag take place on the same sequence.
23 checker_.Detach();
24}
25
26void WeakReference::Flag::Invalidate() {
27 RTC_DCHECK(checker_.CalledSequentially())
28 << "WeakPtrs must be invalidated on the same sequence.";
29 is_valid_ = false;
30}
31
32bool WeakReference::Flag::IsValid() const {
33 RTC_DCHECK(checker_.CalledSequentially())
34 << "WeakPtrs must be checked on the same sequence.";
35 return is_valid_;
36}
37
38WeakReference::Flag::~Flag() {}
39
40WeakReference::WeakReference() {}
41
42WeakReference::WeakReference(const Flag* flag) : flag_(flag) {}
43
44WeakReference::~WeakReference() {}
45
46WeakReference::WeakReference(WeakReference&& other) = default;
47
48WeakReference::WeakReference(const WeakReference& other) = default;
49
50bool WeakReference::is_valid() const {
51 return flag_.get() && flag_->IsValid();
52}
53
54WeakReferenceOwner::WeakReferenceOwner() {
55 checker_.Detach();
56}
57
58WeakReferenceOwner::~WeakReferenceOwner() {
59 RTC_DCHECK(checker_.CalledSequentially());
60 Invalidate();
61}
62
63WeakReference WeakReferenceOwner::GetRef() const {
64 RTC_DCHECK(checker_.CalledSequentially());
65 // If we hold the last reference to the Flag then create a new one.
66 if (!HasRefs())
67 flag_ = new RefCountedObject<WeakReference::Flag>();
68
69 return WeakReference(flag_.get());
70}
71
72void WeakReferenceOwner::Invalidate() {
73 RTC_DCHECK(checker_.CalledSequentially());
74 if (flag_.get()) {
75 flag_->Invalidate();
deadbeef37f5ecf2017-02-27 14:06:41 -080076 flag_ = nullptr;
perkj8ff860a2016-10-03 00:30:04 -070077 }
78}
79
80WeakPtrBase::WeakPtrBase() {}
81
82WeakPtrBase::~WeakPtrBase() {}
83
84WeakPtrBase::WeakPtrBase(const WeakReference& ref) : ref_(ref) {}
85
86} // namespace internal
87} // namespace rtc