• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // This value is used as a max value in a histogram,
23 // Platform.ExternalMetrics.SamplesRead. If it changes, the histogram will need
24 // to be renamed.
25 inline constexpr int kMaxMessagesPerRead = 100000;
26 
27 // Deserializes a sample passed as a string and return a sample.
28 // The return value will either be a scoped_ptr to a Metric sample (if the
29 // deserialization was successful) or a nullptr scoped_ptr.
30 std::unique_ptr<MetricSample> ParseSample(const std::string& sample);
31 
32 // Reads all samples from a file and truncates the file when done.
33 void ReadAndTruncateMetricsFromFile(
34     const std::string& filename,
35     std::vector<std::unique_ptr<MetricSample>>* metrics);
36 
37 // Reads all samples from a file and deletes the file when done.
38 void ReadAndDeleteMetricsFromFile(
39     const std::string& filename,
40     std::vector<std::unique_ptr<MetricSample>>* metrics);
41 
42 // Serializes a sample and write it to filename.
43 // The format for the message is:
44 //  message_size, serialized_message
45 // where
46 //  * message_size is the total length of the message (message_size +
47 //    serialized_message) on 4 bytes
48 //  * serialized_message is the serialized version of sample (using ToString)
49 //
50 //  NB: the file will never leave the device so message_size will be written
51 //  with the architecture's endianness.
52 bool WriteMetricToFile(const MetricSample& sample, const std::string& filename);
53 
54 // Maximum length of a serialized message
55 inline constexpr size_t kMessageMaxLength = 1024;
56 
57 }  // namespace SerializationUtils
58 }  // namespace metrics
59 
60 #endif  // COMPONENTS_METRICS_SERIALIZATION_SERIALIZATION_UTILS_H_
61