1// Copyright 2014 The Prometheus Authors
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package metric
15
16import "github.com/prometheus/common/model"
17
18// Metric wraps a model.Metric and copies it upon modification if Copied is false.
19type Metric struct {
20	Copied bool
21	Metric model.Metric
22}
23
24// Set sets a label name in the wrapped Metric to a given value and copies the
25// Metric initially, if it is not already a copy.
26func (m *Metric) Set(ln model.LabelName, lv model.LabelValue) {
27	m.Copy()
28	m.Metric[ln] = lv
29}
30
31// Del deletes a given label name from the wrapped Metric and copies the
32// Metric initially, if it is not already a copy.
33func (m *Metric) Del(ln model.LabelName) {
34	m.Copy()
35	delete(m.Metric, ln)
36}
37
38// Get the value for the given label name. An empty value is returned
39// if the label does not exist in the metric.
40func (m *Metric) Get(ln model.LabelName) model.LabelValue {
41	return m.Metric[ln]
42}
43
44// Gets behaves as Get but the returned boolean is false iff the label
45// does not exist.
46func (m *Metric) Gets(ln model.LabelName) (model.LabelValue, bool) {
47	lv, ok := m.Metric[ln]
48	return lv, ok
49}
50
51// Copy the underlying Metric if it is not already a copy.
52func (m *Metric) Copy() *Metric {
53	if !m.Copied {
54		m.Metric = m.Metric.Clone()
55		m.Copied = true
56	}
57	return m
58}
59
60// String implements fmt.Stringer.
61func (m Metric) String() string {
62	return m.Metric.String()
63}
64