The open source OpenXR runtime
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

u/truncate_printf: Add truncating helpers

authored by

Jakob Bornecrantz and committed by
Ryan Pavlik
200f1b11 299471f2

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