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 <cstdarg> 12 #include <cstdio> 13 #include <cstdlib> 14 #include <memory> 15 16 namespace freebsd { 17 /* 18 * FILE_up is a std::unique_ptr<> for FILE objects which uses 19 * fclose() to destroy the wrapped pointer. 20 */ 21 struct fclose_deleter { 22 void operator() (std::FILE *fp) const 23 { 24 std::fclose(fp); 25 } 26 }; 27 28 using FILE_up = std::unique_ptr<std::FILE, fclose_deleter>; 29 30 /* 31 * malloc_up<T> is a std::unique_ptr<> which uses free() to 32 * destroy the wrapped pointer. This can be used to wrap 33 * pointers allocated implicitly by malloc() such as those 34 * returned by strdup(). 35 */ 36 template <class T> 37 struct free_deleter { 38 void operator() (T *p) const 39 { 40 std::free(p); 41 } 42 }; 43 44 template <class T> 45 using malloc_up = std::unique_ptr<T, free_deleter<T>>; 46 47 /* 48 * Returns a std::string containing the same output as 49 * sprintf(). Throws std::bad_alloc if an error occurs. 50 */ 51 std::string stringf(const char *fmt, ...) __printflike(1, 2); 52 std::string stringf(const char *fmt, std::va_list ap); 53 } 54 55 #endif /* !__LIBUTILPP_HH__ */ 56