FlatCityBuf C++ reader 0.8.0
Native C++17 reader for FlatCityBuf, the cloud-optimized CityJSON format
Loading...
Searching...
No Matches
checked.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <fcb/error.hpp>
4
5#include <cstdint>
6#include <string>
7
8namespace fcb {
9namespace detail {
10
11// Every value these touch comes from the file and may be hostile or corrupt.
12// Overflow must THROW, never wrap -- a wrapped size becomes an
13// under-allocated buffer, which is how a length check turns into a heap
14// overflow. Use these at every trust boundary, not just in layout.cpp.
15
16inline std::uint64_t checked_add(std::uint64_t a, std::uint64_t b, const char* what = "add") {
17 if (a > UINT64_MAX - b) {
19 std::string("size arithmetic overflow (") + what + ")");
20 }
21 return a + b;
22}
23
24inline std::uint64_t checked_mul(std::uint64_t a, std::uint64_t b, const char* what = "mul") {
25 if (a != 0 && b > UINT64_MAX / a) {
27 std::string("size arithmetic overflow (") + what + ")");
28 }
29 return a * b;
30}
31
34inline std::uint64_t ceil_div(std::uint64_t a, std::uint64_t b) {
35 if (b == 0) {
36 throw Error(ErrorCode::IllegalHeaderSize, "division by zero in size arithmetic");
37 }
38 return a / b + (a % b != 0 ? 1 : 0);
39}
40
44inline std::uint64_t range_end(std::uint64_t offset, std::uint64_t length) {
45 return checked_add(offset, length, "range_end");
46}
47
49inline void require_within(std::uint64_t offset, std::uint64_t length, std::uint64_t limit,
50 const char* what) {
51 if (range_end(offset, length) > limit) {
52 throw Error(ErrorCode::IllegalHeaderSize, std::string("range out of bounds: ") + what);
53 }
54}
55
56} // namespace detail
57} // namespace fcb
Every failure the library reports is one of these.
Definition error.hpp:30
std::uint64_t checked_mul(std::uint64_t a, std::uint64_t b, const char *what="mul")
Definition checked.hpp:24
std::uint64_t range_end(std::uint64_t offset, std::uint64_t length)
End of a range, checked.
Definition checked.hpp:44
void require_within(std::uint64_t offset, std::uint64_t length, std::uint64_t limit, const char *what)
Throws unless [offset, offset+length) lies wholly within limit.
Definition checked.hpp:49
std::uint64_t checked_add(std::uint64_t a, std::uint64_t b, const char *what="add")
Definition checked.hpp:16
std::uint64_t ceil_div(std::uint64_t a, std::uint64_t b)
ceil(a / b) without the (a + b - 1) overflow hazard.
Definition checked.hpp:34
std::uint64_t offset
Definition stree.cpp:57