1 | // Copyright (C) 2016 The Qt Company Ltd. |
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
3 | |
4 | #include "qplatformdefs.h" |
5 | |
6 | #include "qbytearray.h" |
7 | #include "qstring.h" |
8 | |
9 | #include "string.h" |
10 | |
11 | QT_BEGIN_NAMESPACE |
12 | |
13 | #if !defined(QT_VSNPRINTF) || defined(Q_QDOC) |
14 | |
15 | /*! |
16 | \relates QByteArray |
17 | |
18 | A portable \c vsnprintf() function. Will call \c ::vsnprintf(), \c |
19 | ::_vsnprintf(), or \c ::vsnprintf_s depending on the system, or |
20 | fall back to an internal version. |
21 | |
22 | \a fmt is the \c printf() format string. The result is put into |
23 | \a str, which is a buffer of at least \a n bytes. |
24 | |
25 | The caller is responsible to call \c va_end() on \a ap. |
26 | |
27 | \warning Since vsnprintf() shows different behavior on certain |
28 | platforms, you should not rely on the return value or on the fact |
29 | that you will always get a 0 terminated string back. |
30 | |
31 | Ideally, you should never call this function but use QString::asprintf() |
32 | instead. |
33 | |
34 | \sa qsnprintf(), QString::asprintf() |
35 | */ |
36 | |
37 | int qvsnprintf(char *str, size_t n, const char *fmt, va_list ap) |
38 | { |
39 | if (!str || !fmt) |
40 | return -1; |
41 | |
42 | const QByteArray ba = QString::vasprintf(fmt, ap).toLocal8Bit(); |
43 | |
44 | if (n > 0) { |
45 | size_t blen = qMin(size_t(ba.length()), size_t(n - 1)); |
46 | memcpy(str, ba.constData(), blen); |
47 | str[blen] = '\0'; // make sure str is always 0 terminated |
48 | } |
49 | |
50 | return ba.length(); |
51 | } |
52 | |
53 | #else |
54 | |
55 | QT_BEGIN_INCLUDE_NAMESPACE |
56 | #include <stdio.h> |
57 | QT_END_INCLUDE_NAMESPACE |
58 | |
59 | int qvsnprintf(char *str, size_t n, const char *fmt, va_list ap) |
60 | { |
61 | return QT_VSNPRINTF(s: str, maxlen: n, format: fmt, arg: ap); |
62 | } |
63 | |
64 | #endif |
65 | |
66 | /*! |
67 | \target bytearray-qsnprintf |
68 | \relates QByteArray |
69 | |
70 | A portable snprintf() function, calls qvsnprintf. |
71 | |
72 | \a fmt is the \c printf() format string. The result is put into |
73 | \a str, which is a buffer of at least \a n bytes. |
74 | |
75 | \warning Call this function only when you know what you are doing |
76 | since it shows different behavior on certain platforms. |
77 | Use QString::asprintf() to format a string instead. |
78 | |
79 | \sa qvsnprintf(), QString::asprintf() |
80 | */ |
81 | |
82 | int qsnprintf(char *str, size_t n, const char *fmt, ...) |
83 | { |
84 | va_list ap; |
85 | va_start(ap, fmt); |
86 | |
87 | int ret = qvsnprintf(str, n, fmt, ap); |
88 | va_end(ap); |
89 | |
90 | return ret; |
91 | } |
92 | |
93 | QT_END_NAMESPACE |
94 | |