blob: fc4de4106e8515c19388c67e054867fb59a8088f [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001// Copyright 2013 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 model
15
16import (
17 "fmt"
18 "strconv"
19)
20
21// Fingerprint provides a hash-capable representation of a Metric.
22// For our purposes, FNV-1A 64-bit is used.
23type Fingerprint uint64
24
25// FingerprintFromString transforms a string representation into a Fingerprint.
26func FingerprintFromString(s string) (Fingerprint, error) {
27 num, err := strconv.ParseUint(s, 16, 64)
28 return Fingerprint(num), err
29}
30
31// ParseFingerprint parses the input string into a fingerprint.
32func ParseFingerprint(s string) (Fingerprint, error) {
33 num, err := strconv.ParseUint(s, 16, 64)
34 if err != nil {
35 return 0, err
36 }
37 return Fingerprint(num), nil
38}
39
40func (f Fingerprint) String() string {
41 return fmt.Sprintf("%016x", uint64(f))
42}
43
44// Fingerprints represents a collection of Fingerprint subject to a given
45// natural sorting scheme. It implements sort.Interface.
46type Fingerprints []Fingerprint
47
48// Len implements sort.Interface.
49func (f Fingerprints) Len() int {
50 return len(f)
51}
52
53// Less implements sort.Interface.
54func (f Fingerprints) Less(i, j int) bool {
55 return f[i] < f[j]
56}
57
58// Swap implements sort.Interface.
59func (f Fingerprints) Swap(i, j int) {
60 f[i], f[j] = f[j], f[i]
61}
62
63// FingerprintSet is a set of Fingerprints.
64type FingerprintSet map[Fingerprint]struct{}
65
66// Equal returns true if both sets contain the same elements (and not more).
67func (s FingerprintSet) Equal(o FingerprintSet) bool {
68 if len(s) != len(o) {
69 return false
70 }
71
72 for k := range s {
73 if _, ok := o[k]; !ok {
74 return false
75 }
76 }
77
78 return true
79}
80
81// Intersection returns the elements contained in both sets.
82func (s FingerprintSet) Intersection(o FingerprintSet) FingerprintSet {
83 myLength, otherLength := len(s), len(o)
84 if myLength == 0 || otherLength == 0 {
85 return FingerprintSet{}
86 }
87
88 subSet := s
89 superSet := o
90
91 if otherLength < myLength {
92 subSet = o
93 superSet = s
94 }
95
96 out := FingerprintSet{}
97
98 for k := range subSet {
99 if _, ok := superSet[k]; ok {
100 out[k] = struct{}{}
101 }
102 }
103
104 return out
105}