aboutsummaryrefslogtreecommitdiff
path: root/libs/coding/files_container.cpp
blob: 83426dcd01430017c746b0222d85458bdd23dd51 (plain) (blame)
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
#include "coding/files_container.hpp"

#include "coding/file_reader.hpp"
#include "coding/internal/file_data.hpp"
#include "coding/read_write_utils.hpp"
#include "coding/varint.hpp"
#include "coding/write_to_sink.hpp"

#include <cstring>
#include <sstream>

template <typename Source, typename Info>
void Read(Source & src, Info & i)
{
  rw::Read(src, i.m_tag);

  i.m_offset = ReadVarUint<uint64_t>(src);
  i.m_size = ReadVarUint<uint64_t>(src);
}

template <typename Sink, typename Info>
void Write(Sink & sink, Info const & i)
{
  rw::Write(sink, i.m_tag);

  WriteVarUint(sink, i.m_offset);
  WriteVarUint(sink, i.m_size);
}

std::string DebugPrint(FilesContainerBase::TagInfo const & info)
{
  std::ostringstream ss;
  ss << "{ " << info.m_tag << ", " << info.m_offset << ", " << info.m_size << " }";
  return ss.str();
}

/////////////////////////////////////////////////////////////////////////////
// FilesContainerBase
/////////////////////////////////////////////////////////////////////////////

template <typename Reader>
void FilesContainerBase::ReadInfo(Reader & reader)
{
  uint64_t offset = ReadPrimitiveFromPos<uint64_t>(reader, 0);

  ReaderSource<Reader> src(reader);
  src.Skip(offset);

  rw::Read(src, m_info);
}

/////////////////////////////////////////////////////////////////////////////
// FilesContainerR
/////////////////////////////////////////////////////////////////////////////

FilesContainerR::FilesContainerR(std::string const & filePath, uint32_t logPageSize, uint32_t logPageCount)
  : m_source(std::make_unique<FileReader>(filePath, logPageSize, logPageCount))
{
  ReadInfo(m_source);
}

FilesContainerR::FilesContainerR(TReader const & file) : m_source(file)
{
  ReadInfo(m_source);
}

FilesContainerR::TReader FilesContainerR::GetReader(Tag const & tag) const
{
  TagInfo const * p = GetInfo(tag);
  if (!p)
    MYTHROW(Reader::OpenException, ("Can't find section:", GetFileName(), tag));
  return m_source.SubReader(p->m_offset, p->m_size);
}

std::unique_ptr<MemoryRegion> FilesContainerR::GetMemoryRegion(Tag const & tag) const
{
  TagInfo const * p = GetInfo(tag);
  if (!p)
    MYTHROW(Reader::OpenException, ("Can't find section:", GetFileName(), tag));
  return m_source.GetMemoryRegion(p->m_offset, p->m_size);
}

FilesContainerBase::TagInfo const * FilesContainerBase::GetInfo(Tag const & tag) const
{
  auto i = lower_bound(m_info.begin(), m_info.end(), tag, LessInfo());
  if (i != m_info.end() && i->m_tag == tag)
    return &(*i);
  else
    return 0;
}

/////////////////////////////////////////////////////////////////////////////
// FilesContainerW
/////////////////////////////////////////////////////////////////////////////

FilesContainerW::FilesContainerW(std::string const & fName, FileWriter::Op op) : m_name(fName), m_finished(false)
{
  Open(op);
}

void FilesContainerW::Open(FileWriter::Op op)
{
  m_needRewrite = true;

  switch (op)
  {
  case FileWriter::OP_WRITE_TRUNCATE: break;

  case FileWriter::OP_WRITE_EXISTING:
  {
    // read an existing service info
    FileReader reader(m_name);
    ReadInfo(reader);
  }

    // Important: in append mode we should sort info-vector by offsets
    sort(m_info.begin(), m_info.end(), LessOffset());

    // Check that all offsets are unique
#ifdef DEBUG
    for (size_t i = 1; i < m_info.size(); ++i)
      ASSERT(m_info[i - 1].m_offset < m_info[i].m_offset || m_info[i - 1].m_size == 0 || m_info[i].m_size == 0, ());
#endif
    break;

  default: ASSERT(false, ("Unsupported options")); break;
  }

  if (m_info.empty())
    StartNew();
}

void FilesContainerW::StartNew()
{
  // leave space for offset to service info
  FileWriter writer(m_name);
  uint64_t skip = 0;
  writer.Write(&skip, sizeof(skip));
  m_needRewrite = false;
}

FilesContainerW::~FilesContainerW()
{
  if (!m_finished)
    Finish();
}

uint64_t FilesContainerW::SaveCurrentSize()
{
  ASSERT(!m_finished, ());
  uint64_t const curr = FileReader(m_name).Size();
  if (!m_info.empty())
    m_info.back().m_size = curr - m_info.back().m_offset;
  return curr;
}

void FilesContainerW::DeleteSection(Tag const & tag)
{
  {
    // rewrite files on disk
    FilesContainerR contR(m_name);
    FilesContainerW contW(m_name + ".tmp");

    for (size_t i = 0; i < m_info.size(); ++i)
      if (m_info[i].m_tag != tag)
        contW.Write(contR.GetReader(m_info[i].m_tag), m_info[i].m_tag);
  }

  // swap files
  if (!base::DeleteFileX(m_name) || !base::RenameFileX(m_name + ".tmp", m_name))
    MYTHROW(RootException, ("Can't rename file", m_name, "Sharing violation or disk error!"));

  // do open to update m_info
  Open(FileWriter::OP_WRITE_EXISTING);
}

std::unique_ptr<FilesContainerWriter> FilesContainerW::GetWriter(Tag const & tag)
{
  ASSERT(!m_finished, ());

  // Stabilize the previous section's metadata.  When !m_needRewrite, the file
  // has been modified by a prior GetWriter call and the last entry's m_size is
  // still 0 (not yet computed).  SaveCurrentSize reads the current file size
  // and fills it in.  We must NOT call it when m_needRewrite is true (right
  // after Open), because the file still contains the service-info trailer and
  // the sizes loaded from that trailer are already correct.
  if (!m_needRewrite)
    SaveCurrentSize();

  auto it = find_if(m_info.begin(), m_info.end(), EqualTag(tag));
  if (it != m_info.end())
  {
    // Erase the old entry regardless of position.  The old section data stays
    // in the file as a harmless gap that is never referenced after Finish()
    // writes new service info.  This avoids calling DeleteSection, which would
    // need a valid on-disk service-info block (unavailable during a write session).
    m_info.erase(it);

    if (m_info.empty())
      StartNew();
    else
      m_needRewrite = true;
  }

  if (m_needRewrite)
  {
    m_needRewrite = false;

    ASSERT(!m_info.empty(), ());

    uint64_t const curr = m_info.back().m_offset + m_info.back().m_size;
    auto writer = std::make_unique<TruncatingFileWriter>(m_name);
    writer->Seek(curr);
    writer->WritePaddingByPos(kSectionAlignment);

    m_info.emplace_back(tag, writer->Pos());
    ASSERT_EQUAL(m_info.back().m_offset % kSectionAlignment, 0, ());
    return writer;
  }
  else
  {
    auto writer = std::make_unique<FilesContainerWriter>(m_name, FileWriter::OP_APPEND);
    writer->WritePaddingByPos(kSectionAlignment);

    m_info.emplace_back(tag, writer->Pos());
    ASSERT_EQUAL(m_info.back().m_offset % kSectionAlignment, 0, ());
    return writer;
  }
}

void FilesContainerW::Write(std::string const & fPath, Tag const & tag)
{
  Write(ModelReaderPtr(std::make_unique<FileReader>(fPath)), tag);
}

void FilesContainerW::Write(ModelReaderPtr reader, Tag const & tag)
{
  ReaderSource<ModelReaderPtr> src(reader);
  auto writer = GetWriter(tag);

  rw::ReadAndWrite(src, *writer);
}

void FilesContainerW::Write(void const * buffer, size_t size, Tag const & tag)
{
  if (size != 0)
    GetWriter(tag)->Write(buffer, size);
}

void FilesContainerW::Write(std::vector<char> const & buffer, Tag const & tag)
{
  Write(buffer.data(), buffer.size(), tag);
}

void FilesContainerW::Write(std::vector<uint8_t> const & buffer, Tag const & tag)
{
  Write(buffer.data(), buffer.size(), tag);
}

void FilesContainerW::Finish()
{
  ASSERT(!m_finished, ());

  uint64_t const curr = SaveCurrentSize();

  FileWriter writer(m_name, FileWriter::OP_WRITE_EXISTING);
  writer.Seek(0);
  WriteToSink(writer, curr);
  writer.Seek(curr);

  sort(m_info.begin(), m_info.end(), LessInfo());

  rw::Write(writer, m_info);

  m_finished = true;
}