libpqxx  7.9.0
util.hxx
1 /* Various utility definitions for libpqxx.
2  *
3  * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/util instead.
4  *
5  * Copyright (c) 2000-2024, Jeroen T. Vermeulen.
6  *
7  * See COPYING for copyright license. If you did not receive a file called
8  * COPYING with this source code, please notify the distributor of this
9  * mistake, or contact the author.
10  */
11 #ifndef PQXX_H_UTIL
12 #define PQXX_H_UTIL
13 
14 #if !defined(PQXX_HEADER_PRE)
15 # error "Include libpqxx headers as <pqxx/header>, not <pqxx/header.hxx>."
16 #endif
17 
18 #include <cassert>
19 #include <cctype>
20 #include <cerrno>
21 #include <cstdio>
22 #include <cstring>
23 #include <functional>
24 #include <iterator>
25 #include <limits>
26 #include <memory>
27 #include <stdexcept>
28 #include <string>
29 #include <string_view>
30 #include <type_traits>
31 #include <typeinfo>
32 #include <utility>
33 #include <vector>
34 
35 #include "pqxx/except.hxx"
36 #include "pqxx/types.hxx"
37 #include "pqxx/version.hxx"
38 
39 
41 namespace pqxx
42 {}
43 
44 #include <pqxx/internal/libpq-forward.hxx>
45 
46 
47 // C++23: Retire wrapper.
48 #if defined(PQXX_HAVE_UNREACHABLE)
50 # define PQXX_UNREACHABLE std::unreachable()
51 #else
52 # define PQXX_UNREACHABLE assert(false)
53 #endif
54 
55 
57 namespace pqxx::internal
58 {
59 
60 // C++20: Retire wrapper.
62 template<typename LEFT, typename RIGHT>
63 inline constexpr bool cmp_less(LEFT lhs, RIGHT rhs) noexcept
64 {
65 #if defined(PQXX_HAVE_CMP)
66  return std::cmp_less(lhs, rhs);
67 #else
68  // We need a variable just because lgtm.com gives off a false positive
69  // warning when we compare the values directly. It considers that a
70  // "self-comparison."
71  constexpr bool left_signed{std::is_signed_v<LEFT>};
72  if constexpr (left_signed == std::is_signed_v<RIGHT>)
73  return lhs < rhs;
74  else if constexpr (std::is_signed_v<LEFT>)
75  return (lhs <= 0) ? true : (std::make_unsigned_t<LEFT>(lhs) < rhs);
76  else
77  return (rhs <= 0) ? false : (lhs < std::make_unsigned_t<RIGHT>(rhs));
78 #endif
79 }
80 
81 
82 // C++20: Retire wrapper.
84 template<typename LEFT, typename RIGHT>
85 inline constexpr bool cmp_greater(LEFT lhs, RIGHT rhs) noexcept
86 {
87 #if defined(PQXX_HAVE_CMP)
88  return std::cmp_greater(lhs, rhs);
89 #else
90  return cmp_less(rhs, lhs);
91 #endif
92 }
93 
94 
95 // C++20: Retire wrapper.
97 template<typename LEFT, typename RIGHT>
98 inline constexpr bool cmp_less_equal(LEFT lhs, RIGHT rhs) noexcept
99 {
100 #if defined(PQXX_HAVE_CMP)
101  return std::cmp_less_equal(lhs, rhs);
102 #else
103  return not cmp_less(rhs, lhs);
104 #endif
105 }
106 
107 
108 // C++20: Retire wrapper.
110 template<typename LEFT, typename RIGHT>
111 inline constexpr bool cmp_greater_equal(LEFT lhs, RIGHT rhs) noexcept
112 {
113 #if defined(PQXX_HAVE_CMP)
114  return std::cmp_greater_equal(lhs, rhs);
115 #else
116  return not cmp_less(lhs, rhs);
117 #endif
118 }
119 
120 
122 
125 [[nodiscard]] inline std::string cat2(std::string_view x, std::string_view y)
126 {
127  std::string buf;
128  auto const xs{std::size(x)}, ys{std::size(y)};
129  buf.resize(xs + ys);
130  x.copy(std::data(buf), xs);
131  y.copy(std::data(buf) + xs, ys);
132  return buf;
133 }
134 } // namespace pqxx::internal
135 
136 
137 namespace pqxx
138 {
139 using namespace std::literals;
140 
142 template<typename... T> inline constexpr void ignore_unused(T &&...) noexcept
143 {}
144 
145 
147 
150 template<typename TO, typename FROM>
151 inline TO check_cast(FROM value, std::string_view description)
152 {
153  static_assert(std::is_arithmetic_v<FROM>);
154  static_assert(std::is_arithmetic_v<TO>);
155  static_assert(std::is_integral_v<FROM> == std::is_integral_v<TO>);
156 
157  // The rest of this code won't quite work for bool, but bool is trivially
158  // convertible to other arithmetic types as far as I can see.
159  if constexpr (std::is_same_v<FROM, bool>)
160  return static_cast<TO>(value);
161 
162  // Depending on our "if constexpr" conditions, this parameter may not be
163  // needed. Some compilers will warn.
164  ignore_unused(description);
165 
166  using from_limits = std::numeric_limits<decltype(value)>;
167  using to_limits = std::numeric_limits<TO>;
168  if constexpr (std::is_signed_v<FROM>)
169  {
170  if constexpr (std::is_signed_v<TO>)
171  {
172  if (value < to_limits::lowest())
173  throw range_error{internal::cat2("Cast underflow: "sv, description)};
174  }
175  else
176  {
177  // FROM is signed, but TO is not. Treat this as a special case, because
178  // there may not be a good broader type in which the compiler can even
179  // perform our check.
180  if (value < 0)
182  "Casting negative value to unsigned type: "sv, description)};
183  }
184  }
185  else
186  {
187  // No need to check: the value is unsigned so can't fall below the range
188  // of the TO type.
189  }
190 
191  if constexpr (std::is_integral_v<FROM>)
192  {
193  using unsigned_from = std::make_unsigned_t<FROM>;
194  using unsigned_to = std::make_unsigned_t<TO>;
195  constexpr auto from_max{static_cast<unsigned_from>((from_limits::max)())};
196  constexpr auto to_max{static_cast<unsigned_to>((to_limits::max)())};
197  if constexpr (from_max > to_max)
198  {
199  if (internal::cmp_greater(value, to_max))
200  throw range_error{internal::cat2("Cast overflow: "sv, description)};
201  }
202  }
203  else if constexpr ((from_limits::max)() > (to_limits::max)())
204  {
205  if (value > (to_limits::max)())
206  throw range_error{internal::cat2("Cast overflow: ", description)};
207  }
208 
209  return static_cast<TO>(value);
210 }
211 
212 
234 inline PQXX_PRIVATE void check_version() noexcept
235 {
236  // There is no particular reason to do this here in @ref connection, except
237  // to ensure that every meaningful libpqxx client will execute it. The call
238  // must be in the execution path somewhere or the compiler won't try to link
239  // it. We can't use it to initialise a global or class-static variable,
240  // because a smart compiler might resolve it at compile time.
241  //
242  // On the other hand, we don't want to make a useless function call too
243  // often for performance reasons. A local static variable is initialised
244  // only on the definition's first execution. Compilers will be well
245  // optimised for this behaviour, so there's a minimal one-time cost.
246  static auto const version_ok{internal::PQXX_VERSION_CHECK()};
247  ignore_unused(version_ok);
248 }
249 
250 
252 
254 struct PQXX_LIBEXPORT thread_safety_model
255 {
257  bool safe_libpq = false;
258 
260 
266  bool safe_kerberos = false;
267 
269  std::string description;
270 };
271 
272 
274 [[nodiscard]] PQXX_LIBEXPORT thread_safety_model describe_thread_safety();
275 
276 
277 #if defined(PQXX_HAVE_CONCEPTS)
278 # define PQXX_POTENTIAL_BINARY_ARG pqxx::potential_binary
279 #else
280 # define PQXX_POTENTIAL_BINARY_ARG typename
281 #endif
282 
284 
288 struct byte_char_traits : std::char_traits<char>
289 {
290  using char_type = std::byte;
291 
292  static void assign(std::byte &a, const std::byte &b) noexcept { a = b; }
293  static bool eq(std::byte a, std::byte b) { return a == b; }
294  static bool lt(std::byte a, std::byte b) { return a < b; }
295 
296  static int compare(const std::byte *a, const std::byte *b, std::size_t size)
297  {
298  return std::memcmp(a, b, size);
299  }
300 
302  /* This is nonsense: we can't determine the length of a random sequence of
303  * bytes. There is no terminating zero like there is for C strings.
304  *
305  * But `std::char_traits` requires us to provide this function, so we
306  * declare it without defining it.
307  */
308  static size_t length(const std::byte *data);
309 
310  static const std::byte *
311  find(const std::byte *data, std::size_t size, const std::byte &value)
312  {
313  return static_cast<const std::byte *>(
314  std::memchr(data, static_cast<int>(value), size));
315  }
316 
317  static std::byte *
318  move(std::byte *dest, const std::byte *src, std::size_t size)
319  {
320  return static_cast<std::byte *>(std::memmove(dest, src, size));
321  }
322 
323  static std::byte *
324  copy(std::byte *dest, const std::byte *src, std::size_t size)
325  {
326  return static_cast<std::byte *>(std::memcpy(dest, src, size));
327  }
328 
329  static std::byte *assign(std::byte *dest, std::size_t size, std::byte value)
330  {
331  return static_cast<std::byte *>(
332  std::memset(dest, static_cast<int>(value), size));
333  }
334 
336  static int_type not_eof(int_type value);
337 
338  static std::byte to_char_type(int_type value) { return std::byte(value); }
339 
340  static int_type to_int_type(std::byte value) { return int_type(value); }
341 
342  static bool eq_int_type(int_type a, int_type b) { return a == b; }
343 
345  static int_type eof();
346 };
347 
348 template<typename TYPE, typename = void>
349 struct has_generic_char_traits : std::false_type
350 {};
351 
352 template<typename TYPE>
354  TYPE, std::void_t<decltype(std::char_traits<TYPE>::eof)>> : std::true_type
355 {};
356 
357 inline constexpr bool has_generic_bytes_char_traits =
359 
360 // Supress warnings from potentially using a deprecated generic
361 // std::char_traits.
362 // Necessary for libc++ 18.
363 #include "pqxx/internal/ignore-deprecated-pre.hxx"
364 
365 // C++20: Change this type.
367 /* Required to support standard libraries without a generic implementation for
368  * `std::char_traits<std::byte>`.
369  * @warn Will change to `std::vector<std::byte>` in the next major release.
370  */
371 using bytes = std::conditional<
372  has_generic_bytes_char_traits, std::basic_string<std::byte>,
373  std::basic_string<std::byte, byte_char_traits>>::type;
374 
375 // C++20: Change this type.
377 /* Required to support standard libraries without a generic implementation for
378  * `std::char_traits<std::byte>`.
379  * @warn Will change to `std::span<std::byte>` in the next major release.
380  */
381 using bytes_view = std::conditional<
382  has_generic_bytes_char_traits, std::basic_string_view<std::byte>,
383  std::basic_string_view<std::byte, byte_char_traits>>::type;
384 
385 #include "pqxx/internal/ignore-deprecated-post.hxx"
386 
387 
389 
406 template<PQXX_POTENTIAL_BINARY_ARG TYPE>
407 bytes_view binary_cast(TYPE const &data)
408 {
409  static_assert(sizeof(value_type<TYPE>) == 1);
410  // C++20: Use std::as_bytes.
411  return {
412  reinterpret_cast<std::byte const *>(
413  const_cast<strip_t<decltype(*std::data(data))> const *>(
414  std::data(data))),
415  std::size(data)};
416 }
417 
418 
419 #if defined(PQXX_HAVE_CONCEPTS)
420 template<typename CHAR>
421 concept char_sized = (sizeof(CHAR) == 1);
422 # define PQXX_CHAR_SIZED_ARG char_sized
423 #else
424 # define PQXX_CHAR_SIZED_ARG typename
425 #endif
426 
428 
434 template<PQXX_CHAR_SIZED_ARG CHAR, typename SIZE>
435 bytes_view binary_cast(CHAR const *data, SIZE size)
436 {
437  static_assert(sizeof(CHAR) == 1);
438  return {
439  reinterpret_cast<std::byte const *>(data),
440  check_cast<std::size_t>(size, "binary data size")};
441 }
442 
443 
445 constexpr oid oid_none{0};
446 } // namespace pqxx
447 
448 
450 
459 namespace pqxx::internal
460 {
461 using namespace std::literals;
462 
463 
465 
469 template<typename CHAR> inline constexpr bool is_digit(CHAR c) noexcept
470 {
471  return (c >= '0') and (c <= '9');
472 }
473 
474 
476 
478 [[nodiscard]] std::string
479 describe_object(std::string_view class_name, std::string_view name);
480 
481 
483 
495  void const *old_guest, std::string_view old_class, std::string_view old_name,
496  void const *new_guest, std::string_view new_class,
497  std::string_view new_name);
498 
499 
501 
505  void const *old_guest, std::string_view old_class, std::string_view old_name,
506  void const *new_guest, std::string_view new_class,
507  std::string_view new_name);
508 
509 
511 
514 inline constexpr std::size_t size_esc_bin(std::size_t binary_bytes) noexcept
515 {
516  return 2 + (2 * binary_bytes) + 1;
517 }
518 
519 
521 
523 inline constexpr std::size_t size_unesc_bin(std::size_t escaped_bytes) noexcept
524 {
525  return (escaped_bytes - 2) / 2;
526 }
527 
528 
529 // TODO: Use actual binary type for "data".
531 
536 void PQXX_LIBEXPORT esc_bin(bytes_view binary_data, char buffer[]) noexcept;
537 
538 
540 std::string PQXX_LIBEXPORT esc_bin(bytes_view binary_data);
541 
542 
544 void PQXX_LIBEXPORT
545 unesc_bin(std::string_view escaped_data, std::byte buffer[]);
546 
547 
549 bytes PQXX_LIBEXPORT unesc_bin(std::string_view escaped_data);
550 
551 
553 template<typename T> auto ssize(T const &c)
554 {
555 #if defined(PQXX_HAVE_SSIZE)
556  return std::ssize(c);
557 #else
558  using signed_t = std::make_signed_t<decltype(std::size(c))>;
559  return static_cast<signed_t>(std::size(c));
560 #endif // PQXX_HAVE_SSIZe
561 }
562 
563 
565 
569 template<typename RETURN, typename... ARGS>
570 std::tuple<ARGS...> args_f(RETURN (&func)(ARGS...));
571 
572 
574 
578 template<typename RETURN, typename... ARGS>
579 std::tuple<ARGS...> args_f(std::function<RETURN(ARGS...)> const &);
580 
581 
583 
587 template<typename CLASS, typename RETURN, typename... ARGS>
588 std::tuple<ARGS...> member_args_f(RETURN (CLASS::*)(ARGS...));
589 
590 
592 
596 template<typename CLASS, typename RETURN, typename... ARGS>
597 std::tuple<ARGS...> member_args_f(RETURN (CLASS::*)(ARGS...) const);
598 
599 
601 
607 template<typename CALLABLE>
608 auto args_f(CALLABLE const &f)
609  -> decltype(member_args_f(&CALLABLE::operator()));
610 
611 
613 template<typename CALLABLE>
614 using args_t = decltype(args_f(std::declval<CALLABLE>()));
615 
616 
618 
621 template<typename... TYPES>
622 std::tuple<strip_t<TYPES>...> strip_types(std::tuple<TYPES...> const &);
623 
624 
626 template<typename... TYPES>
627 using strip_types_t = decltype(strip_types(std::declval<TYPES...>()));
628 
629 
631 inline constexpr char unescape_char(char escaped) noexcept
632 {
633  switch (escaped)
634  {
635  case 'b': // Backspace.
636  PQXX_UNLIKELY return '\b';
637  case 'f': // Form feed
638  PQXX_UNLIKELY return '\f';
639  case 'n': // Line feed.
640  return '\n';
641  case 'r': // Carriage return.
642  return '\r';
643  case 't': // Horizontal tab.
644  return '\t';
645  case 'v': // Vertical tab.
646  return '\v';
647  default: break;
648  }
649  // Regular character ("self-escaped").
650  return escaped;
651 }
652 
653 
654 // C++20: std::span?
656 template<std::size_t BYTES>
657 char const *PQXX_COLD
658 error_string(int err_num, std::array<char, BYTES> &buffer)
659 {
660  // Not entirely clear whether strerror_s will be in std or global namespace.
661  using namespace std;
662 
663 #if defined(PQXX_HAVE_STERROR_S) || defined(PQXX_HAVE_STRERROR_R)
664 # if defined(PQXX_HAVE_STRERROR_S)
665  auto const err_result{strerror_s(std::data(buffer), BYTES, err_num)};
666 # else
667  auto const err_result{strerror_r(err_num, std::data(buffer), BYTES)};
668 # endif
669  if constexpr (std::is_same_v<pqxx::strip_t<decltype(err_result)>, char *>)
670  {
671  // GNU version of strerror_r; returns the error string, which may or may
672  // not reside within buffer.
673  return err_result;
674  }
675  else
676  {
677  // Either strerror_s or POSIX strerror_r; returns an error code.
678  // Sorry for being lazy here: Not reporting error string for the case
679  // where we can't retrieve an error string.
680  if (err_result == 0)
681  return std::data(buffer);
682  else
683  return "Compound errors.";
684  }
685 
686 #else
687  // Fallback case, hopefully for no actual platforms out there.
688  pqxx::ignore_unused(err_num, buffer);
689  return "(No error information available.)";
690 #endif
691 }
692 } // namespace pqxx::internal
693 
694 
696 {
698 PQXX_LIBEXPORT void pqfreemem(void const *) noexcept;
699 } // namespace pqxx::internal::pq
700 #endif
The home of all libpqxx classes, functions, templates, etc.
Definition: array.hxx:33
std::remove_cv_t< std::remove_reference_t< TYPE > > strip_t
Remove any constness, volatile, and reference-ness from a type.
Definition: types.hxx:78
bytes_view binary_cast(TYPE const &data)
Cast binary data to a type that libpqxx will recognise as binary.
Definition: util.hxx:407
strip_t< decltype(*std::begin(std::declval< CONTAINER >()))> value_type
The type of a container's elements.
Definition: types.hxx:94
void check_version() noexcept
Definition: util.hxx:234
thread_safety_model describe_thread_safety()
Describe thread safety available in this build.
Definition: util.cxx:35
constexpr void ignore_unused(T &&...) noexcept
Suppress compiler warning about an unused item.
Definition: util.hxx:142
constexpr bool has_generic_bytes_char_traits
Definition: util.hxx:357
std::conditional< has_generic_bytes_char_traits, std::basic_string< std::byte >, std::basic_string< std::byte, byte_char_traits > >::type bytes
Type alias for a container containing bytes.
Definition: util.hxx:373
std::conditional< has_generic_bytes_char_traits, std::basic_string_view< std::byte >, std::basic_string_view< std::byte, byte_char_traits > >::type bytes_view
Type alias for a view of bytes.
Definition: util.hxx:383
constexpr oid oid_none
The "null" oid.
Definition: util.hxx:445
TO check_cast(FROM value, std::string_view description)
Cast a numeric value to another type, or throw if it underflows/overflows.
Definition: util.hxx:151
Internal items for libpqxx' own use. Do not use these yourself.
Definition: composite.hxx:84
void unesc_bin(std::string_view escaped_data, std::byte buffer[])
Reconstitute binary data from its escaped version.
Definition: util.cxx:165
int PQXX_VERSION_CHECK() noexcept
Library version check stub.
Definition: version.cxx:23
constexpr std::size_t size_esc_bin(std::size_t binary_bytes) noexcept
Compute buffer size needed to escape binary data for use as a BYTEA.
Definition: util.hxx:514
std::tuple< strip_t< TYPES >... > strip_types(std::tuple< TYPES... > const &)
Helper: Apply strip_t to each of a tuple type's component types.
std::tuple< ARGS... > args_f(RETURN(&func)(ARGS...))
Helper for determining a function's parameter types.
char const *PQXX_COLD error_string(int err_num, std::array< char, BYTES > &buffer)
Get error string for a given errno value.
Definition: util.hxx:658
std::tuple< ARGS... > member_args_f(RETURN(CLASS::*)(ARGS...))
Helper for determining a member function's parameter types.
constexpr bool cmp_less(LEFT lhs, RIGHT rhs) noexcept
Same as std::cmp_less, or a workaround where that's not available.
Definition: util.hxx:63
void check_unique_unregister(void const *old_guest, std::string_view old_class, std::string_view old_name, void const *new_guest, std::string_view new_class, std::string_view new_name)
Like check_unique_register, but for un-registering a guest.
Definition: util.cxx:80
void esc_bin(bytes_view binary_data, char buffer[]) noexcept
Hex-escape binary data into a buffer.
Definition: util.cxx:133
decltype(strip_types(std::declval< TYPES... >())) strip_types_t
Take a tuple type and apply strip_t to its component types.
Definition: util.hxx:627
void check_unique_register(void const *old_guest, std::string_view old_class, std::string_view old_name, void const *new_guest, std::string_view new_class, std::string_view new_name)
Check validity of registering a new "guest" in a "host.".
Definition: util.cxx:63
std::string describe_object(std::string_view class_name, std::string_view name)
Describe an object for humans, based on class name and optional name.
Definition: util.cxx:53
constexpr bool cmp_greater(LEFT lhs, RIGHT rhs) noexcept
C++20 std::cmp_greater, or workaround if not available.
Definition: util.hxx:85
decltype(args_f(std::declval< CALLABLE >())) args_t
A callable's parameter types, as a tuple.
Definition: util.hxx:614
constexpr bool is_digit(CHAR c) noexcept
A safer and more generic replacement for std::isdigit.
Definition: util.hxx:469
constexpr char unescape_char(char escaped) noexcept
Return original byte for escaped character.
Definition: util.hxx:631
constexpr bool cmp_greater_equal(LEFT lhs, RIGHT rhs) noexcept
C++20 std::cmp_greater_equal, or workaround if not available.
Definition: util.hxx:111
std::string cat2(std::string_view x, std::string_view y)
Efficiently concatenate two strings.
Definition: util.hxx:125
constexpr bool cmp_less_equal(LEFT lhs, RIGHT rhs) noexcept
C++20 std::cmp_less_equal, or workaround if not available.
Definition: util.hxx:98
auto ssize(T const &c)
Transitional: std::ssize(), or custom implementation if not available.
Definition: util.hxx:553
constexpr std::size_t size_unesc_bin(std::size_t escaped_bytes) noexcept
Compute binary size from the size of its escaped version.
Definition: util.hxx:523
Definition: util.hxx:696
void pqfreemem(void const *) noexcept
Wrapper for PQfreemem(), with C++ linkage.
Definition: util.cxx:205
Something is out of range, similar to std::out_of_range.
Definition: except.hxx:326
Descriptor of library's thread-safety model.
Definition: util.hxx:255
std::string description
A human-readable description of any thread-safety issues.
Definition: util.hxx:269
Custom std::char_trast if the compiler does not provide one.
Definition: util.hxx:289
static size_t length(const std::byte *data)
Deliberately undefined: "guess" the length of an array of bytes.
static void assign(std::byte &a, const std::byte &b) noexcept
Definition: util.hxx:292
static std::byte * move(std::byte *dest, const std::byte *src, std::size_t size)
Definition: util.hxx:318
static std::byte to_char_type(int_type value)
Definition: util.hxx:338
static int_type not_eof(int_type value)
Declared but not defined: makes no sense for binary data.
static bool eq(std::byte a, std::byte b)
Definition: util.hxx:293
static int_type eof()
Declared but not defined: makes no sense for binary data.
static bool lt(std::byte a, std::byte b)
Definition: util.hxx:294
static std::byte * assign(std::byte *dest, std::size_t size, std::byte value)
Definition: util.hxx:329
static int_type to_int_type(std::byte value)
Definition: util.hxx:340
static bool eq_int_type(int_type a, int_type b)
Definition: util.hxx:342
static const std::byte * find(const std::byte *data, std::size_t size, const std::byte &value)
Definition: util.hxx:311
std::byte char_type
Definition: util.hxx:290
static int compare(const std::byte *a, const std::byte *b, std::size_t size)
Definition: util.hxx:296
static std::byte * copy(std::byte *dest, const std::byte *src, std::size_t size)
Definition: util.hxx:324
Definition: util.hxx:350