blob: 5eaa293cf4cf8672ad2dc91b8e1c595b233d72f5 [file] [log] [blame]
Elliott Hughes6b3be292015-02-03 14:23:53 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <utils/stringprintf.h>
18
19#include <stdio.h>
20
21void android::StringAppendV(std::string* dst, const char* format, va_list ap) {
22 // First try with a small fixed size buffer
23 char space[1024];
24
25 // It's possible for methods that use a va_list to invalidate
26 // the data in it upon use. The fix is to make a copy
27 // of the structure before using it and use that copy instead.
28 va_list backup_ap;
29 va_copy(backup_ap, ap);
30 int result = vsnprintf(space, sizeof(space), format, backup_ap);
31 va_end(backup_ap);
32
33 if (result < static_cast<int>(sizeof(space))) {
34 if (result >= 0) {
35 // Normal case -- everything fit.
36 dst->append(space, result);
37 return;
38 }
39
40 if (result < 0) {
41 // Just an error.
42 return;
43 }
44 }
45
46 // Increase the buffer size to the size requested by vsnprintf,
47 // plus one for the closing \0.
48 int length = result+1;
49 char* buf = new char[length];
50
51 // Restore the va_list before we use it again
52 va_copy(backup_ap, ap);
53 result = vsnprintf(buf, length, format, backup_ap);
54 va_end(backup_ap);
55
56 if (result >= 0 && result < length) {
57 // It fit
58 dst->append(buf, result);
59 }
60 delete[] buf;
61}
62
63std::string android::StringPrintf(const char* fmt, ...) {
64 va_list ap;
65 va_start(ap, fmt);
66 std::string result;
67 StringAppendV(&result, fmt, ap);
68 va_end(ap);
69 return result;
70}
71
72void android::StringAppendF(std::string* dst, const char* format, ...) {
73 va_list ap;
74 va_start(ap, format);
75 StringAppendV(dst, format, ap);
76 va_end(ap);
77}