1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "berberis/base/format_buffer.h"
18
19 #include <cstdarg>
20 #include <cstddef> // size_t
21
22 namespace berberis {
23
FormatBuffer(char * buf,size_t buf_size,const char * format,...)24 size_t FormatBuffer(char* buf, size_t buf_size, const char* format, ...) {
25 va_list ap;
26 va_start(ap, format);
27 size_t n = FormatBufferV(buf, buf_size, format, ap);
28 va_end(ap);
29 return n;
30 }
31
FormatBufferV(char * buf,size_t buf_size,const char * format,va_list ap)32 size_t FormatBufferV(char* buf, size_t buf_size, const char* format, va_list ap) {
33 if (!buf) {
34 return 0;
35 }
36 if (!buf_size) {
37 return 0;
38 }
39
40 CStrBuffer out(buf, buf_size - 1); // reserve space for '\0'!
41 if (format) {
42 FormatBufferVaListArgs args(ap);
43 FormatBufferImpl<CStrBuffer, FormatBufferVaListArgs>(&out, format, &args);
44 }
45 size_t n = out.Size();
46 buf[n] = '\0';
47 return n;
48 }
49
50 } // namespace berberis
51