blob: 4368a3738307c5fc0f86a7b02de9b6e0c944672c [file] [log] [blame]
Zachary Turner24ae6292017-02-16 19:38:21 +00001//===-- VASPrintf.cpp -------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Zachary Turnerd9c0e152017-02-16 20:15:26 +000010#include "lldb/Utility/VASPrintf.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000011
12#include "llvm/ADT/SmallString.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000013#include "llvm/ADT/SmallVector.h"
14#include "llvm/ADT/StringRef.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000015
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000016#include <assert.h>
17#include <stdarg.h>
18#include <stdio.h>
Zachary Turner24ae6292017-02-16 19:38:21 +000019
20bool lldb_private::VASprintf(llvm::SmallVectorImpl<char> &buf, const char *fmt,
21 va_list args) {
22 llvm::SmallString<16> error("<Encoding error>");
23 bool result = true;
24
25 // Copy in case our first call to vsnprintf doesn't fit into our buffer
26 va_list copy_args;
27 va_copy(copy_args, args);
28
29 buf.resize(buf.capacity());
30 // Write up to `capacity` bytes, ignoring the current size.
31 int length = ::vsnprintf(buf.data(), buf.size(), fmt, args);
32 if (length < 0) {
33 buf = error;
34 result = false;
35 goto finish;
36 }
37
Zachary Turner3bc714b2017-03-02 00:05:25 +000038 if (size_t(length) >= buf.size()) {
Adrian Prantl05097242018-04-30 16:49:04 +000039 // The error formatted string didn't fit into our buffer, resize it to the
40 // exact needed size, and retry
Zachary Turner24ae6292017-02-16 19:38:21 +000041 buf.resize(length + 1);
42 length = ::vsnprintf(buf.data(), buf.size(), fmt, copy_args);
43 if (length < 0) {
44 buf = error;
45 result = false;
46 goto finish;
47 }
Zachary Turner3bc714b2017-03-02 00:05:25 +000048 assert(size_t(length) < buf.size());
Zachary Turner24ae6292017-02-16 19:38:21 +000049 }
50 buf.resize(length);
51
52finish:
53 va_end(args);
54 va_end(copy_args);
55 return result;
56}