xref: /openbmc/phosphor-logging/extensions/openpower-pels/json_utils.hpp (revision 81a91e3ee4bf962111cf555ab9d3c3c51000fa3b)
1 #pragma once
2 
3 #include <ctype.h>
4 #include <stdio.h>
5 
6 #include <fstream>
7 #include <iomanip>
8 #include <iostream>
9 #include <string>
10 #include <vector>
11 
12 namespace openpower
13 {
14 namespace pels
15 {
16 const uint8_t indentLevel = 4;
17 const uint8_t colAlign = 32;
18 /**
19  * @brief escape json - use it for PEL hex dumps.
20  * @param[in] std::string - the unescaped JSON as a string literal
21  * @return std::string - escaped JSON string literal
22  */
23 std::string escapeJSON(const std::string& input);
24 
25 /**
26  * @brief get hex dump for PEL section in json format.
27  * @param[in] const void* data - Raw PEL data
28  * @param[i] size_t size - size of Raw PEL
29  * @param[in] size_t indentCount - The number of indent levels to indent
30  * @return char * - the Hex dump
31  */
32 char* dumpHex(const void* data, size_t size, size_t indentCount);
33 
34 /**
35  * @brief Inserts key-value into a JSON string
36  *
37  * @param[in] jsonStr - The JSON string
38  * @param[in] fieldName - The JSON key to insert
39  * @param[in] fieldValue - The JSON value to insert
40  * @param[in] indentCount - Indent count for the line
41  */
42 void jsonInsert(std::string& jsonStr, const std::string& fieldName,
43                 std::string fieldValue, uint8_t indentCount);
44 
45 /**
46  * @brief Inserts key-value array into a JSON string
47  *
48  * @param[in] jsonStr - The JSON string
49  * @param[in] fieldName - The JSON key to insert
50  * @param[in] values - The JSON array to insert
51  * @param[in] indentCount - Indent count for the line
52  */
53 void jsonInsertArray(std::string& jsonStr, const std::string& fieldName,
54                      std::vector<std::string>& values, uint8_t indentCount);
55 
56 /**
57  * @brief Converts an integer to a formatted string
58  * @param[in] format - the format of output string
59  * @param[in] number - the integer to convert
60  * @return std::string - the formatted string
61  */
62 template <typename T>
63 std::string getNumberString(const char* format, T number)
64 {
65     char* value = nullptr;
66     std::string numString;
67 
68     static_assert(std::is_integral<T>::value, "Integral required.");
69 
70     int len = asprintf(&value, format, number);
71     if (len)
72     {
73         numString = value;
74     }
75     free(value);
76 
77     return numString;
78 }
79 
80 /**
81  * @brief helper function to trim trailing whitespaces
82  * @return std::string - trimmed string
83  * @param[in] std::string - string to trim
84  */
85 std::string trimEnd(std::string s);
86 
87 } // namespace pels
88 } // namespace openpower
89