blob: aea68dfff9f11d02a88d63ed0dcff9abad3df243 [file] [log] [blame]
Raphael Isemann80814282020-01-24 08:23:27 +01001//===-- VASprintf.cpp -----------------------------------------------------===//
Zachary Turner24ae6292017-02-16 19:38:21 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Zachary Turner24ae6292017-02-16 19:38:21 +00006//
7//===----------------------------------------------------------------------===//
8
Zachary Turnerd9c0e152017-02-16 20:15:26 +00009#include "lldb/Utility/VASPrintf.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000010
11#include "llvm/ADT/SmallString.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000012#include "llvm/ADT/SmallVector.h"
13#include "llvm/ADT/StringRef.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000014
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000015#include <assert.h>
16#include <stdarg.h>
17#include <stdio.h>
Zachary Turner24ae6292017-02-16 19:38:21 +000018
19bool lldb_private::VASprintf(llvm::SmallVectorImpl<char> &buf, const char *fmt,
20 va_list args) {
21 llvm::SmallString<16> error("<Encoding error>");
22 bool result = true;
23
24 // Copy in case our first call to vsnprintf doesn't fit into our buffer
25 va_list copy_args;
26 va_copy(copy_args, args);
27
28 buf.resize(buf.capacity());
29 // Write up to `capacity` bytes, ignoring the current size.
30 int length = ::vsnprintf(buf.data(), buf.size(), fmt, args);
31 if (length < 0) {
32 buf = error;
33 result = false;
34 goto finish;
35 }
36
Zachary Turner3bc714b2017-03-02 00:05:25 +000037 if (size_t(length) >= buf.size()) {
Adrian Prantl05097242018-04-30 16:49:04 +000038 // The error formatted string didn't fit into our buffer, resize it to the
39 // exact needed size, and retry
Zachary Turner24ae6292017-02-16 19:38:21 +000040 buf.resize(length + 1);
41 length = ::vsnprintf(buf.data(), buf.size(), fmt, copy_args);
42 if (length < 0) {
43 buf = error;
44 result = false;
45 goto finish;
46 }
Zachary Turner3bc714b2017-03-02 00:05:25 +000047 assert(size_t(length) < buf.size());
Zachary Turner24ae6292017-02-16 19:38:21 +000048 }
49 buf.resize(length);
50
51finish:
52 va_end(args);
53 va_end(copy_args);
54 return result;
55}