Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ endif ()

# ========= Core Library =========
set(CORE_SOURCES
src/core/archive_reader.cpp
src/core/block_store.cpp
src/core/file_format.cpp
src/core/file_handle.cpp
Expand Down Expand Up @@ -187,6 +188,7 @@ if (BUILD_TEST)
include(GoogleTest)

set(TEST_SOURCES
test/cases/test_archive_reader.cpp
test/cases/test_block_store.cpp
test/cases/test_cli.cpp
test/cases/test_compress.cpp
Expand Down Expand Up @@ -292,10 +294,9 @@ endif()

# Public headers only. Internal headers under src/ and api/ are implementation
# details and are deliberately not installed.
install(FILES
${PROJECT_SOURCE_DIR}/include/ctar/ctar.h
${PROJECT_SOURCE_DIR}/include/ctar/version.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/ctar
install(DIRECTORY
${PROJECT_SOURCE_DIR}/include/ctar
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)

install(EXPORT ${PROJECT_NAME}Targets
Expand Down
28 changes: 26 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,32 @@ target_link_libraries(app PRIVATE ctar::ctar)

The installed `libctar.a` bundles LZ4 and xxhash, so no separate compression library is needed. Only the
headers under `include/ctar/` are public; `src/` and `api/` headers are internal and are not installed. The
current public API exposes version information; the archive read API is tracked in #101. The bundled
`LZ4_*`/`XXH*` symbols are part of `libctar.a` and may collide with a consumer's own copies of those libraries.
bundled `LZ4_*`/`XXH*` symbols are part of `libctar.a` and may collide with a consumer's own copies of those
libraries.

### Reading an archive from C++

```cpp
#include <ctar/ctar.h>

auto reader = ctar::ArchiveReader::Open("pack_file.ctar");
if (!reader)
{
// reader.error().code, reader.error().message
}

auto entries = reader->List("/", /*recursive=*/true);
auto info = reader->Stat("/hello.txt");
auto data = reader->ReadFile("/image.jpg"); // std::shared_ptr<const ctar::Buffer>
auto file = reader->OpenFile("/data.parquet");
char buf[4096];
file->ReadAt(0, buf);
```

Reading one file touches only that file's stored bytes; `.parquet`, `.jpeg` and other suffix-listed entries
are stored raw and are returned without decompression. Compressed files are decompressed and verified
against the archive's XXH64 before being returned. `ReaderOptions` bounds the metadata size and the
per-file size (`0` disables the limit). Nothing is extracted to disk.

**Not supported**: Windows, Intel Macs, arm64 Linux, systems with glibc older than 2.28 (such as CentOS 7), and
musl-based distributions such as Alpine.
Expand Down
25 changes: 24 additions & 1 deletion README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,9 +339,32 @@ target_link_libraries(app PRIVATE ctar::ctar)
```

安装的 `libctar.a` 已内置 LZ4 和 xxhash,不需要额外安装压缩库。只有 `include/ctar/` 下的头文件是公共的;
`src/` 和 `api/` 下的头文件属于内部实现,不会安装。当前公共 API 只提供版本信息,归档读取 API 见 #101。
`src/` 和 `api/` 下的头文件属于内部实现,不会安装。
内置的 `LZ4_*`/`XXH*` 符号属于 `libctar.a`,可能与使用方自己的同名库冲突。

### 在 C++ 中读取归档

```cpp
#include <ctar/ctar.h>

auto reader = ctar::ArchiveReader::Open("pack_file.ctar");
if (!reader)
{
// reader.error().code, reader.error().message
}

auto entries = reader->List("/", /*recursive=*/true);
auto info = reader->Stat("/hello.txt");
auto data = reader->ReadFile("/image.jpg"); // std::shared_ptr<const ctar::Buffer>
auto file = reader->OpenFile("/data.parquet");
char buf[4096];
file->ReadAt(0, buf);
```

读取单个文件只访问该文件自身存储的字节;`.parquet`、`.jpeg` 等后缀列表中的文件以原始形式存储,
返回时无需解压。压缩文件会解压并按归档中的 XXH64 校验后再返回。`ReaderOptions` 可限制 metadata
大小和单文件大小(`0` 表示不限制)。整个过程不会解压到磁盘。

**暂不支持**:Windows、Intel Mac、arm64 Linux、glibc 低于 2.28 的系统(如 CentOS 7),以及使用 musl 的系统(如 Alpine)。

### Sanitizer 构建
Expand Down
2 changes: 1 addition & 1 deletion doc/file_format.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ The reader rejects archives that violate these cross-field invariants; a writer

- `file_ids` are strictly increasing within a block, so a block cannot reference the same file twice.
- File ranges (`file_offsets` + `file_compressed_sizes`) are ordered, non-overlapping, and fit inside `payload_size`.
- For `kLZ4`/`kLZ4HC`, `file_orig_sizes` and `file_compressed_sizes` fit the LZ4 `int` API, `file_orig_sizes <= 255 * file_compressed_sizes`, and a zero original size requires a zero stored size.
- For `kLZ4`/`kLZ4HC`, `file_orig_sizes` and `file_compressed_sizes` fit the LZ4 `int` API, `file_orig_sizes <= 255 * file_compressed_sizes`, a zero original size requires a zero stored size, and the stored size must be strictly smaller than the original size (the packer stores the file raw when compression does not shrink it).
- Every `file_ids[i]` exists in `file_entry_records`; the entry's `block_id`, `file_orig_size`, `file_compressed_size` and absolute `file_offset` agree with the block, and every indexed file is referenced exactly once.
- Directory paths are unique, and a directory contains no duplicate file names, so every extracted file has a distinct output path.
- The directory index must form a tree rooted at `kRootDirId` (1): every non-root directory appears exactly once as a child, no directory is its own ancestor, and every directory is reachable from the root. The rendering commands (`tree`, `ls`, `dump`) additionally reject trees deeper than 128 to bound their recursion; `unpack` and `stat` do not apply that limit.
Expand Down
2 changes: 1 addition & 1 deletion doc/file_format_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ data_block_meta[data_block_count]

- 块内 `file_ids` 严格递增,同一块不能引用同一个文件两次。
- 文件区间(`file_offsets` + `file_compressed_sizes`)有序、互不重叠,且都位于 `payload_size` 内。
- 对 `kLZ4`/`kLZ4HC`,`file_orig_sizes` 和 `file_compressed_sizes` 必须落在 LZ4 的 `int` API 范围内,`file_orig_sizes <= 255 * file_compressed_sizes`,且原始大小为 0 时存储大小也必须为 0。
- 对 `kLZ4`/`kLZ4HC`,`file_orig_sizes` 和 `file_compressed_sizes` 必须落在 LZ4 的 `int` API 范围内,`file_orig_sizes <= 255 * file_compressed_sizes`,原始大小为 0 时存储大小也必须为 0,且存储大小必须严格小于原始大小(压缩没有变小时打包器会存原始数据)。
- 每个 `file_ids[i]` 都必须存在于 `file_entry_records`,其 `block_id`、`file_orig_size`、`file_compressed_size` 和绝对 `file_offset` 与块元数据一致;所有索引文件都必须被且仅被引用一次。
- 目录路径唯一,同一目录内文件名唯一,保证每个解压文件有唯一的输出路径。
- 目录索引必须是以 `kRootDirId`(1)为根的树:每个非 root 目录恰好出现一次作为子节点,任何目录都不是自己的祖先,所有目录都能从 root 到达。渲染命令(`tree`、`ls`、`dump`)额外拒绝深度超过 128 的树以限制递归;`unpack` 和 `stat` 不施加该限制。空 data block 是非法的。
Expand Down
6 changes: 2 additions & 4 deletions include/ctar/ctar.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@
// Only public, self-contained headers belong here. Internal headers under
// src/ and api/ are not installed and must never be included from this file.
//
// The public surface currently exposes version information only; the archive
// read API (ctar::ArchiveReader) is tracked in issue #101 and will be added
// here without changing the install layout.

#include <ctar/error.h>
#include <ctar/reader.h>
#include <ctar/version.h>

#endif // CTAR_CTAR_PUBLIC_H
35 changes: 35 additions & 0 deletions include/ctar/error.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#ifndef CTAR_ERROR_H
#define CTAR_ERROR_H

#include <cstdint>
#include <expected>
#include <string>

namespace ctar
{

/// Stable error codes exposed by the public API. Internal error types are
/// mapped onto these values and never leak through the installed headers.
enum class ErrorCode : uint8_t
{
kNotFound = 0,
kInvalidArgument,
kCorruption,
kIo,
kTooLarge,
kUnsupported,
kRuntimeError,
};

struct Error
{
ErrorCode code = ErrorCode::kRuntimeError;
std::string message;
};

template <typename T>
using Result = std::expected<T, Error>;

} // namespace ctar

#endif // CTAR_ERROR_H
154 changes: 154 additions & 0 deletions include/ctar/reader.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
#ifndef CTAR_READER_H
#define CTAR_READER_H

#include <cstddef>
#include <cstdint>
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <vector>

#include <ctar/error.h>

namespace ctar
{

enum class EntryKind : uint8_t
{
kFile = 0,
kDirectory,
};

/// One file or directory recorded in an archive.
///
/// `path` is a virtual absolute path rooted at "/": the directory that was
/// passed to `ctar pack` becomes "/", so the archive can be read without
/// knowing where the source tree lived.
struct Entry
{
std::string path;
EntryKind kind = EntryKind::kFile;
uint64_t size = 0; // original file size; 0 for directories
int64_t mtime_ms = 0;
uint32_t permissions = 0;
std::string owner;
std::string group;
};

/// Immutable, shared-ownership byte buffer.
///
/// The data pointer stays valid while the owning `std::shared_ptr` is alive,
/// so it can be handed to libraries that need a contiguous buffer (JPEG
/// decoders, pyarrow, ...) without copying.
class Buffer
{
public:
Buffer() = default;

Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;

[[nodiscard]] const char* data() const noexcept { return data_.get(); }
[[nodiscard]] size_t size() const noexcept { return size_; }
[[nodiscard]] std::string_view view() const noexcept
{
return size_ == 0 ? std::string_view{} : std::string_view(data_.get(), size_);
}

private:
friend class ArchiveReader;
/// Created only by ArchiveReader::MakeBuffer.
Buffer(std::unique_ptr<char[]> data, size_t size) noexcept;

std::unique_ptr<char[]> data_;
size_t size_ = 0;
};

/// A file opened from an archive.
///
/// The archive format compresses each file as a whole (LZ4 has no seek
/// points), so opening a file decompresses it into memory once; subsequent
/// reads are served from that buffer. A `File` is not thread-safe; distinct
/// `File` objects are independent. The reader that created it may be
/// destroyed first.
class File
{
public:
File() = default;

[[nodiscard]] uint64_t Size() const noexcept;
/// Copies up to `dst.size()` bytes from the current position and
/// advances it. Returns the number of bytes copied.
[[nodiscard]] Result<size_t> Read(std::span<char> dst);
/// Copies up to `dst.size()` bytes starting at `offset`. Returns the
/// number of bytes copied; an offset past the end is an error.
[[nodiscard]] Result<size_t> ReadAt(uint64_t offset, std::span<char> dst) const;
/// The whole file. Shared ownership, no copy.
[[nodiscard]] std::shared_ptr<const Buffer> ReadAll() const;

private:
friend class ArchiveReader;
explicit File(std::shared_ptr<const Buffer> data) noexcept;

std::shared_ptr<const Buffer> data_;
size_t offset_ = 0;
};

struct ReaderOptions
{
/// Reject archives whose uncompressed metadata exceeds this many bytes.
/// 0 means unlimited. Matches the CLI's --max-metadata-size.
uint64_t max_metadata_size = 1ULL << 30;
/// Reject files whose original size, or whose stored size in the
/// archive, exceeds this many bytes. 0 means unlimited. Matches the
/// CLI's --max-decompressed-size.
uint64_t max_file_size = 1ULL << 30;
};

/// Read-only, random-access view of a `.ctar` archive.
///
/// Open loads and validates the metadata index; List/Stat only consult it.
/// Reading one file touches only that file's stored bytes, never extracts
/// the archive to disk. After Open the reader is immutable, and read calls
/// may be made concurrently from several threads (the underlying I/O uses
/// pread); individual `File` objects are not thread-safe.
class ArchiveReader
{
public:
ArchiveReader() noexcept;
~ArchiveReader();

ArchiveReader(ArchiveReader&&) noexcept;
ArchiveReader& operator=(ArchiveReader&&) noexcept;
ArchiveReader(const ArchiveReader&) = delete;
ArchiveReader& operator=(const ArchiveReader&) = delete;

/// Opens an archive and loads its metadata index.
static Result<ArchiveReader> Open(std::string archive_path, ReaderOptions options = {});

/// Lists the direct children of `dir` (or every descendant when
/// `recursive` is true), sorted by path in byte order.
[[nodiscard]] Result<std::vector<Entry>> List(std::string_view dir = "/", bool recursive = false) const;

/// Metadata for one file or directory.
[[nodiscard]] Result<Entry> Stat(std::string_view path) const;

/// Opens a file and decompresses it into memory (bounded by
/// ReaderOptions::max_file_size).
[[nodiscard]] Result<File> OpenFile(std::string_view path) const;

/// Convenience wrapper around OpenFile().ReadAll().
[[nodiscard]] Result<std::shared_ptr<const Buffer>> ReadFile(std::string_view path) const;

private:
struct Impl;
explicit ArchiveReader(std::unique_ptr<Impl> impl) noexcept;
static std::shared_ptr<const Buffer> MakeBuffer(std::unique_ptr<char[]> data, size_t size);

std::unique_ptr<Impl> impl_;
};

} // namespace ctar

#endif // CTAR_READER_H
11 changes: 11 additions & 0 deletions scripts/consumer_smoke_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ cmake --build "$consumer_build" >/dev/null
echo "== running the consumer =="
"$consumer_build/ctar_consumer"

echo "== reading a real archive through the public API =="
if [[ -x "$build_dir/ctar" ]]; then
tree_dir="$tmp_root/consumer-tree"
mkdir -p "$tree_dir"
printf 'hello\n' >"$tree_dir/hello.txt"
"$build_dir/ctar" pack "$tree_dir" "$tmp_root/consumer.ctar" >/dev/null
"$consumer_build/ctar_consumer" "$tmp_root/consumer.ctar"
else
echo "ctar CLI not built; skipping the archive read check"
fi

echo "== checking that no test framework was installed =="
pollution=$(find "$prefix" \( -name '*gtest*' -o -name '*gmock*' \) -print)
if [[ -n "$pollution" ]]; then
Expand Down
Loading
Loading