Skip to content

Commit

Permalink
fix(Vfs): make VfsFileDescriptor potentially ref-counted
Browse files Browse the repository at this point in the history
  • Loading branch information
lmichaelis committed Mar 9, 2024
1 parent 24ce0ba commit 5eb44c8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
7 changes: 7 additions & 0 deletions include/zenkit/Vfs.hh
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ namespace zenkit {
struct VfsFileDescriptor {
std::byte const* memory;
std::size_t size;

VfsFileDescriptor(std::byte const* mem, size_t len, bool del);
VfsFileDescriptor(VfsFileDescriptor const& cpy);
~VfsFileDescriptor() noexcept;

private:
size_t* refcnt;
};

class VfsNode;
Expand Down
24 changes: 22 additions & 2 deletions src/Vfs.cc
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,25 @@ namespace zenkit {

VfsNotFoundError::VfsNotFoundError(std::string const& name) : Error("not found: \"" + name + "\"") {}

VfsFileDescriptor::VfsFileDescriptor(std::byte const* mem, size_t len, bool del)
: memory(mem), size(len), refcnt(del ? new size_t(1) : nullptr) {}

VfsFileDescriptor::VfsFileDescriptor(VfsFileDescriptor const& cpy)
: memory(cpy.memory), size(cpy.size), refcnt(cpy.refcnt) {
if (this->refcnt == nullptr) return;
*this->refcnt += 1;
}

VfsFileDescriptor::~VfsFileDescriptor() noexcept {
if (this->refcnt == nullptr) return;
*this->refcnt -= 1;

if (*this->refcnt == 0) {
delete[] memory;
delete this->refcnt;
}
}

bool VfsNodeComparator::operator()(VfsNode const& a, VfsNode const& b) const noexcept {
return phoenix::icompare(a.name(), b.name());
}
Expand Down Expand Up @@ -476,7 +495,7 @@ namespace zenkit {
#ifdef _ZK_WITH_MMAP
auto& mem = this->_m_data_mapped.emplace_back(path);
parent->create(VfsNode::file(path.filename().string(),
VfsFileDescriptor {mem.data(), mem.size()},
VfsFileDescriptor {mem.data(), mem.size(), false},
time.count()));
#else
std::ifstream stream {host, std::ios::ate};
Expand Down Expand Up @@ -603,7 +622,8 @@ namespace zenkit {
parent->remove(e_name);
}

(void) parent->create(VfsNode::file(e_name, VfsFileDescriptor {buf + e_offset, e_size}, timestamp));
(void) parent->create(
VfsNode::file(e_name, VfsFileDescriptor {buf + e_offset, e_size, false}, timestamp));
}

return last;
Expand Down

0 comments on commit 5eb44c8

Please sign in to comment.