blob: 4a5670cd52e41be6c4b8c69847e33d1c83f21f78 [file] [log] [blame]
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -08001// Copyright (c) 2014 The Chromium OS 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
5#ifndef METRICS_PERSISTENT_INTEGER_H_
6#define METRICS_PERSISTENT_INTEGER_H_
7
8#include <base/basictypes.h>
9#include <string>
10
11namespace chromeos_metrics {
12
13// PersistentIntegers is a named 64-bit integer value backed by a file.
14// The in-memory value acts as a write-through cache of the file value.
15// If the backing file doesn't exist or has bad content, the value is 0.
16
17class PersistentInteger {
18 public:
Bertrand SIMONNETe6cfd642014-07-09 16:35:23 -070019 explicit PersistentInteger(const std::string& name);
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080020
21 // Virtual only because of mock.
22 virtual ~PersistentInteger();
23
24 // Sets the value. This writes through to the backing file.
25 void Set(int64 v);
26
27 // Gets the value. May sync from backing file first.
28 int64 Get();
29
30 // Returns the name of the object.
31 std::string Name() { return name_; }
32
33 // Convenience function for Get() followed by Set(0).
34 int64 GetAndClear();
35
36 // Convenience function for v = Get, Set(v + x).
37 // Virtual only because of mock.
38 virtual void Add(int64 x);
39
40 // After calling with |testing| = true, changes some behavior for the purpose
41 // of testing. For instance: instances created while testing use the current
42 // directory for the backing files.
43 static void SetTestingMode(bool testing);
44
45 private:
46 static const int kVersion = 1001;
47
Luigi Semenzatoa5f4fe62014-04-15 09:31:47 -070048 // Writes |value_| to the backing file, creating it if necessary.
49 void Write();
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080050
51 // Reads the value from the backing file, stores it in |value_|, and returns
Luigi Semenzatoa5f4fe62014-04-15 09:31:47 -070052 // true if the backing file is valid. Returns false otherwise, and creates
53 // a valid backing file as a side effect.
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080054 bool Read();
55
56 int64 value_;
57 int32 version_;
58 std::string name_;
59 std::string backing_file_name_;
60 bool synced_;
61 static bool testing_;
62};
63
Bertrand SIMONNETe6cfd642014-07-09 16:35:23 -070064} // namespace chromeos_metrics
Luigi Semenzato2fd51cc2014-02-26 11:53:16 -080065
66#endif // METRICS_PERSISTENT_INTEGER_H_