| Tom Sepez | 36285ed | 2024-12-18 22:13:57 | [diff] [blame] | 1 | // Copyright 2024 The Chromium Authors |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | // |
| 5 | // This file defines printf-like functions for working with span-based |
| 6 | // buffers. |
| 7 | |
| 8 | #ifndef BASE_STRINGS_SPAN_PRINTF_H_ |
| 9 | #define BASE_STRINGS_SPAN_PRINTF_H_ |
| 10 | |
| 11 | #include <stdarg.h> // va_list |
| 12 | |
| 13 | #include "base/compiler_specific.h" |
| 14 | #include "base/containers/span.h" |
| 15 | #include "base/strings/string_util.h" |
| 16 | |
| 17 | namespace base { |
| 18 | |
| 19 | // We separate the declaration from the implementation of this inline |
| 20 | // function just so the PRINTF_FORMAT works. |
| 21 | PRINTF_FORMAT(2, 0) |
| 22 | inline int VSpanPrintf(base::span<char> buffer, |
| 23 | const char* format, |
| 24 | va_list arguments); |
| 25 | inline int VSpanPrintf(base::span<char> buffer, |
| 26 | const char* format, |
| 27 | va_list arguments) { |
| 28 | // SAFETY: buffer size obtained from span. |
| 29 | return UNSAFE_BUFFERS( |
| 30 | base::vsnprintf(buffer.data(), buffer.size(), format, arguments)); |
| 31 | } |
| 32 | |
| 33 | // We separate the declaration from the implementation of this inline |
| 34 | // function just so the PRINTF_FORMAT works. |
| 35 | PRINTF_FORMAT(2, 3) |
| 36 | inline int SpanPrintf(base::span<char> buffer, const char* format, ...); |
| 37 | inline int SpanPrintf(base::span<char> buffer, const char* format, ...) { |
| 38 | va_list arguments; |
| 39 | va_start(arguments, format); |
| 40 | int result = VSpanPrintf(buffer, format, arguments); |
| 41 | va_end(arguments); |
| 42 | return result; |
| 43 | } |
| 44 | |
| 45 | } // namespace base |
| 46 | |
| 47 | #endif // BASE_STRINGS_SPAN_PRINTF_H_ |