Home | History | Annotate | Download | only in metricsd
      1 /*
      2  * Copyright (C) 2015 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef METRICS_PERSISTENT_INTEGER_H_
     18 #define METRICS_PERSISTENT_INTEGER_H_
     19 
     20 #include <stdint.h>
     21 
     22 #include <string>
     23 
     24 #include <base/files/file_path.h>
     25 
     26 namespace chromeos_metrics {
     27 
     28 // PersistentIntegers is a named 64-bit integer value backed by a file.
     29 // The in-memory value acts as a write-through cache of the file value.
     30 // If the backing file doesn't exist or has bad content, the value is 0.
     31 
     32 class PersistentInteger {
     33  public:
     34   PersistentInteger(const std::string& name, const base::FilePath& directory);
     35 
     36   // Virtual only because of mock.
     37   virtual ~PersistentInteger();
     38 
     39   // Sets the value.  This writes through to the backing file.
     40   void Set(int64_t v);
     41 
     42   // Gets the value.  May sync from backing file first.
     43   int64_t Get();
     44 
     45   // Returns the name of the object.
     46   std::string Name() { return name_; }
     47 
     48   // Convenience function for Get() followed by Set(0).
     49   int64_t GetAndClear();
     50 
     51   // Convenience function for v = Get, Set(v + x).
     52   // Virtual only because of mock.
     53   virtual void Add(int64_t x);
     54 
     55  private:
     56   static const int kVersion = 1001;
     57 
     58   // Writes |value_| to the backing file, creating it if necessary.
     59   void Write();
     60 
     61   // Reads the value from the backing file, stores it in |value_|, and returns
     62   // true if the backing file is valid.  Returns false otherwise, and creates
     63   // a valid backing file as a side effect.
     64   bool Read();
     65 
     66   int64_t value_;
     67   int32_t version_;
     68   std::string name_;
     69   base::FilePath backing_file_path_;
     70   bool synced_;
     71 };
     72 
     73 }  // namespace chromeos_metrics
     74 
     75 #endif  // METRICS_PERSISTENT_INTEGER_H_
     76