vkdb
A time series database engine in C++.
Loading...
Searching...
No Matches
string.h
1#ifndef UTILS_STRING_H
2#define UTILS_STRING_H
3
4#include <vkdb/time_series_key.h>
5#include <vkdb/concepts.h>
6#include <optional>
7#include <sstream>
8#include <iostream>
9
10namespace vkdb {
20template <ArithmeticNoCVRefQuals TValue>
21TimeSeriesEntry<TValue> entryFromString(std::string&& entry) {
22 auto sep{entry.find('|')};
23 auto end{entry.find(']')};
24 auto key_str{entry.substr(0, sep)};
25 auto value_str{entry.substr(sep + 1, end - sep - 1)};
26
27 auto entry_key{TimeSeriesKey{std::move(key_str)}};
28 std::optional<TValue> entry_value;
29 if (value_str != "null") {
30 if constexpr (std::is_integral_v<TValue>) {
31 entry_value = static_cast<TValue>(std::stoll(value_str));
32 } else if constexpr (std::is_floating_point_v<TValue>) {
33 entry_value = static_cast<TValue>(std::stod(value_str));
34 }
35 }
36
37 return {entry_key, entry_value};
38}
39
49template <ArithmeticNoCVRefQuals TValue>
50std::string entryToString(const TimeSeriesEntry<TValue>& entry) {
51 std::stringstream ss;
52 ss << "[" << entry.first.str() << "|";
53 if (entry.second.has_value()) {
54 ss << entry.second.value();
55 } else {
56 ss << "null";
57 }
58 ss << "]";
59 return ss.str();
60}
61
71template <ArithmeticNoCVRefQuals TValue>
72std::vector<DataPoint<TValue>> datapointsFromString(
73 const std::string& datapoints
74) {
75 std::vector<DataPoint<TValue>> result;
76 std::string data{datapoints.substr(1, datapoints.size() - 2)};
77 std::istringstream ss{data};
78 std::string entry_str;
79 while (std::getline(ss, entry_str, ';')) {
80 auto entry_data{entryFromString<TValue>(entry_str.substr(1))};
81 result.push_back({
82 entry_data.first.timestamp(),
83 entry_data.first.metric(),
84 entry_data.first.tags(),
85 entry_data.second.value()
86 });
87 }
88 return result;
89}
90
100template <ArithmeticNoCVRefQuals TValue>
101std::string datapointsToString(
102 const std::vector<DataPoint<TValue>>& datapoints
103) {
104 std::ostringstream output;
105 output << "[";
106 for (const auto& datapoint : datapoints) {
107 TimeSeriesKey key{datapoint.timestamp, datapoint.metric, datapoint.tags};
108 TimeSeriesEntry<TValue> entry{key, datapoint.value};
109 output << entryToString(entry) << ";";
110 }
111 output.seekp(-!datapoints.empty(), std::ios_base::end);
112 output << "]";
113 return output.str();
114}
115} // namespace vkdb
116
117#endif // UTILS_STRING_H