1 /* 2 * Copyright (C) 2018-2022 Intel Corporation. 3 * 4 * SPDX-License-Identifier: BSD-3-Clause 5 */ 6 7 #ifndef SPRINTF_H 8 #define SPRINTF_H 9 10 /* Command for the emit function: copy string to output. */ 11 #define PRINT_CMD_COPY 0x00000000U 12 13 /* Command for the emit function: fill output with first character. */ 14 #define PRINT_CMD_FILL 0x00000001U 15 16 /** Structure used to call back emit lived in print_param */ 17 struct snprint_param { 18 /** The destination buffer. */ 19 char *dst; 20 /** The size of the destination buffer. */ 21 uint32_t sz; 22 /** Counter for written chars. */ 23 uint32_t wrtn; 24 }; 25 26 /* Structure used to parse parameters and variables to subroutines. */ 27 struct print_param { 28 /* A pointer to the function that is used to emit characters. */ 29 void (*emit)(size_t, const char *, uint32_t, struct snprint_param *); 30 /* An opaque pointer that is passed as forth argument to the emit 31 * function. 32 */ 33 struct snprint_param *data; 34 /* Contains variables which are recalculated for each argument. */ 35 struct { 36 /* A bitfield with the parsed format flags. */ 37 uint32_t flags; 38 /* The parsed format width. */ 39 uint32_t width; 40 /* The parsed format precision. */ 41 uint32_t precision; 42 /* The bitmask for unsigned values. */ 43 uint64_t mask; 44 /* A pointer to the preformated value. */ 45 const char *value; 46 /* The number of characters in the preformated value buffer. */ 47 uint32_t valuelen; 48 /* A pointer to the values prefix. */ 49 const char *prefix; 50 /* The number of characters in the prefix buffer. */ 51 uint32_t prefixlen; 52 } vars; 53 }; 54 55 void do_print(const char *fmt_arg, struct print_param *param, 56 __builtin_va_list args); 57 58 /** The well known vsnprintf() function. 59 * 60 * Formats and writes a string with a max. size to memory. 61 * 62 * @param dst A pointer to the destination memory. 63 * @param sz The size of the destination memory. 64 * @param fmt A pointer to the NUL terminated format string. 65 * @param args The variable long argument list as va_list. 66 * @return The number of bytes which would be written, even if the destination 67 * is smaller. On error a negative number is returned. 68 */ 69 size_t vsnprintf(char *dst_arg, size_t sz_arg, const char *fmt, va_list args); 70 71 /** The well known snprintf() function. 72 * 73 * Formats a string and writes it to the console output. 74 * 75 * @param dest Pointer to the destination memory. 76 * @param sz Max. size of dest. 77 * @param fmt A pointer to the NUL terminated format string. 78 * 79 * @return The number of characters would by written or a negative 80 * number if an error occurred. 81 * 82 * @bug sz == 0 doesn't work 83 */ 84 85 size_t snprintf(char *dest, size_t sz, const char *fmt, ...); 86 87 #endif /* SPRINTF_H */ 88