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
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.
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.
27 #include "pw_preprocessor/compiler.h"
28 #include "pw_status/status_with_size.h"
30 namespace pw::string {
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.
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.
42 PW_PRINTF_FORMAT(2, 3)
43 StatusWithSize Format(std::span<char> buffer, const char* format, ...);
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
48 StatusWithSize FormatVaList(std::span<char> buffer,
52 } // namespace pw::string