Lightweight 0.20251202.0
Loading...
Searching...
No Matches
ZipEntry.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5#include "../Api.hpp"
6#include "ZipError.hpp"
7
8#include <cstddef>
9#include <cstdint>
10#include <expected>
11#include <span>
12#include <vector>
13
14#if defined(__clang__)
15 #pragma clang diagnostic push
16 #pragma clang diagnostic ignored "-Wnullability-extension"
17#endif
18#include <zip.h>
19#if defined(__clang__)
20 #pragma clang diagnostic pop
21#endif
22
23namespace Lightweight::Zip
24{
25
26class ZipArchive;
27
28/// RAII wrapper for a ZIP entry file handle (zip_file_t*).
29///
30/// This class provides safe, scoped access to a single entry within a ZIP archive.
31/// The entry is automatically closed when the ZipEntry object is destroyed.
32///
33/// ZipEntry objects are non-copyable but movable.
34class LIGHTWEIGHT_API ZipEntry final
35{
36 public:
37 ZipEntry(ZipEntry const&) = delete;
38 ZipEntry& operator=(ZipEntry const&) = delete;
39
40 /// Move constructor. Transfers ownership of the file handle.
41 ZipEntry(ZipEntry&& other) noexcept;
42
43 /// Move assignment operator. Transfers ownership of the file handle.
44 ZipEntry& operator=(ZipEntry&& other) noexcept;
45
46 /// Destructor. Closes the entry if open.
47 ~ZipEntry() noexcept;
48
49 /// Checks if the entry is currently open.
50 ///
51 /// @return true if the entry is open, false otherwise.
52 [[nodiscard]] bool IsOpen() const noexcept;
53
54 /// Reads data from the entry into a buffer.
55 ///
56 /// @param buffer The buffer to read into.
57 /// @return The number of bytes read, or a ZipError on failure.
58 [[nodiscard]] std::expected<size_t, ZipError> Read(std::span<uint8_t> buffer);
59
60 /// Reads all data from the entry.
61 ///
62 /// @param expectedSize The expected size of the entry in bytes.
63 /// @return A vector containing all entry data, or a ZipError on failure.
64 [[nodiscard]] std::expected<std::vector<uint8_t>, ZipError> ReadAll(size_t expectedSize);
65
66 /// Closes the entry.
67 void Close() noexcept;
68
69 private:
70 friend class ZipArchive;
71
72 /// Private constructor. Only ZipArchive can create ZipEntry objects.
73 ///
74 /// @param file The libzip file handle.
75 explicit ZipEntry(zip_file_t* file) noexcept;
76
77 zip_file_t* m_file {};
78};
79
80} // namespace Lightweight::Zip
~ZipEntry() noexcept
Destructor. Closes the entry if open.
ZipEntry(ZipEntry &&other) noexcept
Move constructor. Transfers ownership of the file handle.
ZipEntry & operator=(ZipEntry &&other) noexcept
Move assignment operator. Transfers ownership of the file handle.
Represents an error that occurred during a ZIP operation.
Definition ZipError.hpp:34