1 // Copyright 2018 Google LLC All Rights Reserved. 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 name 16 17 import ( 18 "strings" 19 "unicode/utf8" 20 ) 21 22 // stripRunesFn returns a function which returns -1 (i.e. a value which 23 // signals deletion in strings.Map) for runes in 'runes', and the rune otherwise. 24 func stripRunesFn(runes string) func(rune) rune { 25 return func(r rune) rune { 26 if strings.ContainsRune(runes, r) { 27 return -1 28 } 29 return r 30 } 31 } 32 33 // checkElement checks a given named element matches character and length restrictions. 34 // Returns true if the given element adheres to the given restrictions, false otherwise. 35 func checkElement(name, element, allowedRunes string, minRunes, maxRunes int) error { 36 numRunes := utf8.RuneCountInString(element) 37 if (numRunes < minRunes) || (maxRunes < numRunes) { 38 return newErrBadName("%s must be between %d and %d characters in length: %s", name, minRunes, maxRunes, element) 39 } else if len(strings.Map(stripRunesFn(allowedRunes), element)) != 0 { 40 return newErrBadName("%s can only contain the characters `%s`: %s", name, allowedRunes, element) 41 } 42 return nil 43 } 44