OpenVPN 3 Core Library
Loading...
Searching...
No Matches
buffmt.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#pragma once
13
14#include <utility>
15#include <type_traits>
16
20
22
23template <typename T>
25{
26 public:
27 static void write(Buffer &buf, T value)
28 {
29 UnsignedDecimal dec(std::move(value));
30 char ret[max_length()];
31 for (size_t i = sizeof(ret); i-- > 0;)
32 {
33 ret[i] = dec.next();
34 if (dec.is_zero())
35 {
36 buf.write(ret + i, sizeof(ret) - i);
37 return;
38 }
39 }
40 throw Exception("BufferFormat::UnsignedDecimal::write: overflow");
41 }
42
43 static constexpr size_t max_length()
44 {
45 return sizeof(T) * 3;
46 }
47
48 private:
49 UnsignedDecimal(T &&value)
50 : value_(std::move(value))
51 {
52 static_assert(std::is_unsigned<T>::value, "UnsignedDecimal: unsigned type required");
53 }
54
55 char next()
56 {
57 T d = value_ / T(10);
58 T r = value_ % T(10);
59 value_ = d;
60 return static_cast<char>('0' + r);
61 }
62
63 bool is_zero() const
64 {
65 return !value_;
66 }
67
69};
70
71template <typename T>
72class Hex
73{
74 public:
75 static void write(Buffer &buf, T value)
76 {
77 Hex hex(std::move(value));
78 char ret[max_length()];
79 for (size_t i = sizeof(ret); i-- > 0;)
80 {
81 ret[i] = hex.next();
82 if (hex.is_zero())
83 {
84 buf.write(ret + i, sizeof(ret) - i);
85 return;
86 }
87 }
88 throw Exception("BufferFormat::Hex::write: overflow");
89 }
90
91 static constexpr size_t max_length()
92 {
93 return sizeof(T) * 2;
94 }
95
96 private:
97 Hex(T &&value)
98 : value_(std::move(value))
99 {
100 static_assert(std::is_unsigned<T>::value, "BufferFormat::Hex: unsigned type required");
101 }
102
103 char next()
104 {
105 T d = value_ / T(16);
106 T r = value_ % T(16);
107 value_ = d;
108 return render_hex_char(r);
109 }
110
111 bool is_zero() const
112 {
113 return !value_;
114 }
115
117};
118
119} // namespace openvpn::BufferFormat
static constexpr size_t max_length()
Definition buffmt.hpp:91
static void write(Buffer &buf, T value)
Definition buffmt.hpp:75
static constexpr size_t max_length()
Definition buffmt.hpp:43
static void write(Buffer &buf, T value)
Definition buffmt.hpp:27
void write(const T *data, const size_t size)
Write data to the buffer.
Definition buffer.hpp:1563
char render_hex_char(const int c, const bool caps=false)
Definition hexstr.hpp:42
std::string ret