xref: /aosp_15_r20/external/cronet/components/metrics/serialization/serialization_utils.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2014 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_SERIALIZATION_SERIALIZATION_UTILS_H_
6 #define COMPONENTS_METRICS_SERIALIZATION_SERIALIZATION_UTILS_H_
7 
8 #include <memory>
9 #include <string>
10 #include <vector>
11 
12 namespace metrics {
13 
14 class MetricSample;
15 
16 // Metrics helpers to serialize and deserialize metrics collected by
17 // ChromeOS.
18 namespace SerializationUtils {
19 
20 // If there are more than 100,000 messages in the file, discard the remaining
21 // messages to avoid running out of memory.
22 extern const int kMaxMessagesPerRead;
23 
24 // Deserializes a sample passed as a string and return a sample.
25 // The return value will either be a scoped_ptr to a Metric sample (if the
26 // deserialization was successful) or a nullptr scoped_ptr.
27 std::unique_ptr<MetricSample> ParseSample(const std::string& sample);
28 
29 // Reads all samples from a file and truncates the file when done.
30 void ReadAndTruncateMetricsFromFile(
31     const std::string& filename,
32     std::vector<std::unique_ptr<MetricSample>>* metrics);
33 
34 // Reads all samples from a file and deletes the file when done.
35 void ReadAndDeleteMetricsFromFile(
36     const std::string& filename,
37     std::vector<std::unique_ptr<MetricSample>>* metrics);
38 
39 // Serializes a sample and write it to filename.
40 // The format for the message is:
41 //  message_size, serialized_message
42 // where
43 //  * message_size is the total length of the message (message_size +
44 //    serialized_message) on 4 bytes
45 //  * serialized_message is the serialized version of sample (using ToString)
46 //
47 //  NB: the file will never leave the device so message_size will be written
48 //  with the architecture's endianness.
49 bool WriteMetricToFile(const MetricSample& sample, const std::string& filename);
50 
51 // Maximum length of a serialized message
52 static const size_t kMessageMaxLength = 1024;
53 
54 }  // namespace SerializationUtils
55 }  // namespace metrics
56 
57 #endif  // COMPONENTS_METRICS_SERIALIZATION_SERIALIZATION_UTILS_H_
58