Skip to content
Open
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
27 changes: 17 additions & 10 deletions cpp/Platform.Memory/FileMappedResizableDirectMemory.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,10 @@ namespace Platform::Memory
{
std::ofstream file{Path, std::ios::binary | std::ios::app};
}
auto size = std::filesystem::file_size(Path);
auto capacity = std::max(size, static_cast<std::uintmax_t>(minimumReservedCapacity));
capacity = std::max(capacity, static_cast<std::uintmax_t>(MinimumCapacity));
const auto remainder = capacity % MinimumCapacity;
const auto padding = remainder == 0 ? 0 : MinimumCapacity - remainder;
if (capacity > std::numeric_limits<capacity_t>::max() - padding)
{
throw std::length_error("Mapped file exceeds the maximum reserved capacity");
}
const auto size = std::filesystem::file_size(Path);
const auto capacity = InitialReservedCapacity(size, minimumReservedCapacity);
_open = true;
ReservedCapacity(static_cast<capacity_t>(capacity + padding));
ReservedCapacity(capacity);
UsedCapacity(static_cast<capacity_t>(size));
}

Expand Down Expand Up @@ -85,6 +78,20 @@ namespace Platform::Memory
public: std::filesystem::path Path;
public: explicit FileMappedResizableDirectMemory(const std::string& path) : FileMappedResizableDirectMemory(path, MinimumCapacity) { }

private: static capacity_t InitialReservedCapacity(std::uintmax_t fileSize, capacity_t minimumReservedCapacity)
{
const auto required = std::max({
fileSize, std::uintmax_t{minimumReservedCapacity}, std::uintmax_t{MinimumCapacity}
});
const auto remainder = required % MinimumCapacity;
const auto padding = remainder == 0 ? 0 : MinimumCapacity - remainder;
if (required > std::numeric_limits<capacity_t>::max() - padding)
{
throw std::length_error("Mapped file exceeds the maximum reserved capacity");
}
return static_cast<capacity_t>(required + padding);
}

private: void MapFile(capacity_t capacity)
{
if (capacity == 0)
Expand Down
4 changes: 2 additions & 2 deletions cpp/Platform.Memory/Platform.Memory.TemplateLibrary.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
<title>LinksPlatform's Platform.Memory Template Library</title>
<summary>LinksPlatform's Platform.Memory is a Template Library what contains crossplatform class API for memory mapping.</summary>
<description>LinksPlatform's Platform.Memory is a Template Library what contains crossplatform class API for memory mapping. Use Platform.Memory.h file to include the library.</description>
<releaseNotes>Initial realise</releaseNotes>
<version>0.1.0</version>
<releaseNotes>Clarify how mapped files reserve whole pages on open.</releaseNotes>
<version>0.1.1</version>
<authors>konard</authors>
<owners>konard</owners>
<copyright>konard</copyright>
Expand Down
13 changes: 7 additions & 6 deletions cpp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
`FileMappedResizableDirectMemory` stores the native-endian bytes of the values
without a header. See the [shared format](../README.md#mapped-file-format).

On open, `UsedCapacity()` is the existing length in bytes, and the default
reservation rounds up to the system page size. Set `UsedCapacity(bytes)` to
the number of initialized bytes before closing. `Close()` flushes and unmaps
the view before truncating to that length. Closing again is harmless, and the
destructor attempts the same operation when the owner leaves scope. Call
`Close()` explicitly to handle errors.
On open, `UsedCapacity()` is the existing length in bytes. The initial
reservation is the smallest whole number of system pages that holds the file
and meets the caller-supplied minimum, with at least one page. Set
`UsedCapacity(bytes)` to the number of initialized bytes before closing.
`Close()` flushes and unmaps the view before truncating to that length.
Closing again is harmless, and the destructor attempts the same operation
when the owner leaves scope. Call `Close()` explicitly to handle errors.

For a typed array, compute the element count as `UsedCapacity() / sizeof(T)`
after checking for a whole number of elements. An empty file represents zero
Expand Down
2 changes: 2 additions & 0 deletions examples/mapped-file-interop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ cases end in a real zero value. The check verifies the closed file size, the
reported logical size, every value, and that reopening preserves all bytes.
The C# fixture also checks byte lengths around page boundaries, including an
aligned two-page file that previously reserved an extra page.
The C++ fixture checks explicit minimum reservations around page boundaries and
rejects a reservation that would overflow when rounded up.

Initialize the Rust submodule and build the three fixture executables from the
repository root. The C++ build uses the dependencies from `cpp/conanfile.txt`.
Expand Down
3 changes: 3 additions & 0 deletions examples/mapped-file-interop/check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ trap 'rm -rf "$fixtures"' EXIT
languages=(csharp cpp rust)
executables=("$@")

"$2" check-reservation "$fixtures"
echo "C++ initial reservation checks passed"

for writer in "${!languages[@]}"; do
origin="$fixtures/${languages[writer]}"
mkdir "$origin"
Expand Down
63 changes: 59 additions & 4 deletions examples/mapped-file-interop/fixture.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include <cstdint>
#include <iostream>
#include <limits>
#include <string_view>

using Platform::Memory::FileMappedResizableDirectMemory;
Expand Down Expand Up @@ -54,23 +55,77 @@ void Read(const std::filesystem::path& path, std::size_t count, std::size_t rese
}
}

void CheckReservations(const std::filesystem::path& directory)
{
const auto page = FileMappedResizableDirectMemory::MinimumCapacity;
struct ReservationCase
{
std::size_t length;
std::size_t minimum;
std::size_t expected;
};
const ReservationCase cases[] = {
{2 * page, page, 2 * page},
{0, 0, page},
{page - 1, 1, page},
{page + 1, page, 2 * page},
{0, 2 * page, 2 * page},
{page, page + 1, 2 * page},
{2 * page + 1, page + 1, 3 * page}
};

for (const auto& testCase : cases)
{
const auto name = "reservation-" + std::to_string(testCase.length)
+ "-" + std::to_string(testCase.minimum) + ".bin";
const auto path = directory / name;
std::ofstream(path, std::ios::binary).close();
std::filesystem::resize_file(path, testCase.length);
FileMappedResizableDirectMemory memory(path.string(), testCase.minimum);
Check(memory.UsedCapacity() == testCase.length, path, "unexpected logical length");
Check(memory.ReservedCapacity() == testCase.expected, path, "unexpected reservation");
Check(std::filesystem::file_size(path) == testCase.expected, path, "unexpected open file length");
memory.Close();
Check(std::filesystem::file_size(path) == testCase.length, path, "unexpected closed file length");
}

const auto path = directory / "reservation-overflow.bin";
std::ofstream(path, std::ios::binary).put('x');
bool overflowRejected = false;
try
{
FileMappedResizableDirectMemory memory(path.string(), std::numeric_limits<std::size_t>::max());
}
catch (const std::length_error&)
{
overflowRejected = true;
}
Check(overflowRejected, path, "overflowing reservation was accepted");
Check(std::filesystem::file_size(path) == 1, path, "overflow changed file length");
}

int main(int argc, const char* argv[])
{
if (argc != 3 || (std::string_view(argv[1]) != "write" && std::string_view(argv[1]) != "read"))
const auto mode = argc == 3 ? std::string_view(argv[1]) : std::string_view{};
if (mode != "write" && mode != "read" && mode != "check-reservation")
{
std::cerr << "Expected write|read DIRECTORY\n";
std::cerr << "Expected write|read|check-reservation DIRECTORY\n";
return 1;
}
const auto page = FileMappedResizableDirectMemory::MinimumCapacity;
const auto writing = std::string_view(argv[1]) == "write";
try
{
if (mode == "check-reservation")
{
CheckReservations(argv[2]);
return 0;
}
for (std::size_t count : {std::size_t{0}, std::size_t{3}, page / 8, page / 8 + 1})
{
const auto path = std::filesystem::path(argv[2]) / (std::to_string(count) + ".bin");
const auto length = count * sizeof(std::uint64_t);
const auto reservation = std::max(page, (length + page - 1) / page * page);
if (writing)
if (mode == "write")
{
Write(path, count, reservation + page);
}
Expand Down
Loading