Bug 1910362 - Create new Nimbus helper r=aaronmt,ohorvath
[gecko.git] / xpcom / base / SizeOfState.h
blob2df0b24e93f5edaf9e3bf6f31c66ce44d186897e
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef SizeOfState_h
8 #define SizeOfState_h
10 #include "mozilla/fallible.h"
11 #include "mozilla/MemoryReporting.h"
12 #include "mozilla/Unused.h"
13 #include "nsTHashtable.h"
14 #include "nsHashKeys.h"
16 // This file includes types that are useful during memory reporting, but which
17 // cannot be put into mfbt/MemoryReporting.h because they depend on things that
18 // are not in MFBT.
20 namespace mozilla {
22 // A table of seen pointers. Useful when measuring structures that contain
23 // nodes that may be pointed to from multiple places, e.g. via RefPtr (in C++
24 // code) or Arc (in Rust code).
25 class SeenPtrs : public nsTHashtable<nsPtrHashKey<const void>> {
26 public:
27 // Returns true if we have seen this pointer before, false otherwise. Also
28 // remembers this pointer for later queries.
29 bool HaveSeenPtr(const void* aPtr) {
30 uint32_t oldCount = Count();
32 mozilla::Unused << PutEntry(aPtr, fallible);
34 // If the counts match, there are two possibilities.
36 // - Lookup succeeded: we've seen the pointer before, and didn't need to
37 // add a new entry.
39 // - PutEntry() tried to add the entry and failed due to lack of memory. In
40 // this case we can't tell if this pointer has been seen before (because
41 // the table is in an unreliable state and may have dropped previous
42 // insertions). When doing memory reporting it's better to err on the
43 // side of under-reporting rather than over-reporting, so we assume we've
44 // seen the pointer before.
46 return oldCount == Count();
50 // Memory reporting state. Some memory measuring functions
51 // (SizeOfIncludingThis(), etc.) just need a MallocSizeOf parameter, but some
52 // also need a record of pointers that have been seen and should not be
53 // re-measured. This class encapsulates both of those things.
54 class SizeOfState {
55 public:
56 explicit SizeOfState(MallocSizeOf aMallocSizeOf)
57 : mMallocSizeOf(aMallocSizeOf) {}
59 bool HaveSeenPtr(const void* aPtr) { return mSeenPtrs.HaveSeenPtr(aPtr); }
61 MallocSizeOf mMallocSizeOf;
62 SeenPtrs mSeenPtrs;
65 } // namespace mozilla
67 #endif // SizeOfState_h