Harden binary stream overlapping writes
This commit is contained in:
@@ -1,7 +1,28 @@
|
||||
#include "foundation/binary_stream.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace pp::foundation {
|
||||
|
||||
namespace {
|
||||
|
||||
[[nodiscard]] bool overlaps_backing_storage(
|
||||
const std::vector<std::byte>& backing,
|
||||
std::span<const std::byte> bytes) noexcept
|
||||
{
|
||||
if (backing.empty() || bytes.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto backing_begin = reinterpret_cast<std::uintptr_t>(backing.data());
|
||||
const auto backing_end = backing_begin + backing.size();
|
||||
const auto bytes_begin = reinterpret_cast<std::uintptr_t>(bytes.data());
|
||||
const auto bytes_end = bytes_begin + bytes.size();
|
||||
return bytes_begin < backing_end && backing_begin < bytes_end;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ByteReader::ByteReader(std::span<const std::byte> bytes) noexcept
|
||||
: bytes_(bytes)
|
||||
{
|
||||
@@ -135,6 +156,12 @@ Status ByteWriter::write_bytes(std::span<const std::byte> bytes)
|
||||
return Status::invalid_argument("writer has no backing storage");
|
||||
}
|
||||
|
||||
if (overlaps_backing_storage(*bytes_, bytes)) {
|
||||
const std::vector<std::byte> copy(bytes.begin(), bytes.end());
|
||||
bytes_->insert(bytes_->end(), copy.begin(), copy.end());
|
||||
return Status::success();
|
||||
}
|
||||
|
||||
bytes_->insert(bytes_->end(), bytes.begin(), bytes.end());
|
||||
return Status::success();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user