1 // Copyright 2019 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
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
12 // License for the specific language governing permissions and limitations under
15 #include "pw_string/format.h"
19 namespace pw::string {
21 StatusWithSize Format(std::span<char> buffer, const char* format, ...) {
23 va_start(args, format);
24 const StatusWithSize result = FormatVaList(buffer, format, args);
30 StatusWithSize FormatVaList(std::span<char> buffer,
34 return StatusWithSize::ResourceExhausted();
37 const int result = std::vsnprintf(buffer.data(), buffer.size(), format, args);
39 // If an error occurred, the number of characters written is unknown.
40 // Discard any output by terminating the buffer.
43 return StatusWithSize::InvalidArgument();
46 // If result >= buffer.size(), the output was truncated and null-terminated.
47 if (static_cast<unsigned>(result) >= buffer.size()) {
48 return StatusWithSize::ResourceExhausted(buffer.size() - 1);
51 return StatusWithSize(result);
54 } // namespace pw::string