Generic C++ templates/library for FreeBSD base
- Reply: Gleb Popov : "Re: Generic C++ templates/library for FreeBSD base"
- Go to: [ bottom of page ] [ top of archives ] [ this month ]
Date: Thu, 13 Mar 2025 20:53:17 UTC
One of the projects I have been working on is converting ctld to C++ as part of adding NVMeoF support. Along the way I've written a few things that I think are generic and would be useful in other parts of the base system using C++. One is a stringf() function that accepts printf() style format string and arguments and returns a std::string. I know C++23 adds <format>, but we can't assume that yet, and this function is probably more useful when adapting existing C code. Compared to some other solutions, I chose to wrap asprintf() and do an extra copy at the end into a std::string rather than calling vsnprintf() twice. It seems less ugly than the vsnprintf() solutions also: https://github.com/freebsd/freebsd-src/commit/01bd3d89ddf9ccbf884e52fe7289e8a9278e2d63 The other things I've added are a couple of unique_ptr<> wrappers that use custom deleters. One is malloc_up<> (I've copied a convention from GDB of using a _up suffix for these) that uses free() as its deleter. It's useful for things like strdup(): https://github.com/freebsd/freebsd-src/commit/a4f299fcad78be42a522aa26ec1cfddc5db986d8 The other is a FILE_up that wraps a FILE * and uses fclose() as its deleter buried as part of a larger change: https://github.com/freebsd/freebsd-src/commit/77b800022b18ab61983b22022b16943355b2bf75 I wonder if we don't instead want a standalone library for these sorts of things, maybe a <freebsd> header with a freebsd namespace so that you'd have freebsd::malloc_up<>, freebsd::stringf, etc.? I'm not quite sure what to call the library for bits that aren't just templates (such as the stringf implementation). I'm tempted to call it libutil++, but the mismatch with the header name is a bit odd. Thoughts? -- John Baldwin