blob: 05348a49153c1b15c4610aeb4938ef26c00ce249 [file] [log] [blame]
Geoff Langda5777c2014-07-11 09:52:58 -04001//
2// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
7#include "common/angleutils.h"
Geoff Lang22072132014-11-20 15:15:01 -05008#include "common/debug.h"
9
Olli Etuaho86ffde52014-10-03 14:51:54 +030010#include <stdio.h>
Jamie Madillc9bdeff2016-02-08 12:36:55 -050011
12#include <limits>
Geoff Langda5777c2014-07-11 09:52:58 -040013#include <vector>
14
Jamie Madillc9bdeff2016-02-08 12:36:55 -050015namespace angle
16{
17const uintptr_t DirtyPointer = std::numeric_limits<uintptr_t>::max();
18}
19
Austin Kinross922a9fb2014-10-21 14:26:33 -070020size_t FormatStringIntoVector(const char *fmt, va_list vararg, std::vector<char>& outBuffer)
21{
Corentin Walleza8ccb952016-12-16 15:12:57 -050022 // The state of the va_list passed to vsnprintf is undefined after the call, do a copy in case
23 // we need to grow the buffer.
24 va_list varargCopy;
25 va_copy(varargCopy, vararg);
26
Austin Kinross922a9fb2014-10-21 14:26:33 -070027 // Attempt to just print to the current buffer
Corentin Walleza8ccb952016-12-16 15:12:57 -050028 int len = vsnprintf(&(outBuffer.front()), outBuffer.size(), fmt, varargCopy);
29 va_end(varargCopy);
30
Austin Kinross922a9fb2014-10-21 14:26:33 -070031 if (len < 0 || static_cast<size_t>(len) >= outBuffer.size())
32 {
33 // Buffer was not large enough, calculate the required size and resize the buffer
34 len = vsnprintf(NULL, 0, fmt, vararg);
35 outBuffer.resize(len + 1);
36
37 // Print again
Corentin Walleza8ccb952016-12-16 15:12:57 -050038 va_copy(varargCopy, vararg);
39 len = vsnprintf(&(outBuffer.front()), outBuffer.size(), fmt, varargCopy);
40 va_end(varargCopy);
Austin Kinross922a9fb2014-10-21 14:26:33 -070041 }
42 ASSERT(len >= 0);
43 return static_cast<size_t>(len);
44}
45
Shannon Woods8e7d7a32014-09-02 17:09:08 -040046std::string FormatString(const char *fmt, va_list vararg)
Geoff Langda5777c2014-07-11 09:52:58 -040047{
Jamie Madille4ea2022015-03-26 20:35:05 +000048 static std::vector<char> buffer(512);
Geoff Langda5777c2014-07-11 09:52:58 -040049
Austin Kinross922a9fb2014-10-21 14:26:33 -070050 size_t len = FormatStringIntoVector(fmt, vararg, buffer);
Jamie Madillb4fd0c92014-10-01 17:40:24 -040051 return std::string(&buffer[0], len);
Geoff Langda5777c2014-07-11 09:52:58 -040052}
53
Shannon Woods8e7d7a32014-09-02 17:09:08 -040054std::string FormatString(const char *fmt, ...)
Geoff Langda5777c2014-07-11 09:52:58 -040055{
56 va_list vararg;
57 va_start(vararg, fmt);
58 std::string result = FormatString(fmt, vararg);
59 va_end(vararg);
60 return result;
61}