blob: 7d920b5c7ca861673db4c0e5fb48cfaed3725705 [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:
19 PersistentInteger(const std::string& name);
20
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
48 // Writes |value| to the backing file, creating it if necessary.
49 void Write(int64 value);
50
51 // Reads the value from the backing file, stores it in |value_|, and returns
52 // true if the backing file is valid. Returns false otherwise.
53 bool Read();
54
55 int64 value_;
56 int32 version_;
57 std::string name_;
58 std::string backing_file_name_;
59 bool synced_;
60 static bool testing_;
61};
62
63}
64
65#endif // METRICS_PERSISTENT_INTEGER_H_