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 15import collections 16 17 18_Metadatum = collections.namedtuple('_Metadatum', ('key', 'value',)) 19 20 21cdef void _store_c_metadata( 22 metadata, grpc_metadata **c_metadata, size_t *c_count): 23 if metadata is None: 24 c_count[0] = 0 25 c_metadata[0] = NULL 26 else: 27 metadatum_count = len(metadata) 28 if metadatum_count == 0: 29 c_count[0] = 0 30 c_metadata[0] = NULL 31 else: 32 c_count[0] = metadatum_count 33 c_metadata[0] = <grpc_metadata *>gpr_malloc( 34 metadatum_count * sizeof(grpc_metadata)) 35 for index, (key, value) in enumerate(metadata): 36 encoded_key = _encode(key) 37 encoded_value = value if encoded_key[-4:] == b'-bin' else _encode(value) 38 c_metadata[0][index].key = _slice_from_bytes(encoded_key) 39 c_metadata[0][index].value = _slice_from_bytes(encoded_value) 40 41 42cdef void _release_c_metadata(grpc_metadata *c_metadata, int count): 43 if 0 < count: 44 for index in range(count): 45 grpc_slice_unref(c_metadata[index].key) 46 grpc_slice_unref(c_metadata[index].value) 47 gpr_free(c_metadata) 48 49 50cdef tuple _metadatum(grpc_slice key_slice, grpc_slice value_slice): 51 cdef bytes key = _slice_bytes(key_slice) 52 cdef bytes value = _slice_bytes(value_slice) 53 return <tuple>_Metadatum( 54 _decode(key), value if key[-4:] == b'-bin' else _decode(value)) 55 56 57cdef tuple _metadata(grpc_metadata_array *c_metadata_array): 58 return tuple( 59 _metadatum( 60 c_metadata_array.metadata[index].key, 61 c_metadata_array.metadata[index].value) 62 for index in range(c_metadata_array.count)) 63