1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause 3 * 4 * Copyright (c) 2025 Chelsio Communications, Inc. 5 * Written by: John Baldwin <jhb@FreeBSD.org> 6 */ 7 8 #ifndef __LIBUTILPP_HH__ 9 #define __LIBUTILPP_HH__ 10 11 #include <netdb.h> 12 13 #include <cstdarg> 14 #include <cstdio> 15 #include <cstdlib> 16 #include <memory> 17 18 namespace freebsd { 19 /* 20 * FILE_up is a std::unique_ptr<> for FILE objects which uses 21 * fclose() to destroy the wrapped pointer. 22 */ 23 struct fclose_deleter { 24 void operator() (std::FILE *fp) const 25 { 26 std::fclose(fp); 27 } 28 }; 29 30 using FILE_up = std::unique_ptr<std::FILE, fclose_deleter>; 31 32 /* 33 * addrinfo_up is a std::unique_ptr<> which uses 34 * freeaddrinfo() to destroy the wrapped pointer. It is 35 * intended to wrap arrays allocated by getaddrinfo(). 36 */ 37 struct freeaddrinfo_deleter { 38 void operator() (struct addrinfo *ai) const 39 { 40 freeaddrinfo(ai); 41 } 42 }; 43 44 using addrinfo_up = std::unique_ptr<addrinfo, freeaddrinfo_deleter>; 45 46 /* 47 * malloc_up<T> is a std::unique_ptr<> which uses free() to 48 * destroy the wrapped pointer. This can be used to wrap 49 * pointers allocated implicitly by malloc() such as those 50 * returned by strdup(). 51 */ 52 template <class T> 53 struct free_deleter { 54 void operator() (T *p) const 55 { 56 std::free(p); 57 } 58 }; 59 60 template <class T> 61 using malloc_up = std::unique_ptr<T, free_deleter<T>>; 62 63 /* 64 * Returns a std::string containing the same output as 65 * sprintf(). Throws std::bad_alloc if an error occurs. 66 */ 67 std::string stringf(const char *fmt, ...) __printflike(1, 2); 68 std::string stringf(const char *fmt, std::va_list ap); 69 } 70 71 #endif /* !__LIBUTILPP_HH__ */ 72