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('_Metadatum', ( 19 'key', 20 'value', 21)) 22 23 24def _beta_metadatum(key, value): 25 beta_key = key if isinstance(key, (bytes,)) else key.encode('ascii') 26 beta_value = value if isinstance(value, (bytes,)) else value.encode('ascii') 27 return _Metadatum(beta_key, beta_value) 28 29 30def _metadatum(beta_key, beta_value): 31 key = beta_key if isinstance(beta_key, (str,)) else beta_key.decode('utf8') 32 if isinstance(beta_value, (str,)) or key[-4:] == '-bin': 33 value = beta_value 34 else: 35 value = beta_value.decode('utf8') 36 return _Metadatum(key, value) 37 38 39def beta(metadata): 40 if metadata is None: 41 return () 42 else: 43 return tuple(_beta_metadatum(key, value) for key, value in metadata) 44 45 46def unbeta(beta_metadata): 47 if beta_metadata is None: 48 return () 49 else: 50 return tuple( 51 _metadatum(beta_key, beta_value) 52 for beta_key, beta_value in beta_metadata) 53