Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_string / format.cc
1 // Copyright 2019 The Pigweed Authors
2 //
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
5 // the License at
6 //
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
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_string/format.h"
16
17 #include <cstdio>
18
19 namespace pw::string {
20
21 StatusWithSize Format(std::span<char> buffer, const char* format, ...) {
22   va_list args;
23   va_start(args, format);
24   const StatusWithSize result = FormatVaList(buffer, format, args);
25   va_end(args);
26
27   return result;
28 }
29
30 StatusWithSize FormatVaList(std::span<char> buffer,
31                             const char* format,
32                             va_list args) {
33   if (buffer.empty()) {
34     return StatusWithSize::ResourceExhausted();
35   }
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';
43     return StatusWithSize::InvalidArgument();
44   }
45
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);
49   }
50
51   return StatusWithSize(result);
52 }
53
54 }  // namespace pw::string