aboutsummaryrefslogtreecommitdiff
path: root/libs/coding/zip_reader.hpp
blob: b4182b6c91fbda30cf87aafee37b1594a1caae31 (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
#pragma once

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

#include "base/exception.hpp"

#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>

class ZipFileReader : public FileReader
{
public:
  struct Delegate
  {
    virtual ~Delegate() = default;

    // When |size| is zero, end of file is reached.
    virtual void OnBlockUnzipped(size_t size, char const * data) = 0;

    virtual void OnStarted() {}
    virtual void OnCompleted() {}
  };

  using ProgressFn = std::function<void(uint64_t, uint64_t)>;
  /// Contains file name inside zip and it's uncompressed size
  using FileList = std::vector<std::pair<std::string, uint32_t>>;

  DECLARE_EXCEPTION(OpenZipException, OpenException);
  DECLARE_EXCEPTION(LocateZipException, OpenException);
  DECLARE_EXCEPTION(InvalidZipException, OpenException);

  ZipFileReader(std::string const & container, std::string const & file,
                uint32_t logPageSize = FileReader::kDefaultLogPageSize,
                uint32_t logPageCount = FileReader::kDefaultLogPageCount);

  /// @note Size() returns compressed file size inside zip
  uint64_t UncompressedSize() const { return m_uncompressedFileSize; }

  /// @returns true for a deflated entry, false for a stored (method 0, readable in place) one.
  bool IsCompressed() const { return m_isCompressed; }

  /// @warning Can also throw Writer::OpenException and Writer::WriteException
  static void UnzipFile(std::string const & zipContainer, std::string const & fileInZip, Delegate & delegate);
  static void UnzipFile(std::string const & zipContainer, std::string const & fileInZip, std::string const & outPath);

  static void FilesList(std::string const & zipContainer, FileList & filesList);

  /// Quick version without exceptions
  static bool IsZip(std::string const & zipContainer);

  /// Opens |fileInZip| inside |zipContainer| and returns a random-access reader for it.
  /// A stored (uncompressed) entry is read in place from the container; a deflated entry is inflated
  /// once into memory (our in-place FileReader can only read uncompressed data from the container).
  static std::unique_ptr<ModelReader> CreateModelReader(std::string const & zipContainer, std::string const & fileInZip,
                                                        uint32_t logPageSize = FileReader::kDefaultLogPageSize,
                                                        uint32_t logPageCount = FileReader::kDefaultLogPageCount);

private:
  uint64_t m_uncompressedFileSize;
  bool m_isCompressed;
};