Welcome to mirror list, hosted at ThFree Co, Russian Federation.

string_storage_base.cpp « platform - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2850435346a5e541c100358f2c7966b404a9ddf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "string_storage_base.hpp"

#include "coding/reader_streambuf.hpp"
#include "coding/file_reader.hpp"
#include "coding/file_writer.hpp"

#include "base/exception.hpp"
#include "base/logging.hpp"
#include "base/stl_helpers.hpp"

#include <istream>

using namespace std;

namespace
{
constexpr char kDelimChar = '=';
}  // namespace

namespace platform
{
StringStorageBase::StringStorageBase(string const & path) : m_path(path)
{
  try
  {
    LOG(LINFO, ("Settings path:", m_path));
    ReaderStreamBuf buffer(make_unique<FileReader>(m_path));
    istream stream(&buffer);

    string line;
    while (getline(stream, line))
    {
      if (line.empty())
        continue;

      size_t const delimPos = line.find(kDelimChar);
      if (delimPos == string::npos)
        continue;

      string const key = line.substr(0, delimPos);
      string const value = line.substr(delimPos + 1);
      if (!key.empty() && !value.empty())
        m_values[key] = value;
    }
  }
  catch (RootException const & ex)
  {
    LOG(LWARNING, ("Loading settings:", ex.Msg()));
  }
}

void StringStorageBase::Save() const
{
  try
  {
    FileWriter file(m_path);
    for (auto const & value : m_values)
    {
      string line(value.first);
      line += kDelimChar;
      line += value.second;
      line += '\n';
      file.Write(line.data(), line.size());
    }
  }
  catch (RootException const & ex)
  {
    // Ignore all settings saving exceptions.
    LOG(LWARNING, ("Saving settings:", ex.Msg()));
  }
}

void StringStorageBase::Clear()
{
  lock_guard<mutex> guard(m_mutex);
  m_values.clear();
  Save();
}

bool StringStorageBase::GetValue(string const & key, string & outValue) const
{
  lock_guard<mutex> guard(m_mutex);

  auto const found = m_values.find(key);
  if (found == m_values.end())
    return false;

  outValue = found->second;
  return true;
}

void StringStorageBase::SetValue(string const & key, string && value)
{
  lock_guard<mutex> guard(m_mutex);

  m_values[key] = move(value);
  Save();
}

void StringStorageBase::DeleteKeyAndValue(string const & key)
{
  lock_guard<mutex> guard(m_mutex);

  auto const found = m_values.find(key);
  if (found != m_values.end())
  {
    m_values.erase(found);
    Save();
  }
}
}  // namespace platform