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