1 // Copyright 2017, OpenCensus Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package internal 16 17 import ( 18 "strings" 19 "unicode" 20 ) 21 22 const labelKeySizeLimit = 100 23 24 // Sanitize returns a string that is trunacated to 100 characters if it's too 25 // long, and replaces non-alphanumeric characters to underscores. 26 func Sanitize(s string) string { 27 if len(s) == 0 { 28 return s 29 } 30 if len(s) > labelKeySizeLimit { 31 s = s[:labelKeySizeLimit] 32 } 33 s = strings.Map(sanitizeRune, s) 34 if unicode.IsDigit(rune(s[0])) { 35 s = "key_" + s 36 } 37 if s[0] == '_' { 38 s = "key" + s 39 } 40 return s 41 } 42 43 // converts anything that is not a letter or digit to an underscore 44 func sanitizeRune(r rune) rune { 45 if unicode.IsLetter(r) || unicode.IsDigit(r) { 46 return r 47 } 48 // Everything else turns into an underscore 49 return '_' 50 } 51