54 lines
2.1 KiB
C++
54 lines
2.1 KiB
C++
#include <Void/Binary/ByteBuffer.hpp>
|
|
#include <Void/Memory/BudgetResource.hpp>
|
|
#include <Void/Testing/Assert.hpp>
|
|
#include <Void/Testing/Test.hpp>
|
|
|
|
#include <array>
|
|
#include <bit>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <string>
|
|
|
|
Void::Testing::Test binary_byte_buffer_limits_oom_preserve_and_zero_copy_freeze()
|
|
{
|
|
using Void::Binary::BinaryErrorCode;
|
|
using Void::Binary::ByteBuffer;
|
|
|
|
// Zero ceiling permits empty output only.
|
|
ByteBuffer zero_cap{std::size_t{0}};
|
|
Void::Testing::expect(zero_cap.writeString("").has_value());
|
|
const auto zero_fail = zero_cap.writeBool(true);
|
|
Void::Testing::expect(!zero_fail.has_value());
|
|
Void::Testing::expect(zero_fail.error().code() ==
|
|
Void::Binary::to_error_code(BinaryErrorCode::budget_exceeded));
|
|
|
|
// Upstream BudgetResource failure preserves previously committed bytes.
|
|
Void::Memory::BudgetResource budget{16};
|
|
ByteBuffer buf{&budget, 1024};
|
|
Void::Testing::require(buf.writeBig<std::uint32_t>(0x01020304u).has_value());
|
|
const auto before_oom_size = buf.size();
|
|
const std::array<std::byte, 64> big_chunk{};
|
|
const auto oom = buf.append(big_chunk);
|
|
Void::Testing::expect(!oom.has_value());
|
|
Void::Testing::expect(oom.error().code() ==
|
|
Void::Binary::to_error_code(BinaryErrorCode::allocation_failed));
|
|
Void::Testing::expect_eq(buf.size(), before_oom_size);
|
|
|
|
// Self-aliasing append works safely even across buffer growth.
|
|
ByteBuffer growable{256};
|
|
Void::Testing::require(growable.writeString("abc").has_value());
|
|
for (int i = 0; i < 4; ++i) {
|
|
Void::Testing::require(growable.append(growable.view()).has_value());
|
|
}
|
|
Void::Testing::expect_eq(growable.size(), std::size_t{48});
|
|
const std::byte* const pre_freeze_ptr = growable.view().data();
|
|
|
|
const auto frozen = growable.freeze();
|
|
Void::Testing::expect(growable.empty());
|
|
Void::Testing::expect(frozen.data() == pre_freeze_ptr);
|
|
Void::Testing::expect_eq(frozen.size(), std::size_t{48});
|
|
auto r = frozen.reader();
|
|
const auto prefix = r.readString(6);
|
|
Void::Testing::require(prefix.has_value());
|
|
Void::Testing::expect_eq(*prefix, std::string{"abcabc"});
|
|
} |