• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
26 #include "pw_preprocessor/compiler.h"
27 #include "pw_span/span.h"
28 #include "pw_status/status_with_size.h"
29 
30 namespace pw::string {
31 
32 /// @brief Writes a printf-style formatted string to the provided buffer,
33 /// similarly to `std::snprintf()`.
34 ///
35 /// The `std::snprintf()` return value is awkward to interpret, and
36 /// misinterpreting it can lead to serious bugs.
37 ///
38 /// @returns The number of characters written, excluding the null
39 /// terminator. The buffer is always null-terminated unless it is empty.
40 /// The status is `OkStatus()` if the operation succeeded,
41 /// `Status::ResourceExhausted()` if the buffer was too small to fit the output,
42 /// or `Status::InvalidArgument()` if there was a formatting error.
43 PW_PRINTF_FORMAT(2, 3)
44 StatusWithSize Format(span<char> buffer, const char* format, ...);
45 
46 /// @brief Writes a printf-style formatted string with va_list-packed arguments
47 /// to the provided buffer, similarly to `std::vsnprintf()`.
48 ///
49 /// @returns See `pw::string::Format()`.
50 PW_PRINTF_FORMAT(2, 0)
51 StatusWithSize FormatVaList(span<char> buffer,
52                             const char* format,
53                             va_list args);
54 
55 }  // namespace pw::string
56