LibreOffice Module o3tl (master) 1
sprintf.hxx
Go to the documentation of this file.
1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
9
10#pragma once
11
12#include <sal/config.h>
13
14#include <cassert>
15#include <cstddef>
16#include <cstdio>
17#include <utility>
18
19#include <o3tl/safeint.hxx>
20
21namespace o3tl
22{
23// A drop-in replacement for safe uses of std::sprintf where it is statically known that the
24// provided buffer is large enough. Compared to a plain use of std::sprintf, using o3tl::sprintf
25// for one makes it explicit that the call is considered safe and for another avoids deprecation
26// warnings on platforms like the macOS 13 SDK that mark std::sprintf as deprecated. Many simple
27// uses of std::sprintf across the code base can be replaced with alternative code using e.g.
28// OString::number. This is for the remaining formatting-rich cases for which there is no easy
29// replacement yet in our C++17 baseline. Ultimately, it should be removed again once alternatives
30// for those remaining cases, like C++20 std::format, are available.
31template <std::size_t N, typename... T>
32int sprintf(char (&s)[N], char const* format, T&&... arguments)
33{
34 auto const n = std::snprintf(s, N, format, std::forward<T>(arguments)...);
35 assert(n < 0 || o3tl::make_unsigned(n) < N);
36 (void)n;
37 return n;
38}
39}
40
41/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */
sal_Int64 n
constexpr std::enable_if_t< std::is_signed_v< T >, std::make_unsigned_t< T > > make_unsigned(T value)
Definition: safeint.hxx:205
int sprintf(char(&s)[N], char const *format, T &&... arguments)
Definition: sprintf.hxx:32
#define N