• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef COMPONENTS_METRICS_STRUCTURED_LIB_ARENA_PERSISTENT_PROTO_H_
6 #define COMPONENTS_METRICS_STRUCTURED_LIB_ARENA_PERSISTENT_PROTO_H_
7 
8 #include <concepts>
9 #include <memory>
10 #include <type_traits>
11 
12 #include "components/metrics/structured/lib/persistent_proto_internal.h"
13 #include "third_party/protobuf/src/google/protobuf/message_lite.h"
14 
15 namespace metrics::structured {
16 
17 // A PersistentProto that stores T in an arena.
18 //
19 // The provided arena must live longer than |this| and doesn't
20 // take ownership.
21 //
22 // See comment in persistent_proto.h and persistent_proto_internal.h for more
23 // details.
24 template <class T>
requires(std::derived_from<T,google::protobuf::MessageLite>)25   requires(std::derived_from<T, google::protobuf::MessageLite>)
26 class ArenaPersistentProto : public internal::PersistentProtoInternal {
27  public:
28   ArenaPersistentProto(const base::FilePath& path,
29                        base::TimeDelta write_delay,
30                        PersistentProtoInternal::ReadCallback on_read,
31                        PersistentProtoInternal::WriteCallback on_write)
32       : internal::PersistentProtoInternal(path,
33                                           write_delay,
34                                           std::move(on_read),
35                                           std::move(on_write)) {}
36 
37   ~ArenaPersistentProto() override { DeallocProto(); }
38 
39   T* get() { return static_cast<T*>(internal::PersistentProtoInternal::get()); }
40   const T* get() const {
41     return static_cast<T*>(internal::PersistentProtoInternal::get());
42   }
43 
44   T* operator->() { return get(); }
45   const T* operator->() const { return get(); }
46 
47   T& operator*() { return *get(); }
48   const T& operator*() const { return *get(); }
49 
50   const google::protobuf::Arena* arena() const { return &arena_; }
51 
52  private:
53   google::protobuf::MessageLite* GetProto() override {
54     return google::protobuf::Arena::Create<T>(&arena_);
55   }
56 
57   google::protobuf::Arena arena_;
58 };
59 }  // namespace metrics::structured
60 
61 #endif  // COMPONENTS_METRICS_STRUCTURED_LIB_ARENA_PERSISTENT_PROTO_H_
62