[Extensions] Add metrics for UserScriptListener
[chromium-blink-merge.git] / ios / web / weak_nsobject_counter.mm
blobbd14b7b3f0180ae2cd6d7d7dd95883617d343be8
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "ios/web/weak_nsobject_counter.h"
7 #import <objc/runtime.h>
9 #include "base/logging.h"
10 #import "base/mac/scoped_nsobject.h"
12 namespace {
13 // The key needed for objc_setAssociatedObject. Any value will do, because the
14 // address is the key.
15 const char kObserverAssociatedObjectKey = 'h';
18 // Used for observing the objects tracked in the WeakNSObjectCounter. This
19 // object will be dealloced when the tracked object is dealloced and will
20 // notify the shared counter.
21 @interface CRBWeakNSObjectDeallocationObserver : NSObject
22 // Designated initializer. |object| cannot be nil. It registers self as an
23 // associated object to |object|.
24 - (instancetype)initWithSharedCounter:(const linked_ptr<NSUInteger>&)counter
25                    objectToBeObserved:(id)object;
26 @end
28 @implementation CRBWeakNSObjectDeallocationObserver {
29   linked_ptr<NSUInteger> _counter;
32 - (instancetype)init {
33   NOTREACHED();
34   return nil;
37 - (instancetype)initWithSharedCounter:(const linked_ptr<NSUInteger>&)counter
38                    objectToBeObserved:(id)object {
39   self = [super init];
40   if (self) {
41     DCHECK(counter.get());
42     DCHECK(object);
43     _counter = counter;
44     objc_setAssociatedObject(object, &kObserverAssociatedObjectKey, self,
45                              OBJC_ASSOCIATION_RETAIN);
46     (*_counter)++;
47   }
48   return self;
51 - (void)dealloc {
52   DCHECK(_counter.get());
53   (*_counter)--;
54   _counter.reset();
55   [super dealloc];
58 @end
60 namespace web {
62 WeakNSObjectCounter::WeakNSObjectCounter() : counter_(new NSUInteger(0)) {
65 WeakNSObjectCounter::~WeakNSObjectCounter() {
66   DCHECK(CalledOnValidThread());
69 void WeakNSObjectCounter::Insert(id object) {
70   DCHECK(CalledOnValidThread());
71   DCHECK(object);
72   // Create an associated object and register it with |object|.
73   base::scoped_nsobject<CRBWeakNSObjectDeallocationObserver> observingObject(
74       [[CRBWeakNSObjectDeallocationObserver alloc]
75           initWithSharedCounter:counter_ objectToBeObserved:object]);
78 NSUInteger WeakNSObjectCounter::Size() const {
79   DCHECK(CalledOnValidThread());
80   return *counter_;
83 }  // namespace web