Debian Codegraph @

propagators/envcar/normalize.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package envcar // import "go.opentelemetry.io/contrib/propagators/envcar"
5
6 import (
7 "unicode/utf8"
8 )
9
10 // normalize converts s to a valid POSIX environment variable name.
11 // The conversion rules are:
12 // - A–Z, 0–9, and _ are kept as-is.
13 // - a–z are uppercased.
14 // - All other characters are replaced with _.
15 // - If the result would start with a digit, an underscore is prepended.
16 func normalize(s string) string {
17 if s == "" {
18 return ""
19 }
20
21 // Pre-allocate the exact output length. If the first byte is a digit,
22 // the name must be prefixed with '_', so allocate one extra byte.
23 var b []byte
24 i := 0
25 if s[0] >= '0' && s[0] <= '9' {
26 b = make([]byte, utf8.RuneCountInString(s)+1)
27 b[0] = '_'
28 i = 1
29 } else {
30 b = make([]byte, utf8.RuneCountInString(s))
31 }
32
33 for _, r := range s {
34 switch {
35 case r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_':
36 // Uppercase letters, digits, and underscores are valid as-is.
37 b[i] = byte(r) //nolint:gosec // G115: overflow is not possible.
38 case r >= 'a' && r <= 'z':
39 // Lowercase letters are converted to uppercase.
40 b[i] = byte(r + 'A' - 'a')
41 default:
42 // All other characters (including non-ASCII runes) become underscores.
43 b[i] = '_'
44 }
45 i++
46 }
47 return string(b)
48 }