xref: /aosp_15_r20/external/cronet/components/metrics/structured/lib/arena_persistent_proto.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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(google::protobuf::Arena* arena,
29                        const base::FilePath& path,
30                        base::TimeDelta write_delay,
31                        PersistentProtoInternal::ReadCallback on_read,
32                        PersistentProtoInternal::WriteCallback on_write)
33       : internal::PersistentProtoInternal(path,
34                                           write_delay,
35                                           std::move(on_read),
36                                           std::move(on_write)) {
37     handle_ = google::protobuf::Arena::Create<T>(arena_);
38   }
39 
40   ~ArenaPersistentProto() override { DeallocProto(); }
41 
42   T* get() { return static_cast<T*>(internal::PersistentProtoInternal::get()); }
43   const T* get() const {
44     return static_cast<T*>(internal::PersistentProtoInternal::get());
45   }
46 
47   T* operator->() { return get(); }
48   const T* operator->() const { return get(); }
49 
50   T& operator*() { return *get(); }
51   const T& operator*() const { return *get(); }
52 
53  private:
54   google::protobuf::MessageLite* GetProto() override { return handle_; }
55 
56   raw_ptr<T> handle_;
57   raw_ptr<google::protobuf::Arena> arena_;
58 };
59 }  // namespace metrics::structured
60 
61 #endif  // COMPONENTS_METRICS_STRUCTURED_LIB_ARENA_PERSISTENT_PROTO_H_
62