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

string_file.hpp « indexer - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d2c888917c2d1f4d8ac65c360a2ca90ec4725e10 (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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#pragma once

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

#include "base/macros.hpp"
#include "base/mem_trie.hpp"
#include "base/string_utils.hpp"
#include "base/worker_thread.hpp"

#include "coding/read_write_utils.hpp"
#include "std/iterator_facade.hpp"
#include "std/queue.hpp"
#include "std/functional.hpp"
#include "std/unique_ptr.hpp"

template <typename TValue>
class StringsFile
{
public:
  using ValueT = TValue;
  using IdT = uint32_t;

  class TString
  {
    strings::UniString m_name;
    ValueT m_val;

  public:
    TString() {}
    TString(strings::UniString const & name, signed char lang, ValueT const & val) : m_val(val)
    {
      m_name.reserve(name.size() + 1);
      m_name.push_back(static_cast<uint8_t>(lang));
      m_name.append(name.begin(), name.end());
    }

    TString(strings::UniString const & langName, ValueT const & val) : m_name(langName), m_val(val)
    {
    }

    uint32_t GetKeySize() const { return m_name.size(); }
    uint32_t const * GetKeyData() const { return m_name.data(); }

    strings::UniString const & GetString() const { return m_name; }

    ValueT const & GetValue() const { return m_val; }

    bool operator<(TString const & name) const
    {
      if (m_name != name.m_name)
        return m_name < name.m_name;
      return m_val < name.m_val;
    }

    bool operator==(TString const & name) const
    {
      return m_name == name.m_name && m_val == name.m_val;
    }

    template <class TWriter>
    IdT Write(TWriter & writer) const
    {
      IdT const pos = static_cast<IdT>(writer.Pos());
      CHECK_EQUAL(static_cast<uint64_t>(pos), writer.Pos(), ());

      rw::Write(writer, m_name);
      m_val.Write(writer);

      return pos;
    }

    template <class TReader>
    void Read(TReader & src)
    {
      rw::Read(src, m_name);
      m_val.Read(src);
    }

    inline void const * value_data() const { return m_val.data(); }

    inline size_t value_size() const { return m_val.size(); }

    void Swap(TString & r)
    {
      m_name.swap(r.m_name);
      m_val.swap(r.m_val);
    }
  };

  using StringsListT = vector<TString>;

  // Contains start and end offsets of file portions.
  using OffsetsListT = vector<pair<uint64_t, uint64_t>>;

  /// This class encapsulates a task to efficiently sort a bunch of
  /// strings and writes them in a sorted oreder.
  class SortAndDumpStringsTask
  {
  public:
    /// A class ctor.
    ///
    /// \param writer A writer that will be used to write strings.
    /// \param offsets A list of offsets [begin, end) that denote
    ///                groups of sorted strings in a file.  When strings will be
    ///                sorted and dumped on a disk, a pair of offsets will be added
    ///                to the list.
    /// \param strings Vector of strings that should be sorted. Internal data is moved out from
    ///                strings, so it'll become empty after ctor.
    SortAndDumpStringsTask(FileWriter & writer, OffsetsListT & offsets, StringsListT & strings)
        : m_writer(writer), m_offsets(offsets)
    {
      strings.swap(m_strings);
    }

    /// Sorts strings via in-memory trie and writes them.
    void operator()()
    {
      vector<uint8_t> memBuffer;
      {
        my::MemTrie<strings::UniString, ValueT> trie;
        for (auto const & s : m_strings)
          trie.Add(s.GetString(), s.GetValue());
        MemWriter<vector<uint8_t>> memWriter(memBuffer);
        trie.ForEach([&memWriter](const strings::UniString & s, const ValueT & v)
                     {
                       rw::Write(memWriter, s);
                       v.Write(memWriter);
                     });
      }

      uint64_t const spos = m_writer.Pos();
      m_writer.Write(memBuffer.data(), memBuffer.size());
      uint64_t const epos = m_writer.Pos();
      m_offsets.push_back(make_pair(spos, epos));
      m_writer.Flush();
    }

  private:
    FileWriter & m_writer;
    OffsetsListT & m_offsets;
    StringsListT m_strings;

    DISALLOW_COPY_AND_MOVE(SortAndDumpStringsTask);
  };

  class IteratorT : public iterator_facade<IteratorT, TString, forward_traversal_tag, TString>
  {
    StringsFile & m_file;
    bool m_end;

    bool IsEnd() const;
    inline bool IsValid() const { return (!m_end && !IsEnd()); }

  public:
    IteratorT(StringsFile & file, bool isEnd) : m_file(file), m_end(isEnd)
    {
      // Additional check in case for empty sequence.
      if (!m_end)
        m_end = IsEnd();
    }

    TString dereference() const;
    bool equal(IteratorT const & r) const { return (m_end == r.m_end); }
    void increment();
  };

  StringsFile(string const & fPath);

  void EndAdding();
  void OpenForRead();

  /// @precondition Should be opened for writing.
  void AddString(TString const & s);

  IteratorT Begin() { return IteratorT(*this, false); }
  IteratorT End() { return IteratorT(*this, true); }

private:
  unique_ptr<FileWriter> m_writer;
  unique_ptr<FileReader> m_reader;

  void Flush();
  bool PushNextValue(size_t i);

  StringsListT m_strings;
  OffsetsListT m_offsets;

  // A worker thread that sorts and writes groups of strings.  The
  // whole process looks like a pipeline, i.e. main thread accumulates
  // strings while worker thread sequentially sorts and stores groups
  // of strings on a disk.
  my::WorkerThread<SortAndDumpStringsTask> m_workerThread;

  struct QValue
  {
    TString m_string;
    size_t m_index;

    QValue(TString const & s, size_t i) : m_string(s), m_index(i) {}

    inline bool operator>(QValue const & rhs) const { return !(m_string < rhs.m_string); }
  };

  priority_queue<QValue, vector<QValue>, greater<QValue>> m_queue;
};

template <typename ValueT>
void StringsFile<ValueT>::AddString(TString const & s)
{
  size_t const kMaxSize = 1000000;

  if (m_strings.size() >= kMaxSize)
    Flush();

  m_strings.push_back(s);
}

template <typename ValueT>
bool StringsFile<ValueT>::IteratorT::IsEnd() const
{
  return m_file.m_queue.empty();
}

template <typename ValueT>
typename StringsFile<ValueT>::TString StringsFile<ValueT>::IteratorT::dereference() const
{
  ASSERT(IsValid(), ());
  return m_file.m_queue.top().m_string;
}

template <typename ValueT>
void StringsFile<ValueT>::IteratorT::increment()
{
  ASSERT(IsValid(), ());
  int const index = m_file.m_queue.top().m_index;

  m_file.m_queue.pop();

  if (!m_file.PushNextValue(index))
    m_end = IsEnd();
}

template <typename ValueT>
StringsFile<ValueT>::StringsFile(string const & fPath)
    : m_workerThread(1 /* maxTasks */)
{
  m_writer.reset(new FileWriter(fPath));
}

template <typename ValueT>
void StringsFile<ValueT>::Flush()
{
  shared_ptr<SortAndDumpStringsTask> task(
      new SortAndDumpStringsTask(*m_writer, m_offsets, m_strings));
  m_workerThread.Push(task);
}

template <typename ValueT>
bool StringsFile<ValueT>::PushNextValue(size_t i)
{
  // reach the end of the portion file
  if (m_offsets[i].first >= m_offsets[i].second)
    return false;

  // init source to needed offset
  ReaderSource<FileReader> src(*m_reader);
  src.Skip(m_offsets[i].first);

  // read string
  TString s;
  s.Read(src);

  // update offset
  m_offsets[i].first = src.Pos();

  // push value to queue
  m_queue.push(QValue(s, i));
  return true;
}

template <typename ValueT>
void StringsFile<ValueT>::EndAdding()
{
  Flush();

  m_workerThread.RunUntilIdleAndStop();

  m_writer->Flush();
}

template <typename ValueT>
void StringsFile<ValueT>::OpenForRead()
{
  string const fPath = m_writer->GetName();
  m_writer.reset();

  m_reader.reset(new FileReader(fPath));

  for (size_t i = 0; i < m_offsets.size(); ++i)
    PushNextValue(i);
}