Version 7.6.3.2-android, tag libreoffice-7.6.3.2-android
[LibreOffice.git] / include / o3tl / sprintf.hxx
blob373fff744c910344ebbc5a9ee04d4f1398e83adc
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.
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 */
10 #pragma once
12 #include <sal/config.h>
14 #include <cassert>
15 #include <cstddef>
16 #include <cstdio>
17 #include <utility>
19 #include <o3tl/safeint.hxx>
21 namespace o3tl
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.
31 template <std::size_t N, typename... T>
32 int sprintf(char (&s)[N], char const* format, T&&... arguments)
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;
41 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */