1# Copyright 2017 gRPC 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"""API metadata conversion utilities.""" 15 16import collections 17 18_Metadatum = collections.namedtuple( 19 "_Metadatum", 20 ( 21 "key", 22 "value", 23 ), 24) 25 26 27def _beta_metadatum(key, value): 28 beta_key = key if isinstance(key, (bytes,)) else key.encode("ascii") 29 beta_value = value if isinstance(value, (bytes,)) else value.encode("ascii") 30 return _Metadatum(beta_key, beta_value) 31 32 33def _metadatum(beta_key, beta_value): 34 key = beta_key if isinstance(beta_key, (str,)) else beta_key.decode("utf8") 35 if isinstance(beta_value, (str,)) or key[-4:] == "-bin": 36 value = beta_value 37 else: 38 value = beta_value.decode("utf8") 39 return _Metadatum(key, value) 40 41 42def beta(metadata): 43 if metadata is None: 44 return () 45 else: 46 return tuple(_beta_metadatum(key, value) for key, value in metadata) 47 48 49def unbeta(beta_metadata): 50 if beta_metadata is None: 51 return () 52 else: 53 return tuple( 54 _metadatum(beta_key, beta_value) 55 for beta_key, beta_value in beta_metadata 56 ) 57