Wyatt Hepler | e2dc6d1 | 2019-11-15 09:05:07 -0800 | [diff] [blame] | 1 | // Copyright 2019 The Pigweed Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not |
Wyatt Hepler | 1a96094 | 2019-11-26 14:13:38 -0800 | [diff] [blame] | 4 | // use this file except in compliance with the License. You may obtain a copy of |
| 5 | // the License at |
Wyatt Hepler | e2dc6d1 | 2019-11-15 09:05:07 -0800 | [diff] [blame] | 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 |
Wyatt Hepler | 1a96094 | 2019-11-26 14:13:38 -0800 | [diff] [blame] | 12 | // License for the specific language governing permissions and limitations under |
| 13 | // the License. |
Wyatt Hepler | e2dc6d1 | 2019-11-15 09:05:07 -0800 | [diff] [blame] | 14 | |
| 15 | #include "pw_string/format.h" |
| 16 | |
| 17 | #include <cstdio> |
| 18 | |
| 19 | namespace pw::string { |
| 20 | |
| 21 | StatusWithSize Format(const span<char>& buffer, const char* format, ...) { |
| 22 | va_list args; |
| 23 | va_start(args, format); |
Wyatt Hepler | 2596fe5 | 2020-01-23 17:40:10 -0800 | [diff] [blame] | 24 | const StatusWithSize result = FormatVaList(buffer, format, args); |
Wyatt Hepler | e2dc6d1 | 2019-11-15 09:05:07 -0800 | [diff] [blame] | 25 | va_end(args); |
| 26 | |
| 27 | return result; |
| 28 | } |
| 29 | |
Wyatt Hepler | 2596fe5 | 2020-01-23 17:40:10 -0800 | [diff] [blame] | 30 | StatusWithSize FormatVaList(const span<char>& buffer, |
| 31 | const char* format, |
| 32 | va_list args) { |
Wyatt Hepler | e2dc6d1 | 2019-11-15 09:05:07 -0800 | [diff] [blame] | 33 | if (buffer.empty()) { |
Wyatt Hepler | f707880 | 2020-02-25 13:50:05 -0800 | [diff] [blame] | 34 | return StatusWithSize::RESOURCE_EXHAUSTED; |
Wyatt Hepler | e2dc6d1 | 2019-11-15 09:05:07 -0800 | [diff] [blame] | 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'; |
Wyatt Hepler | f707880 | 2020-02-25 13:50:05 -0800 | [diff] [blame] | 43 | return StatusWithSize::INVALID_ARGUMENT; |
Wyatt Hepler | e2dc6d1 | 2019-11-15 09:05:07 -0800 | [diff] [blame] | 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(Status::RESOURCE_EXHAUSTED, buffer.size() - 1); |
| 49 | } |
| 50 | |
| 51 | return StatusWithSize(result); |
| 52 | } |
| 53 | |
| 54 | } // namespace pw::string |