1 #pragma once
2 #include <sstream>
3 #include <string>
4 
5 namespace witherspoon
6 {
7 namespace power
8 {
9 namespace util
10 {
11 
12 /**
13  * @class NamesValues
14  *
15  * Builds up a string of name=value pairs for use in
16  * situations like error log metadata.
17  *
18  * Names and values can be added to an instance of this
19  * class, and then calling get() will return a string
20  * that appends them all together.
21  *
22  * Currently, just uint64_t values that will be displayed
23  * in hex are supported.
24  *
25  * For example:
26  *     NamesValues m;
27  *     uint8_t d = 0xFF;
28  *
29  *     m.add("STATUS_VOUT", d);
30  *     m.add("STATUS_WORD", 0xABCD);
31  *
32  *     m.get() //returns: "STATUS_VOUT=0xFF|STATUS_WORD=0xABCD"
33  */
34 class NamesValues
35 {
36     public:
37 
38         NamesValues() = default;
39         NamesValues(const NamesValues&) = default;
40         NamesValues& operator=(const NamesValues&) = default;
41         NamesValues(NamesValues&&) = default;
42         NamesValues& operator=(NamesValues&&) = default;
43 
44         /**
45          * Adds a name/value pair to the object
46          *
47          * @param name - the name to add
48          * @param value - the value to add
49          */
50         void add(const std::string& name, uint64_t value)
51         {
52             addDivider();
53             addName(name);
54             addValue(value);
55         }
56 
57         /**
58          * Returns a formatted concatenation of all of the names and
59          * their values.
60          *
61          * @return string - "<name1>=<value1>|<name2>=<value2>..etc"
62          */
63         const std::string& get() const
64         {
65             return all;
66         }
67 
68     private:
69 
70         /**
71          * Adds a name to the object
72          *
73          * @param name - the name to add
74          */
75         void addName(const std::string& name)
76         {
77             all += name + '=';
78         }
79 
80         /**
81          * Adds a value to the object
82          *
83          * @param value - the value to add
84          */
85         void addValue(uint64_t value)
86         {
87             std::ostringstream stream;
88             stream << "0x" << std::hex << value;
89             all += stream.str();
90         }
91 
92         /**
93          * Adds a divider to the summary string to
94          * break up the name/value pairs
95          */
96         void addDivider()
97         {
98            if (!all.empty())
99            {
100                 all += '|';
101            }
102         }
103 
104         /**
105          * The string containing all name/value pairs
106          */
107         std::string all;
108 };
109 
110 }
111 }
112 }
113