blob: b575f5030253062accda5187e4fb3f8f64b849ff [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>
Shawn McCarneyf47a7a72024-04-18 16:59:33 -050019#include <iterator>
Shawn McCarneyfe44e832024-04-18 16:03:49 -050020#include <span>
21#include <string>
22
23/**
24 * @namespace format_utils
25 *
26 * Contains utility functions for formatting data.
27 */
28namespace phosphor::power::sequencer::format_utils
29{
30
31/**
32 * Returns a string containing the elements in the specified container span.
33 *
34 * The string starts with "[", ends with "]", and the elements are separated by
35 * ", ". The individual elements are formatted using std::format.
36 *
37 * This function is a temporary solution until g++ implements the C++23
38 * std::format() support for formatting ranges.
39 *
40 * @param span span of elements to format within a container
41 * @return formatted string containing the specified elements
42 */
43template <typename T>
44std::string toString(const std::span<T>& span)
45{
46 std::string str{"["};
47 for (auto it = span.cbegin(); it != span.cend(); ++it)
48 {
49 str += std::format("{}", *it);
50 if (std::distance(it, span.cend()) > 1)
51 {
52 str += ", ";
53 }
54 }
55 str += "]";
56 return str;
57}
58
59} // namespace phosphor::power::sequencer::format_utils