github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/pkg/util/conv.go (about) 1 package util 2 3 import ( 4 "time" 5 "unsafe" 6 7 "github.com/prometheus/common/model" 8 "github.com/prometheus/prometheus/model/labels" 9 ) 10 11 // ModelLabelSetToMap convert a model.LabelSet to a map[string]string 12 func ModelLabelSetToMap(m model.LabelSet) map[string]string { 13 if len(m) == 0 { 14 return map[string]string{} 15 } 16 return *(*map[string]string)(unsafe.Pointer(&m)) 17 } 18 19 // MapToModelLabelSet converts a map into a model.LabelSet 20 func MapToModelLabelSet(m map[string]string) model.LabelSet { 21 if len(m) == 0 { 22 return model.LabelSet{} 23 } 24 return *(*map[model.LabelName]model.LabelValue)(unsafe.Pointer(&m)) 25 } 26 27 // RoundToMilliseconds returns milliseconds precision time from nanoseconds. 28 // from will be rounded down to the nearest milliseconds while through is rounded up. 29 func RoundToMilliseconds(from, through time.Time) (model.Time, model.Time) { 30 fromMs := from.UnixNano() / int64(time.Millisecond) 31 throughMs := through.UnixNano() / int64(time.Millisecond) 32 33 // add a millisecond to the through time if the nanosecond offset within the second is not a multiple of milliseconds 34 if int64(through.Nanosecond())%int64(time.Millisecond) != 0 { 35 throughMs++ 36 } 37 38 return model.Time(fromMs), model.Time(throughMs) 39 } 40 41 // LabelsToMetric converts a Labels to Metric 42 // Don't do this on any performance sensitive paths. 43 func LabelsToMetric(ls labels.Labels) model.Metric { 44 m := make(model.Metric, len(ls)) 45 for _, l := range ls { 46 m[model.LabelName(l.Name)] = model.LabelValue(l.Value) 47 } 48 return m 49 }