1"""Utility functions not closely tied to other spec_tools types.""" 2# Copyright (c) 2018-2019 Collabora, Ltd. 3# Copyright (c) 2013-2020 The Khronos Group Inc. 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17 18def getElemName(elem, default=None): 19 """Get the name associated with an element, either a name child or name attribute.""" 20 name_elem = elem.find('name') 21 if name_elem is not None: 22 return name_elem.text 23 # Fallback if there is no child. 24 return elem.get('name', default) 25 26 27def getElemType(elem, default=None): 28 """Get the type associated with an element, either a type child or type attribute.""" 29 type_elem = elem.find('type') 30 if type_elem is not None: 31 return type_elem.text 32 # Fallback if there is no child. 33 return elem.get('type', default) 34 35 36def findFirstWithPredicate(collection, pred): 37 """Return the first element that satisfies the predicate, or None if none exist. 38 39 NOTE: Some places where this is used might be better served by changing to a dictionary. 40 """ 41 for elt in collection: 42 if pred(elt): 43 return elt 44 return None 45 46 47def findNamedElem(elems, name): 48 """Traverse a collection of elements with 'name' nodes or attributes, looking for and returning one with the right name. 49 50 NOTE: Many places where this is used might be better served by changing to a dictionary. 51 """ 52 return findFirstWithPredicate(elems, lambda elem: getElemName(elem) == name) 53 54 55def findTypedElem(elems, typename): 56 """Traverse a collection of elements with 'type' nodes or attributes, looking for and returning one with the right typename. 57 58 NOTE: Many places where this is used might be better served by changing to a dictionary. 59 """ 60 return findFirstWithPredicate(elems, lambda elem: getElemType(elem) == typename) 61 62 63def findNamedObject(collection, name): 64 """Traverse a collection of elements with 'name' attributes, looking for and returning one with the right name. 65 66 NOTE: Many places where this is used might be better served by changing to a dictionary. 67 """ 68 return findFirstWithPredicate(collection, lambda elt: elt.name == name) 69