labelset_string.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2024 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. package model
  14. import (
  15. "bytes"
  16. "slices"
  17. "strconv"
  18. )
  19. // String will look like `{foo="bar", more="less"}`. Names are sorted alphabetically.
  20. func (l LabelSet) String() string {
  21. var lna [32]string // On stack to avoid memory allocation for sorting names.
  22. labelNames := lna[:0]
  23. for name := range l {
  24. labelNames = append(labelNames, string(name))
  25. }
  26. slices.Sort(labelNames)
  27. var bytea [1024]byte // On stack to avoid memory allocation while building the output.
  28. b := bytes.NewBuffer(bytea[:0])
  29. b.WriteByte('{')
  30. for i, name := range labelNames {
  31. if i > 0 {
  32. b.WriteString(", ")
  33. }
  34. b.WriteString(name)
  35. b.WriteByte('=')
  36. b.Write(strconv.AppendQuote(b.AvailableBuffer(), string(l[LabelName(name)])))
  37. }
  38. b.WriteByte('}')
  39. return b.String()
  40. }