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 #pragma once 15 16 // This provides the pw::string::Format functions, which are safer alternatives 17 // to std::snprintf and std::vsnprintf. The snprintf return value is awkward to 18 // interpret, and misinterpreting it can lead to serious bugs. 19 // 20 // These functions return a StatusWithSize. The Status is set to reflect any 21 // errors and the return value is always the number of characters written before 22 // the null terminator. 23 24 #include <cstdarg> 25 #include <span> 26 27 #include "pw_preprocessor/compiler.h" 28 #include "pw_status/status_with_size.h" 29 30 namespace pw::string { 31 32 // Writes a printf-style formatted string to the provided buffer, similarly to 33 // std::snprintf. Returns the number of characters written, excluding the null 34 // terminator. The buffer is always null-terminated unless it is empty. 35 // 36 // The status is 37 // 38 // OkStatus() if the operation succeeded, 39 // Status::ResourceExhausted() if the buffer was too small to fit the output, 40 // Status::InvalidArgument() if there was a formatting error. 41 // 42 PW_PRINTF_FORMAT(2, 3) 43 StatusWithSize Format(std::span<char> buffer, const char* format, ...); 44 45 // Writes a printf-style formatted string with va_list-packed arguments to the 46 // provided buffer, similarly to std::vsnprintf. The return value is the same as 47 // above. 48 StatusWithSize FormatVaList(std::span<char> buffer, 49 const char* format, 50 va_list args); 51 52 } // namespace pw::string 53