node_attached_data.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2019 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.
  4. #ifndef COMPONENTS_PERFORMANCE_MANAGER_GRAPH_NODE_ATTACHED_DATA_H_
  5. #define COMPONENTS_PERFORMANCE_MANAGER_GRAPH_NODE_ATTACHED_DATA_H_
  6. #include "base/check_op.h"
  7. #include "base/memory/raw_ptr.h"
  8. #include "components/performance_manager/graph/node_base.h"
  9. #include "components/performance_manager/public/graph/node_attached_data.h"
  10. namespace performance_manager {
  11. // Helper class for providing internal storage of a NodeAttachedData
  12. // implementation directly in a node. The storage is provided as a raw buffer of
  13. // bytes which is initialized externally by the NodeAttachedDataImpl via a
  14. // placement new. In this way the node only needs to know about the
  15. // NodeAttachedData base class, and the size of the required storage.
  16. template <size_t DataSize>
  17. class InternalNodeAttachedDataStorage {
  18. public:
  19. static constexpr size_t kDataSize = DataSize;
  20. InternalNodeAttachedDataStorage() {}
  21. InternalNodeAttachedDataStorage(const InternalNodeAttachedDataStorage&) =
  22. delete;
  23. InternalNodeAttachedDataStorage& operator=(
  24. const InternalNodeAttachedDataStorage&) = delete;
  25. ~InternalNodeAttachedDataStorage() { Reset(); }
  26. operator bool() const { return data_; }
  27. // Returns a pointer to the data object, if allocated.
  28. NodeAttachedData* Get() { return data_; }
  29. void Reset() {
  30. if (data_)
  31. data_->~NodeAttachedData();
  32. data_ = nullptr;
  33. }
  34. uint8_t* buffer() { return buffer_; }
  35. protected:
  36. friend class InternalNodeAttachedDataStorageAccess;
  37. // Transitions this object to being allocated.
  38. void Set(NodeAttachedData* data) {
  39. DCHECK(!data_);
  40. // Depending on the object layout, once it has been cast to a
  41. // NodeAttachedData there's no guarantee that the pointer will be at the
  42. // head of the object, only that the pointer will be somewhere inside of the
  43. // full object extent.
  44. DCHECK_LE(buffer_, reinterpret_cast<uint8_t*>(data));
  45. DCHECK_GT(buffer_ + kDataSize, reinterpret_cast<uint8_t*>(data));
  46. data_ = data;
  47. }
  48. private:
  49. raw_ptr<NodeAttachedData> data_ = nullptr;
  50. uint8_t buffer_[kDataSize];
  51. };
  52. } // namespace performance_manager
  53. #endif // COMPONENTS_PERFORMANCE_MANAGER_GRAPH_NODE_ATTACHED_DATA_H_