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

query_saver.cpp « search - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2cf765d87ed4ccc9e2e37584a41ee16d1bd71587 (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
#include "query_saver.hpp"

#include "platform/settings.hpp"

#include "coding/hex.hpp"
#include "coding/reader.hpp"
#include "coding/writer.hpp"

namespace
{
size_t constexpr kMaxSuggestCount = 10;
char constexpr kSettingsKey[] = "UserQueries";
}  // namespace

namespace search
{
QuerySaver::QuerySaver()
{
  Load();
}

void QuerySaver::SaveNewQuery(string const & query)
{
  if (query.empty())
    return;

  // Remove items if needed.
  auto const it = find(m_topQueries.begin(), m_topQueries.end(), query);
  if (it != m_topQueries.end())
    m_topQueries.erase(it);
  else if (m_topQueries.size() >= kMaxSuggestCount)
    m_topQueries.pop_back();

  // Add new query and save it to drive.
  m_topQueries.push_front(query);
  Save();
}

void QuerySaver::Clear()
{
  m_topQueries.clear();
  Settings::Delete(kSettingsKey);
}

void QuerySaver::Serialize(vector<char> & data) const
{
  data.clear();
  MemWriter<vector<char>> writer(data);
  uint16_t size = m_topQueries.size();
  writer.Write(&size, 2);
  for (auto const & query : m_topQueries)
  {
    size = query.size();
    writer.Write(&size, 2);
    writer.Write(query.c_str(), size);
  }
}

void QuerySaver::Deserialize(string const & data)
{
  MemReader reader(data.c_str(), data.size());

  uint16_t queriesCount;
  reader.Read(0 /* pos */, &queriesCount, 2);

  size_t pos = 2;
  for (int i = 0; i < queriesCount; ++i)
  {
    uint16_t stringLength;
    reader.Read(pos, &stringLength, 2);
    pos += 2;
    vector<char> str(stringLength);
    reader.Read(pos, &str[0], stringLength);
    pos += stringLength;
    m_topQueries.emplace_back(&str[0], stringLength);
  }
}

void QuerySaver::Save()
{
  vector<char> data;
  Serialize(data);
  string hexData = ToHex(&data[0], data.size());
  Settings::Set(kSettingsKey, hexData);
}

void QuerySaver::Load()
{
  string hexData;
  Settings::Get(kSettingsKey, hexData);
  if (hexData.empty())
    return;
  string rawData = FromHex(hexData);
  Deserialize(rawData);
}
}  // namesapce search