Files
android/libwvdrmengine/cdm/util/src/string_format.cpp
John "Juce" Bruce ff73463d0b Add String Formatting Util
(Merged from http://go/wvgerrit/160042.)

Since we don't have access to std::format yet, this patch adds a
function to wvutil to format text into a std::string.

Bug: 255466913
Test: x86-64
Test: raven
Change-Id: I28043da76af5b4772a29fa7e7241343caf9b54a1
2022-11-15 05:24:19 +00:00

41 lines
988 B
C++

// Copyright 2022 Google LLC. All Rights Reserved. This file and proprietary
// source code may only be used and distributed under the Widevine License
// Agreement.
#include "string_format.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory>
namespace wvutil {
bool FormatString(std::string* out, const char* fmt, ...) {
if (out == nullptr || fmt == nullptr) return false;
va_list ap1;
va_start(ap1, fmt);
const int desired_size = vsnprintf(nullptr, 0, fmt, ap1);
va_end(ap1);
if (desired_size < 0) return false;
const size_t buffer_size =
static_cast<size_t>(desired_size) + 1; // +1 for null
std::unique_ptr<char[]> buffer(new char[buffer_size]);
va_list ap2;
va_start(ap2, fmt);
const int actual_size = vsnprintf(buffer.get(), buffer_size, fmt, ap2);
va_end(ap2);
if (actual_size != desired_size) return false;
out->assign(buffer.get(), actual_size);
return true;
}
} // namespace wvutil