1""" 2Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 3See https://llvm.org/LICENSE.txt for license information. 4SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 5 6Prepares language bindings for LLDB build process. Run with --help 7to see a description of the supported command line arguments. 8""" 9 10# Python modules: 11import io 12 13# Third party modules 14import six 15 16 17def _encoded_read(old_read, encoding): 18 def impl(size): 19 result = old_read(size) 20 # If this is Python 2 then we need to convert the resulting `unicode` back 21 # into a `str` before returning 22 if six.PY2: 23 result = result.encode(encoding) 24 return result 25 return impl 26 27 28def _encoded_write(old_write, encoding): 29 def impl(s): 30 # If we were asked to write a `str` (in Py2) or a `bytes` (in Py3) decode it 31 # as unicode before attempting to write. 32 if isinstance(s, six.binary_type): 33 s = s.decode(encoding, "replace") 34 return old_write(s) 35 return impl 36 37''' 38Create a Text I/O file object that can be written to with either unicode strings or byte strings 39under Python 2 and Python 3, and automatically encodes and decodes as necessary to return the 40native string type for the current Python version 41''' 42 43 44def open( 45 file, 46 encoding, 47 mode='r', 48 buffering=-1, 49 errors=None, 50 newline=None, 51 closefd=True): 52 wrapped_file = io.open( 53 file, 54 mode=mode, 55 buffering=buffering, 56 encoding=encoding, 57 errors=errors, 58 newline=newline, 59 closefd=closefd) 60 new_read = _encoded_read(getattr(wrapped_file, 'read'), encoding) 61 new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding) 62 setattr(wrapped_file, 'read', new_read) 63 setattr(wrapped_file, 'write', new_write) 64 return wrapped_file 65