xref: /llvm-project/lldb/packages/Python/lldbsuite/support/encoded_file.py (revision e5a7990dbe8d5c45541a7d56b07d64d20b1fe002)
1"""
2                     The LLVM Compiler Infrastructure
3
4This file is distributed under the University of Illinois Open Source
5License. See LICENSE.TXT for details.
6
7Prepares language bindings for LLDB build process.  Run with --help
8to see a description of the supported command line arguments.
9"""
10
11# Python modules:
12import io
13
14# Third party modules
15import six
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
27def _encoded_write(old_write, encoding):
28    def impl(s):
29        # If we were asked to write a `str` (in Py2) or a `bytes` (in Py3) decode it
30        # as unicode before attempting to write.
31        if isinstance(s, six.binary_type):
32            s = s.decode(encoding)
33        return old_write(s)
34    return impl
35
36'''
37Create a Text I/O file object that can be written to with either unicode strings or byte strings
38under Python 2 and Python 3, and automatically encodes and decodes as necessary to return the
39native string type for the current Python version
40'''
41def open(file, encoding, mode='r', buffering=-1, errors=None, newline=None, closefd=True):
42    wrapped_file = io.open(file, mode=mode, buffering=buffering, encoding=encoding,
43                           errors=errors, newline=newline, closefd=closefd)
44    new_read = _encoded_read(getattr(wrapped_file, 'read'), encoding)
45    new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding)
46    setattr(wrapped_file, 'read', new_read)
47    setattr(wrapped_file, 'write', new_write)
48    return wrapped_file
49