]> git.ipfire.org Git - thirdparty/pdns.git/commitdiff
feat: implement ostream << operator for AnyValue
authorPieter Lexis <pieter.lexis@powerdns.com>
Thu, 25 Sep 2025 15:40:16 +0000 (17:40 +0200)
committerPieter Lexis <pieter.lexis@powerdns.com>
Tue, 14 Oct 2025 18:34:58 +0000 (20:34 +0200)
pdns/protozero-trace.cc
pdns/protozero-trace.hh

index 5b1fa712f4817e7cdabac274027d69c50ad5da33..894fd97695208d424b9b5ce26e1f3389ea555485 100644 (file)
@@ -21,6 +21,9 @@
  */
 
 #include "protozero-trace.hh"
+#include "base64.hh"
+#include <string>
+#include <variant>
 
 namespace pdns::trace
 {
@@ -96,6 +99,48 @@ AnyValue AnyValue::decode(protozero::pbf_reader& reader)
   return {};
 }
 
+std::string AnyValue::toLogString() const
+{
+  if (std::holds_alternative<std::string>(*this)) {
+    return "\"" + std::get<std::string>(*this) + "\"";
+  }
+  if (std::holds_alternative<bool>(*this)) {
+    if (std::get<bool>(*this)) {
+      return "true";
+    }
+    return "false";
+  }
+  if (std::holds_alternative<int64_t>(*this)) {
+    return std::to_string(std::get<int64_t>(*this));
+  }
+  if (std::holds_alternative<double>(*this)) {
+    return std::to_string(std::get<double>(*this));
+  }
+  if (std::holds_alternative<ArrayValue>(*this)) {
+    std::string tmp = "[";
+    for (auto const& val : std::get<ArrayValue>(*this).values) {
+      tmp += val.toLogString() + ", ";
+    }
+    tmp.resize(tmp.size() - 2); // Strip ", "
+    return tmp += "]";
+  }
+  if (std::holds_alternative<KeyValueList>(*this)) {
+    std::string tmp = "{";
+    for (auto const& val : std::get<KeyValueList>(*this).values) {
+      tmp += val.key + ": " + val.value.toLogString() + ", ";
+    }
+    if (tmp.size() > 2) {
+      tmp.resize(tmp.size() - 2); // Strip ", "
+    }
+    return tmp += "}";
+  }
+  if (std::holds_alternative<std::vector<uint8_t>>(*this)) {
+    auto val = std::get<std::vector<uint8_t>>(*this);
+    return Base64Encode(std::string(val.begin(), val.end()));
+  }
+  return "UNSUPPORTED TYPE";
+}
+
 void EntityRef::encode(protozero::pbf_writer& writer) const
 {
   pdns::trace::encode(writer, 1, schema_url);
index 6141916921c1d47cbb8370400fad13c9eddfe653..bf3617dfcb8911e8be3ba224336c0c83576c2b13 100644 (file)
@@ -176,6 +176,11 @@ struct AnyValue : public std::variant<NoValue, std::string, bool, int64_t, doubl
 {
   void encode(protozero::pbf_writer& writer) const;
   static AnyValue decode(protozero::pbf_reader& reader);
+  [[nodiscard]] std::string toLogString() const;
+  friend std::ostream& operator<<(std::ostream& ostrm, const AnyValue& val)
+  {
+    return ostrm << val.toLogString();
+  }
 };
 
 struct EntityRef