Geoff Lang | da5777c | 2014-07-11 09:52:58 -0400 | [diff] [blame] | 1 | // |
| 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" |
Austin Kinross | 922a9fb | 2014-10-21 14:26:33 -0700 | [diff] [blame] | 8 | #include "debug.h" |
Olli Etuaho | 86ffde5 | 2014-10-03 14:51:54 +0300 | [diff] [blame] | 9 | #include <stdio.h> |
Geoff Lang | da5777c | 2014-07-11 09:52:58 -0400 | [diff] [blame] | 10 | #include <vector> |
| 11 | |
Austin Kinross | 922a9fb | 2014-10-21 14:26:33 -0700 | [diff] [blame] | 12 | size_t FormatStringIntoVector(const char *fmt, va_list vararg, std::vector<char>& outBuffer) |
| 13 | { |
| 14 | // Attempt to just print to the current buffer |
| 15 | int len = vsnprintf(&(outBuffer.front()), outBuffer.size(), fmt, vararg); |
| 16 | if (len < 0 || static_cast<size_t>(len) >= outBuffer.size()) |
| 17 | { |
| 18 | // Buffer was not large enough, calculate the required size and resize the buffer |
| 19 | len = vsnprintf(NULL, 0, fmt, vararg); |
| 20 | outBuffer.resize(len + 1); |
| 21 | |
| 22 | // Print again |
| 23 | len = vsnprintf(&(outBuffer.front()), outBuffer.size(), fmt, vararg); |
| 24 | } |
| 25 | ASSERT(len >= 0); |
| 26 | return static_cast<size_t>(len); |
| 27 | } |
| 28 | |
Shannon Woods | 8e7d7a3 | 2014-09-02 17:09:08 -0400 | [diff] [blame] | 29 | std::string FormatString(const char *fmt, va_list vararg) |
Geoff Lang | da5777c | 2014-07-11 09:52:58 -0400 | [diff] [blame] | 30 | { |
| 31 | static std::vector<char> buffer(512); |
| 32 | |
Austin Kinross | 922a9fb | 2014-10-21 14:26:33 -0700 | [diff] [blame] | 33 | size_t len = FormatStringIntoVector(fmt, vararg, buffer); |
Jamie Madill | b4fd0c9 | 2014-10-01 17:40:24 -0400 | [diff] [blame] | 34 | return std::string(&buffer[0], len); |
Geoff Lang | da5777c | 2014-07-11 09:52:58 -0400 | [diff] [blame] | 35 | } |
| 36 | |
Shannon Woods | 8e7d7a3 | 2014-09-02 17:09:08 -0400 | [diff] [blame] | 37 | std::string FormatString(const char *fmt, ...) |
Geoff Lang | da5777c | 2014-07-11 09:52:58 -0400 | [diff] [blame] | 38 | { |
| 39 | va_list vararg; |
| 40 | va_start(vararg, fmt); |
| 41 | std::string result = FormatString(fmt, vararg); |
| 42 | va_end(vararg); |
| 43 | return result; |
| 44 | } |