I am trying to write code that serializes objects into a std::vector<std::byte> to then write that into a file. Each section of the file gets a small header which contains uint64_ts that represent byte offsets into the start of the file at which data is located. As I'm using C++20 I want to use std::span as much as possible. I currently have a std::spanstd::byte on which I frequently call subspan to advance the bytes. Though now my issue is how do I calculate the difference between two spans without having a bunch of reinterpret_cast and pointer arithmetic in my own code. This is what the code looks like currently:
auto* fileHeader = reinterpret_cast<ShaderFileHeader*>(output.data());
fileHeader->magic = headerMagic;
fileHeader->shaderCount = inputCount;
// Create a view of the section containing shader headers and write the basic header info.
std::span<ShaderDescription> shaders = { reinterpret_cast<ShaderDescription*>(output.data() + sizeof(ShaderFileHeader)), inputCount };
for (auto i = 0U; i < inputCount; ++i) {
auto& input = inputs[i];
shaders[i].byteSize = input.shaderBytes.size();
shaders[i].stage = input.stage;
shaders[i].lang = input.lang;
}
auto offset = sizeof(ShaderFileHeader) + shaders.size_bytes();
for (auto i = 0U; i < inputCount; ++i) {
auto& input = inputs[i];
// Write the name to the buffer.
auto size = input.name.size() + 1; // For the null terminator.
shaders[i].nameByteOffset = offset;
std::memcpy(&output[offset], input.name.data(), size);
offset += size;
// Write the shader binaries to the buffer.
shaders[i].byteOffset = offset;
std::memcpy(&output[offset], input.shaderBytes.data(), input.shaderBytes.size());
offset += input.shaderBytes.size();
}