xref: /aosp_15_r20/external/grpc-grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1# Copyright 2016 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
15
16# This function will ascii encode unicode string inputs if necessary.
17# In Python3, unicode strings are the default str type.
18cdef bytes str_to_bytes(object s):
19  if s is None or isinstance(s, bytes):
20    return s
21  elif isinstance(s, unicode):
22    return s.encode('ascii')
23  else:
24    raise TypeError('Expected bytes, str, or unicode, not {}'.format(type(s)))
25
26
27# TODO(https://github.com/grpc/grpc/issues/13782): It would be nice for us if
28# the type of metadata that we accept were exactly the same as the type of
29# metadata that we deliver to our users (so "str" for this function's
30# parameter rather than "object"), but would it be nice for our users? Right
31# now we haven't yet heard from enough users to know one way or another.
32cdef bytes _encode(object string_or_none):
33  if string_or_none is None:
34    return b''
35  elif isinstance(string_or_none, (bytes,)):
36    return <bytes>string_or_none
37  elif isinstance(string_or_none, (unicode,)):
38    return string_or_none.encode('utf8')
39  else:
40    raise TypeError('Expected str, not {}'.format(type(string_or_none)))
41
42
43cdef str _decode(bytes bytestring):
44    if isinstance(bytestring, (str,)):
45        return <str>bytestring
46    else:
47        try:
48            return bytestring.decode('utf8')
49        except UnicodeDecodeError:
50            _LOGGER.exception('Invalid encoding on %s', bytestring)
51            return bytestring.decode('latin1')
52