blob: 327e51888ab8c9a1f5838235d055bae4e2520bbb [file] [log] [blame]
Shawn McCarneyfe44e832024-04-18 16:03:49 -05001/**
2 * Copyright © 2024 IBM Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#pragma once
17
18#include <format>
19#include <span>
20#include <string>
21
22/**
23 * @namespace format_utils
24 *
25 * Contains utility functions for formatting data.
26 */
27namespace phosphor::power::sequencer::format_utils
28{
29
30/**
31 * Returns a string containing the elements in the specified container span.
32 *
33 * The string starts with "[", ends with "]", and the elements are separated by
34 * ", ". The individual elements are formatted using std::format.
35 *
36 * This function is a temporary solution until g++ implements the C++23
37 * std::format() support for formatting ranges.
38 *
39 * @param span span of elements to format within a container
40 * @return formatted string containing the specified elements
41 */
42template <typename T>
43std::string toString(const std::span<T>& span)
44{
45 std::string str{"["};
46 for (auto it = span.cbegin(); it != span.cend(); ++it)
47 {
48 str += std::format("{}", *it);
49 if (std::distance(it, span.cend()) > 1)
50 {
51 str += ", ";
52 }
53 }
54 str += "]";
55 return str;
56}
57
58} // namespace phosphor::power::sequencer::format_utils