byteme
C++ wrappers for buffered inputs
Loading...
Searching...
No Matches
check_buffer_size.hpp
Go to the documentation of this file.
1#ifndef BYTEME_CHECK_BUFFER_SIZE_HPP
2#define BYTEME_CHECK_BUFFER_SIZE_HPP
3
4#include <vector>
5#include <limits>
6#include <type_traits>
7#include <cstddef>
8
14namespace byteme {
15
19template<typename Type_>
20constexpr typename std::make_unsigned<Type_>::type unsigned_max() {
21 return std::numeric_limits<Type_>::max();
22}
23
24template<typename Cap_>
25bool exceeds_cap(std::size_t buffer_size) {
26 constexpr auto cap = unsigned_max<Cap_>();
27 if constexpr(std::numeric_limits<std::size_t>::max() > cap) {
28 return buffer_size > cap;
29 } else {
30 return false;
31 }
32}
33
34template<typename Cap_>
35std::size_t check_buffer_size(std::size_t buffer_size) {
36 if (exceeds_cap<Cap_>(buffer_size)) {
37 return unsigned_max<Cap_>();
38 } else {
39 return buffer_size;
40 }
41}
42
43inline std::size_t check_buffer_size(std::size_t buffer_size) {
44 // Usually this is a no-op as the size_type is a size_t.
45 // But it doesn't hurt to confirm that is the case.
46 return check_buffer_size<typename std::vector<unsigned char>::size_type>(buffer_size);
47}
48
49template<typename Cap_, bool non_zero_, typename Buffer_, typename BufSize_, class Func_>
50void safe_write(const Buffer_* buffer, BufSize_ n, Func_ fun) {
51 constexpr auto total = unsigned_max<Cap_>();
52 while (n > total) {
53 fun(buffer, total);
54 n -= total;
55 buffer += total;
56 }
57
58 if constexpr(non_zero_) {
59 if (n == 0) { // not sure if we need this, but better safe than sorry.
60 return;
61 }
62 }
63
64 fun(buffer, n);
65}
81template<typename Output_, typename Size_>
82constexpr Output_ cap(Size_ size) {
83 constexpr auto cap = std::numeric_limits<Output_>::max();
84 if (static_cast<typename std::make_unsigned<Size_>::type>(size) > cap) {
85 return cap;
86 } else {
87 return size;
88 }
89}
90
91}
92
93#endif
Simple byte readers and writers.
constexpr Output_ cap(Size_ size)
Definition check_buffer_size.hpp:82