freebsd-src/lib/libutil++/stringf.cc
John Baldwin b3127a2dc2 libutil++: New library containing C++ utility classes for use in base
- freebsd::FILE_up is a wrapper class for std::unique_ptr<> for FILE
  objects which uses a custom deleter that calls fclose().

- freebsd::malloc_up<T> is a wrapper class for std::unique_ptr<> which
  uses a custom deleter that calls free().  It is useful for pointers
  allocated by malloc() such as strdup().

- The freebsd::stringf() functions return a std::string constructed
  using a printf format string.

  The current implementation of freebsd::stringf() uses fwopen() where
  the write function appends to a std::string.

Sponsored by:	Chelsio Communications
Pull Request:	https://github.com/freebsd/freebsd-src/pull/1794
2025-08-04 15:38:06 -04:00

57 lines
987 B
C++

/*-
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2025 Chelsio Communications, Inc.
* Written by: John Baldwin <jhb@FreeBSD.org>
*/
#include <cstdarg>
#include <cstdio>
#include <string>
#include "libutil++.hh"
static int
stringf_write(void *cookie, const char *buf, int len)
{
std::string *str = reinterpret_cast<std::string *>(cookie);
try {
str->append(buf, len);
} catch (std::bad_alloc) {
errno = ENOMEM;
return (-1);
} catch (std::length_error) {
errno = EFBIG;
return (-1);
}
return (len);
}
std::string
freebsd::stringf(const char *fmt, va_list ap)
{
std::string str;
freebsd::FILE_up fp(fwopen(reinterpret_cast<void *>(&str),
stringf_write));
vfprintf(fp.get(), fmt, ap);
if (ferror(fp.get()))
throw std::bad_alloc();
fp.reset(nullptr);
return str;
}
std::string
freebsd::stringf(const char *fmt, ...)
{
std::va_list ap;
std::string str;
va_start(ap, fmt);
str = freebsd::stringf(fmt, ap);
va_end(ap);
return str;
}