Loading...
Searching...
No Matches
packed_record_buffer.hpp
Go to the documentation of this file.
1#pragma once
2
3/**
4 * PackedRecordBuffer — byte buffer for a Fortran unformatted record whose
5 * fields are mixed-width scalars.
6 *
7 * A Fortran WRITE of a list of scalars lays them end to end with no
8 * alignment padding; a C struct with the same members does not. Appending
9 * each field's bytes here reproduces the packed layout exactly, independent
10 * of compiler alignment rules, and never exposes uninitialized bytes.
11 */
12
13#include <cstddef>
14#include <cstring>
15#include <type_traits>
16#include <vector>
17
18namespace q3 {
19
21 public:
22 template <typename Scalar> void append(Scalar value) {
23 static_assert(std::is_trivially_copyable<Scalar>::value,
24 "PackedRecordBuffer appends raw bytes of trivially copyable scalars");
25 const std::size_t offset = bytes_.size();
26 bytes_.resize(offset + sizeof(Scalar));
27 std::memcpy(bytes_.data() + offset, &value, sizeof(Scalar));
28 }
29
30 [[nodiscard]] const char* data() const {
31 return bytes_.data();
32 }
33 [[nodiscard]] std::size_t size() const {
34 return bytes_.size();
35 }
36
37 private:
38 std::vector<char> bytes_;
39};
40
41} // namespace q3