blob: c08bf3c035faf9b3807396bfb5598b38d47d46a6 [file] [log] [blame]
Wyatt Heplere2dc6d12019-11-15 09:05:07 -08001// Copyright 2019 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
Wyatt Hepler1a960942019-11-26 14:13:38 -08004// use this file except in compliance with the License. You may obtain a copy of
5// the License at
Wyatt Heplere2dc6d12019-11-15 09:05:07 -08006//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
Wyatt Hepler1a960942019-11-26 14:13:38 -080012// License for the specific language governing permissions and limitations under
13// the License.
Wyatt Heplere2dc6d12019-11-15 09:05:07 -080014
15#include "pw_string/format.h"
16
17#include <cstdio>
18
19namespace pw::string {
20
Wyatt Hepler6d1a6c62020-06-22 15:40:45 -070021StatusWithSize Format(std::span<char> buffer, const char* format, ...) {
Wyatt Heplere2dc6d12019-11-15 09:05:07 -080022 va_list args;
23 va_start(args, format);
Wyatt Hepler2596fe52020-01-23 17:40:10 -080024 const StatusWithSize result = FormatVaList(buffer, format, args);
Wyatt Heplere2dc6d12019-11-15 09:05:07 -080025 va_end(args);
26
27 return result;
28}
29
Wyatt Hepler6d1a6c62020-06-22 15:40:45 -070030StatusWithSize FormatVaList(std::span<char> buffer,
Wyatt Hepler2596fe52020-01-23 17:40:10 -080031 const char* format,
32 va_list args) {
Wyatt Heplere2dc6d12019-11-15 09:05:07 -080033 if (buffer.empty()) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070034 return StatusWithSize::ResourceExhausted();
Wyatt Heplere2dc6d12019-11-15 09:05:07 -080035 }
36
37 const int result = std::vsnprintf(buffer.data(), buffer.size(), format, args);
38
39 // If an error occurred, the number of characters written is unknown.
40 // Discard any output by terminating the buffer.
41 if (result < 0) {
42 buffer[0] = '\0';
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070043 return StatusWithSize::InvalidArgument();
Wyatt Heplere2dc6d12019-11-15 09:05:07 -080044 }
45
46 // If result >= buffer.size(), the output was truncated and null-terminated.
47 if (static_cast<unsigned>(result) >= buffer.size()) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070048 return StatusWithSize::ResourceExhausted(buffer.size() - 1);
Wyatt Heplere2dc6d12019-11-15 09:05:07 -080049 }
50
51 return StatusWithSize(result);
52}
53
54} // namespace pw::string