// Copyright 2017 Google Inc. All Rights Reserved. // // This file contains the declarations for the Metric class and related // types. #ifndef WVCDM_METRICS_VALUE_METRIC_H_ #define WVCDM_METRICS_VALUE_METRIC_H_ #include #include #include "metric_serialization.h" namespace wvcdm { namespace metrics { // Private namespace for some helper implementation functions. namespace impl { // These helper functions map the templated ValueMetric class // Serialize call to the MetricSerializer explicit calls. template void Serialize(MetricSerializer* serializer, const std::string& metric_name, const T& t); inline void SerializeError(MetricSerializer* serializer, const std::string& metric_name, const int& error_code) { serializer->SetInt32(metric_name + "/error", error_code); } } // namespace impl // The Metric class supports storing a single value which can be overwritten. // the Metric class also supports the MetricSerializer interface through // which the value can be serialized. If the value was never given a value // or an error code, then the metric will not serialize anything. // // Example Usage: // Metric cdm_version("drm/cdm/version") // .Record("a.b.c.d"); // // MyMetricSerializerImpl serialzer; // cdm_version.Serialize(&serializer); // // Example Error Usage: // // Metric cdm_version("drm/cdm/version") // .SetError(error_code); // // Note that serialization is the same. But the ValueMetric will serialize // the error code to /error instead of just . template class ValueMetric : public MetricSerializable { public: // Constructs a metric with the given metric name. explicit ValueMetric(const std::string& metric_name) : metric_name_(metric_name), error_code_(0), has_error_(false), has_value_(false) {} // Serialize the metric name and value using the given serializer. // Caller owns |serializer| which cannot be null. virtual void Serialize(MetricSerializer* serializer) { if (has_value_) { impl::Serialize(serializer, metric_name_, value_); } else if (has_error_) { impl::SerializeError(serializer, metric_name_, error_code_); } else { // Do nothing if there is no value and no error. } } // Record the value of the metric. void Record(const T& value) { value_ = value; has_value_ = true; has_error_ = false; } // Set the error code if an error was encountered. void SetError(int error_code) { error_code_ = error_code; has_value_ = false; has_error_ = true; } // Get the current value of the metric. const T& GetValue() { return value_; } // Clears the indicators that the metric or error was set. void Clear() { has_value_ = false; has_error_ = false; } private: std::string metric_name_; T value_; int error_code_; bool has_error_; bool has_value_; }; } // namespace metrics } // namespace wvcdm #endif // WVCDM_METRICS_VALUE_METRIC_H_