Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
util.hh
Go to the documentation of this file.
1#pragma once
3
4#include "nix/util/types.hh"
5#include "nix/util/error.hh"
6#include "nix/util/strings.hh"
7
8#include <set>
9#include <bit>
10#include <optional>
11#include <ranges>
12#include <concepts>
13
14namespace nix {
15
16void initLibUtil();
17
23std::vector<char *> stringsToCharPtrs(const Strings & ss);
24
25MakeError(FormatError, Error);
26
27template<class... Parts>
28auto concatStrings(Parts &&... parts)
29 -> std::enable_if_t<(... && std::is_convertible_v<Parts, std::string_view>), std::string>
30{
31 std::string_view views[sizeof...(parts)] = {std::forward<Parts>(parts)...};
32 return concatStringsSep({}, views);
33}
34
38inline std::string quoteString(std::string_view s, char quote = '\'')
39{
40 std::string result;
41 result.reserve(s.size() + 2);
42 result += quote;
43 result += s;
44 result += quote;
45 return result;
46}
47
51template<class C>
52Strings quoteStrings(const C & c, char quote = '\'')
53{
54 Strings res;
55 for (auto & s : c)
56 res.push_back(quoteString(s, quote));
57 return res;
58}
59
65std::string chomp(std::string_view s);
66
70std::string trim(std::string_view s, std::string_view whitespace = " \n\r\t");
71
75std::string replaceStrings(std::string s, std::string_view from, std::string_view to);
76
81std::string rewriteStrings(
82 std::string s, const StringMap & rewrites, std::set<uint64_t> * matches = nullptr, uint64_t offsetShift = 0);
83
87template<std::integral N>
88std::optional<N> string2Int(const std::string_view s);
89
90/* Guess what these overloads would do? If you gussed "8" parses as uint8_t(56) then
91 congratulations. Needless to say, these overloads are deleted and are gigantic footguns. */
92
93#define NIX_DELETE_STRING2INT_OVERLOAD(T) \
94 template<> \
95 std::optional<T> string2Int(const std::string_view s) = delete;
96
97NIX_DELETE_STRING2INT_OVERLOAD(char)
98NIX_DELETE_STRING2INT_OVERLOAD(signed char)
99NIX_DELETE_STRING2INT_OVERLOAD(unsigned char)
100NIX_DELETE_STRING2INT_OVERLOAD(wchar_t)
101NIX_DELETE_STRING2INT_OVERLOAD(char16_t)
102NIX_DELETE_STRING2INT_OVERLOAD(char32_t)
103
104#undef NIX_DELETE_STRING2INT_OVERLOAD
105
110template<class N>
111N string2IntWithUnitPrefix(std::string_view s)
112{
113 uint64_t multiplier = 1;
114 if (!s.empty()) {
115 char u = std::toupper(*s.rbegin());
116 if (std::isalpha(u)) {
117 if (u == 'K')
118 multiplier = 1ULL << 10;
119 else if (u == 'M')
120 multiplier = 1ULL << 20;
121 else if (u == 'G')
122 multiplier = 1ULL << 30;
123 else if (u == 'T')
124 multiplier = 1ULL << 40;
125 else
126 throw UsageError("invalid unit specifier '%1%'", u);
127 s.remove_suffix(1);
128 }
129 }
130 if (auto n = string2Int<N>(s))
131 return *n * multiplier;
132 throw UsageError("'%s' is not an integer", s);
133}
134
135// Base also uses 'K', because it should also displayed as KiB => 100 Bytes => 0.1 KiB
136#define NIX_UTIL_SIZE_UNITS \
137 NIX_UTIL_DEFINE_SIZE_UNIT(Base, 'K') \
138 NIX_UTIL_DEFINE_SIZE_UNIT(Kilo, 'K') \
139 NIX_UTIL_DEFINE_SIZE_UNIT(Mega, 'M') \
140 NIX_UTIL_DEFINE_SIZE_UNIT(Giga, 'G') \
141 NIX_UTIL_DEFINE_SIZE_UNIT(Tera, 'T') \
142 NIX_UTIL_DEFINE_SIZE_UNIT(Peta, 'P') \
143 NIX_UTIL_DEFINE_SIZE_UNIT(Exa, 'E') \
144 NIX_UTIL_DEFINE_SIZE_UNIT(Zetta, 'Z') \
145 NIX_UTIL_DEFINE_SIZE_UNIT(Yotta, 'Y')
146
147enum class SizeUnit {
148#define NIX_UTIL_DEFINE_SIZE_UNIT(name, suffix) name,
149 NIX_UTIL_SIZE_UNITS
150#undef NIX_UTIL_DEFINE_SIZE_UNIT
151};
152
153constexpr inline auto sizeUnits = std::to_array<SizeUnit>({
154#define NIX_UTIL_DEFINE_SIZE_UNIT(name, suffix) SizeUnit::name,
155 NIX_UTIL_SIZE_UNITS
156#undef NIX_UTIL_DEFINE_SIZE_UNIT
157});
158
159SizeUnit getSizeUnit(int64_t value);
160
165std::optional<SizeUnit> getCommonSizeUnit(std::initializer_list<int64_t> values);
166
167std::string renderSizeWithoutUnit(int64_t value, SizeUnit unit, bool align = false);
168
169char getSizeUnitSuffix(SizeUnit unit);
170
176std::string renderSize(int64_t value, bool align = false);
177
181template<class N>
182std::optional<N> string2Float(const std::string_view s);
183
187template<typename T>
188 requires std::is_unsigned_v<T> && (sizeof(T) > 1)
189T readLittleEndian(unsigned char * p)
190{
191 T x = 0;
192 std::memcpy(&x, p, sizeof(T));
193 /* Don't need to do anything if we are not on a big endian machine. */
194 if constexpr (std::endian::native != std::endian::little)
195 x = std::byteswap(x);
196 return x;
197}
198
202template<typename T>
203 requires std::is_unsigned_v<T> && (sizeof(T) > 1)
204void writeBigEndian(unsigned char * p, T x)
205{
206 if constexpr (std::endian::native != std::endian::big)
207 x = std::byteswap(x);
208 std::memcpy(p, &x, sizeof(T));
209}
210
214bool hasPrefix(std::string_view s, std::string_view prefix);
215
219bool hasSuffix(std::string_view s, std::string_view suffix);
220
224std::string toLower(std::string s);
225
234std::string escapeShellArgAlways(const std::string_view s);
235
246void ignoreExceptionInDestructor(Verbosity lvl = lvlError);
247
255void ignoreExceptionExceptInterrupt(Verbosity lvl = lvlError);
256
260constexpr char treeConn[] = "├───";
261constexpr char treeLast[] = "└───";
262constexpr char treeLine[] = "│ ";
263constexpr char treeNull[] = " ";
264
270std::string stripIndentation(std::string_view s);
271
277std::pair<std::string_view, std::string_view> getLine(std::string_view s);
278
285template<class T>
286const T * get(const std::optional<T> & opt)
287{
288 return opt ? &*opt : nullptr;
289}
290
295template<class T>
296T * get(std::optional<T> & opt)
297{
298 return opt ? &*opt : nullptr;
299}
300
304template<class T, typename K>
305const typename T::mapped_type * get(const T & map, const K & key)
306{
307 auto i = map.find(key);
308 if (i == map.end())
309 return nullptr;
310 return &i->second;
311}
312
313template<class T, typename K>
314typename T::mapped_type * get(T & map, const K & key)
315{
316 auto i = map.find(key);
317 if (i == map.end())
318 return nullptr;
319 return &i->second;
320}
321
325template<class T, typename K>
326typename T::mapped_type * get(T && map, const K & key) = delete;
327
331template<class T>
332std::optional<typename T::mapped_type> getConcurrent(const T & map, const typename T::key_type & key)
333{
334 std::optional<typename T::mapped_type> res;
335 map.cvisit(key, [&](auto & x) { res = x.second; });
336 return res;
337}
338
342template<class T, typename K>
343const typename T::mapped_type & getOr(T & map, const K & key, const typename T::mapped_type & defaultValue)
344{
345 auto i = map.find(key);
346 if (i == map.end())
347 return defaultValue;
348 return i->second;
349}
350
354template<class T, typename K>
355const typename T::mapped_type & getOr(T && map, const K & key, const typename T::mapped_type & defaultValue) = delete;
356
360template<class T>
361std::optional<typename T::value_type> remove_begin(T & c)
362{
363 auto i = c.begin();
364 if (i == c.end())
365 return {};
366 auto v = std::move(*i);
367 c.erase(i);
368 return v;
369}
370
374template<class T>
375std::optional<typename T::value_type> pop(T & c)
376{
377 if (c.empty())
378 return {};
379 auto v = std::move(c.front());
380 c.pop();
381 return v;
382}
383
384template<typename T>
385class Callback;
386
391template<typename T>
392struct MaintainCount
393{
394 T & counter;
395 long delta;
396
397 MaintainCount(T & counter, long delta = 1)
398 : counter(counter)
399 , delta(delta)
400 {
401 counter += delta;
402 }
403
404 MaintainCount(MaintainCount &&) = delete;
405 MaintainCount(const MaintainCount &) = delete;
406 MaintainCount & operator=(MaintainCount &&) = delete;
407 MaintainCount & operator=(const MaintainCount &) = delete;
408
409 ~MaintainCount()
410 {
411 counter -= delta;
412 }
413};
414
418template<std::ranges::viewable_range R>
419constexpr auto enumerate(R && range)
420{
421 /* Not std::views::enumerate because it uses difference_type for the index. */
422 return std::views::zip(std::views::iota(size_t{0}), std::forward<R>(range));
423}
424
430template<std::ranges::viewable_range R>
431 requires std::ranges::sized_range<R>
432constexpr auto markLast(R && range)
433{
434 auto n = std::ranges::size(range);
435 return std::views::zip(
436 std::views::iota(size_t{1}) | std::views::transform([n](size_t i) { return i == n; }), std::forward<R>(range));
437}
438
442template<class... Ts>
443struct overloaded : Ts...
444{
445 using Ts::operator()...;
446};
447template<class... Ts>
448overloaded(Ts...) -> overloaded<Ts...>;
449
454inline std::string operator+(const std::string & s1, std::string_view s2)
455{
456 std::string s;
457 s.reserve(s1.size() + s2.size());
458 s.append(s1);
459 s.append(s2);
460 return s;
461}
462
463inline std::string operator+(std::string && s, std::string_view s2)
464{
465 s.append(s2);
466 return std::move(s);
467}
468
469inline std::string operator+(std::string_view s1, const char * s2)
470{
471 auto s2Size = strlen(s2);
472 std::string s;
473 s.reserve(s1.size() + s2Size);
474 s.append(s1);
475 s.append(s2, s2Size);
476 return s;
477}
478
482#define NIX_INCOMPLETE_SWITCH_BEGIN _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Wswitch-enum\"")
483#define NIX_INCOMPLETE_SWITCH_END _Pragma("GCC diagnostic pop")
484
485} // namespace nix
Definition error.hh:310
Definition error.hh:311
This file defines two main structs/classes used in nix error handling.
Definition util.hh:444
const T * get(const std::optional< T > &opt)
Definition util.hh:286
Strings quoteStrings(const C &c, char quote='\'')
Definition util.hh:52
constexpr auto markLast(R &&range)
Definition util.hh:432
std::optional< typename T::value_type > remove_begin(T &c)
Definition util.hh:361
std::optional< typename T::value_type > pop(T &c)
Definition util.hh:375
std::optional< typename T::mapped_type > getConcurrent(const T &map, const typename T::key_type &key)
Definition util.hh:332
T readLittleEndian(unsigned char *p)
Definition util.hh:189
N string2IntWithUnitPrefix(std::string_view s)
Definition util.hh:111
std::pair< std::string_view, std::string_view > getLine(std::string_view s)
Definition util.cc:336
std::optional< SizeUnit > getCommonSizeUnit(std::initializer_list< int64_t > values)
Definition util.cc:189
std::optional< N > string2Float(const std::string_view s)
Definition util.cc:164
constexpr auto enumerate(R &&range)
Definition util.hh:419
const T::mapped_type & getOr(T &map, const K &key, const typename T::mapped_type &defaultValue)
Definition util.hh:343
std::string operator+(const std::string &s1, std::string_view s2)
Definition util.hh:454
std::string quoteString(std::string_view s, char quote='\'')
Definition util.hh:38
std::vector< char * > stringsToCharPtrs(const Strings &ss)
Definition util.cc:87
std::string renderSize(int64_t value, bool align=false)
Definition util.cc:228
std::string stripIndentation(std::string_view s)
Definition util.cc:298
constexpr char treeConn[]
Definition util.hh:260
void writeBigEndian(unsigned char *p, T x)
Definition util.hh:204
std::optional< N > string2Int(const std::string_view s)
Definition util.cc:142