My Project 4.4.0
C++ Distributed Hash Table
Loading...
Searching...
No Matches
utils.h
1// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
2// SPDX-License-Identifier: MIT
3#pragma once
4
5#include "def.h"
6
7#include <type_traits>
8#include <msgpack.hpp>
9#include <fmt/format.h>
10
11#include <chrono>
12#include <random>
13#include <functional>
14#include <map>
15#include <string_view>
16
17#include <cstdarg>
18
19#define WANT4 1
20#define WANT6 2
21
25namespace dht {
26
27using NetId = uint32_t;
28using want_t = int_fast8_t;
29
30OPENDHT_PUBLIC const char* version();
31
32// shortcut for std::shared_ptr
33template<class T>
34using Sp = std::shared_ptr<T>;
35
36template<typename Key, typename Item, typename Condition>
37void
38erase_if(std::map<Key, Item>& map, const Condition& condition)
39{
40 for (auto it = map.begin(); it != map.end();) {
41 if (condition(*it)) {
42 it = map.erase(it);
43 } else {
44 ++it;
45 }
46 }
47}
48
49template<typename... Args>
50std::string
51concat(Args&&... args)
52{
53 static_assert((std::is_constructible_v<std::string_view, Args&&> && ...));
54 std::string s;
55 s.reserve((std::string_view {args}.size() + ...));
56 (s.append(std::forward<Args>(args)), ...);
57 return s;
58}
59
63OPENDHT_PUBLIC std::pair<std::string_view, std::string_view> splitPort(std::string_view s);
64
65class OPENDHT_PUBLIC DhtException : public std::runtime_error
66{
67public:
68 DhtException(const std::string& str = "")
69 : std::runtime_error("DhtException occurred: " + str)
70 {}
71};
72
73class OPENDHT_PUBLIC SocketException : public DhtException
74{
75public:
76 SocketException(int err)
77 : DhtException(strerror(err))
78 {}
79};
80
81// Time related definitions and utility functions
82
83using clock = std::chrono::steady_clock;
84using system_clock = std::chrono::system_clock;
85using time_point = clock::time_point;
86using duration = clock::duration;
87
88OPENDHT_PUBLIC time_point from_system_time(system_clock::time_point t,
89 time_point steady_now,
90 system_clock::time_point system_now);
91OPENDHT_PUBLIC time_point from_system_time(system_clock::time_point t);
92OPENDHT_PUBLIC system_clock::time_point to_system_time(time_point t,
93 time_point steady_now,
94 system_clock::time_point system_now);
95OPENDHT_PUBLIC system_clock::time_point to_system_time(time_point t);
96OPENDHT_PUBLIC time_point from_time_t(std::time_t t);
97OPENDHT_PUBLIC std::time_t to_time_t(time_point t);
98
99template<class DT>
100static std::string
101print_duration(DT d)
102{
103 if (d < std::chrono::seconds(0)) {
104 return "-" + print_duration(-d);
105 } else if (d < std::chrono::milliseconds(1)) {
106 return fmt::format("{:.3g} us",
107 std::chrono::duration_cast<std::chrono::duration<double, std::micro>>(d).count());
108 } else if (d < std::chrono::seconds(1)) {
109 return fmt::format("{:.3g} ms",
110 std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(d).count());
111 } else if (d < std::chrono::minutes(1)) {
112 return fmt::format("{:.3g} s", std::chrono::duration_cast<std::chrono::duration<double>>(d).count());
113 } else if (d < std::chrono::hours(1)) {
114 return fmt::format("{:.3g} min",
115 std::chrono::duration_cast<std::chrono::duration<double, std::ratio<60>>>(d).count());
116 } else if (d < std::chrono::hours(72)) {
117 return fmt::format("{:.3g} h",
118 std::chrono::duration_cast<std::chrono::duration<double, std::ratio<3600>>>(d).count());
119 } else {
120 return fmt::format("{:.3g} days",
121 std::chrono::duration_cast<std::chrono::duration<double, std::ratio<86400>>>(d).count());
122 }
123}
124
125template<class TimePoint>
126static std::string
127print_time_relative(TimePoint now, TimePoint d)
128{
129 using namespace std::literals;
130 if (d == TimePoint::min())
131 return "never"s;
132 if (d == now)
133 return "now"s;
134 return (d > now) ? concat("in "sv, print_duration(d - now)) : concat(print_duration(now - d), " ago"sv);
135}
136
137OPENDHT_PUBLIC std::string printByteCount(size_t bytes);
138
139template<typename Duration = duration>
140class uniform_duration_distribution : public std::uniform_int_distribution<typename Duration::rep>
141{
142 using Base = std::uniform_int_distribution<typename Duration::rep>;
143 using param_type = typename Base::param_type;
144
145public:
146 uniform_duration_distribution(Duration min, Duration max)
147 : Base(min.count(), max.count())
148 {}
149 template<class Generator>
150 Duration operator()(Generator&& g)
151 {
152 return Duration(Base::operator()(g));
153 }
154 template<class Generator>
155 Duration operator()(Generator&& g, const param_type& params)
156 {
157 return Duration(Base::operator()(g, params));
158 }
159};
160
161// Serialization related definitions and utility functions
162
166using Blob = std::vector<uint8_t>;
167
171OPENDHT_PUBLIC Blob unpackBlob(const msgpack::object& o);
172
173template<typename Type>
174Blob
175packMsg(const Type& t)
176{
177 msgpack::sbuffer buffer;
178 msgpack::packer<msgpack::sbuffer> pk(&buffer);
179 pk.pack(t);
180 return {buffer.data(), buffer.data() + buffer.size()};
181}
182
183template<typename Type>
184Type
185unpackMsg(const Blob& b)
186{
187 msgpack::unpacked msg_res = msgpack::unpack((const char*) b.data(), b.size());
188 return msg_res.get().as<Type>();
189}
190
191inline msgpack::unpacked
192unpackMsg(const Blob& b)
193{
194 return msgpack::unpack((const char*) b.data(), b.size());
195}
196
197OPENDHT_PUBLIC msgpack::object* findMapValue(const msgpack::object& map, const char* key, size_t length);
198
199inline msgpack::object*
200findMapValue(const msgpack::object& map, const char* key)
201{
202 return findMapValue(map, key, strlen(key));
203}
204inline msgpack::object*
205findMapValue(const msgpack::object& map, std::string_view key)
206{
207 return findMapValue(map, key.data(), key.size());
208}
209
210} // namespace dht
OPENDHT_PUBLIC Blob unpackBlob(const msgpack::object &o)
OPENDHT_PUBLIC std::pair< std::string_view, std::string_view > splitPort(std::string_view s)
std::vector< uint8_t > Blob
Definition utils.h:166