Monado OpenXR Runtime
Loading...
Searching...
No Matches
u_truncate_printf.h
Go to the documentation of this file.
1// Copyright 2023, Collabora, Ltd.
2// Copyright 2026, NVIDIA CORPORATION.
3// SPDX-License-Identifier: BSL-1.0
4/*!
5 * @file
6 * @brief Truncating versions of string printing functions.
7 * @author Jakob Bornecrantz <jakob@collabora.com>
8 * @ingroup aux_util
9 */
10
11#pragma once
12
13#include "xrt/xrt_compiler.h"
14
15#include <stdio.h>
16#include <stdarg.h>
17#include <limits.h>
18
19
20#ifdef __cplusplus
21extern "C" {
22#endif
23
24
25/*!
26 * We want to truncate the value, not get the possible written.
27 *
28 * There are no version of the *many* Windows versions of this functions that
29 * truncates and returns the number of bytes written (not including null). Also
30 * need to have the same behaviour on Linux.
31 *
32 * @ingroup @aux_util
33 */
34static inline int
35u_truncate_vsnprintf(char *chars, size_t char_count, const char *fmt, va_list args)
36{
37 /*
38 * We always want to be able to write null terminator, and
39 * something probably went wrong if char_count larger then INT_MAX.
40 */
41 if (char_count == 0 || char_count > INT_MAX) {
42 return -1;
43 }
44
45 // Will always be able to write null terminator.
46 int ret = vsnprintf(chars, char_count, fmt, args);
47 if (ret < 0) {
48 return ret;
49 }
50
51 // Safe, ret is checked for negative above.
52 if ((size_t)ret > char_count - 1) {
53 return (int)char_count - 1;
54 }
55
56 return ret;
57}
58
59// Cannot use the XRT_PRINTF_FORMAT macro on a function definition.
60static inline int
61u_truncate_snprintf(char *chars, size_t char_count, const char *fmt, ...) XRT_PRINTF_FORMAT(3, 4);
62
63/*!
64 * We want to truncate the value, not get the possible written, and error when
65 * we can not write out anything.
66 *
67 * See @ref u_truncate_vsnprintf for more info.
68 *
69 * @ingroup @aux_util
70 */
71static inline int
72u_truncate_snprintf(char *chars, size_t char_count, const char *fmt, ...)
73{
74 /*
75 * We always want to be able to write null terminator, and
76 * something probably went wrong if char_count larger then INT_MAX.
77 */
78 if (char_count == 0 || char_count > INT_MAX) {
79 return -1;
80 }
81
82 va_list args;
83 va_start(args, fmt);
84 int ret = u_truncate_vsnprintf(chars, char_count, fmt, args);
85 va_end(args);
86
87 return ret;
88}
89
90
91#ifdef __cplusplus
92}
93#endif
static int u_truncate_snprintf(char *chars, size_t char_count, const char *fmt,...) XRT_PRINTF_FORMAT(3
We want to truncate the value, not get the possible written, and error when we can not write out anyt...
Definition u_truncate_printf.h:72
static int u_truncate_vsnprintf(char *chars, size_t char_count, const char *fmt, va_list args)
We want to truncate the value, not get the possible written.
Definition u_truncate_printf.h:35
Header holding common defines.