| // Copyright 2018 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file |
| |
| package catapult |
| |
| import ( |
| "errors" |
| ) |
| |
| // HistogramSet is a collection of Histograms and related Diagnostics. |
| type HistogramSet struct { |
| histograms []Histogram |
| diagnostics []Diagnostic |
| } |
| |
| // AddHistogram adds a histogram to this HistogramSet. |
| // |
| // If this HistogramSet already contains a Diagnostic, the addition fails and |
| // an error is returned. |
| // |
| // TODO(kharland): This API does not allow adding a Histogram after Diagnostics |
| // have been added because it is not clear if the caller intended for the new |
| // Histogram to contain the same references to the shared Diagnostics in this |
| // HistogramSet as the existing Histograms. Allow adding Histograms after |
| // Diagnostics when Fuchsia needs this functionality. |
| func (h *HistogramSet) AddHistogram(histogram Histogram) error { |
| if len(h.diagnostics) > 0 { |
| return errors.New("can't add Histogram after adding Diagnostics") |
| } |
| h.histograms = append(h.histograms, histogram) |
| return nil |
| } |
| |
| // AddSharedDiagnostic adds a diagnostic to this HistogramSet. |
| // |
| // A shared Diagnostic is a diagnostic that exists in the HistogramSet, so |
| // that it may be referenced by Histograms within the set. A reference to the |
| // Diagnostic is automatically added to each Histogram in the set when calling |
| // this method. name is used as the key for this reference. |
| func (h *HistogramSet) AddSharedDiagnostic(name string, diagnostic Diagnostic) { |
| h.diagnostics = append(h.diagnostics, diagnostic) |
| |
| guid := diagnostic.GetGUID() |
| |
| // Reference the diagnostic's GUID in each Histogram in this set. |
| // |
| // Use the loop index instead of the loop variable since this directly |
| // mutates the histogram. |
| for i := range h.histograms { |
| h.histograms[i].AddDiagnostic(name, guid) |
| } |
| } |
| |
| // ToJSON returns a JSON-serializable representation of this HistogramSet. |
| func (h *HistogramSet) ToJSON() []interface{} { |
| jsonObject := []interface{}{} |
| // Diagnostics must come first in the HistogramSet or Catapult will reject |
| // the upload request. |
| for _, entry := range h.diagnostics { |
| jsonObject = append(jsonObject, entry) |
| } |
| for _, entry := range h.histograms { |
| jsonObject = append(jsonObject, entry) |
| } |
| return jsonObject |
| } |