xref: /llvm-project/lldb/packages/Python/lldbsuite/support/encoded_file.py (revision b9c1b51e45b845debb76d8658edabca70ca56079)
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
17
18def _encoded_read(old_read, encoding):
19    def impl(size):
20        result = old_read(size)
21        # If this is Python 2 then we need to convert the resulting `unicode` back
22        # into a `str` before returning
23        if six.PY2:
24            result = result.encode(encoding)
25        return result
26    return impl
27
28
29def _encoded_write(old_write, encoding):
30    def impl(s):
31        # If we were asked to write a `str` (in Py2) or a `bytes` (in Py3) decode it
32        # as unicode before attempting to write.
33        if isinstance(s, six.binary_type):
34            s = s.decode(encoding)
35        return old_write(s)
36    return impl
37
38'''
39Create a Text I/O file object that can be written to with either unicode strings or byte strings
40under Python 2 and Python 3, and automatically encodes and decodes as necessary to return the
41native string type for the current Python version
42'''
43
44
45def open(
46        file,
47        encoding,
48        mode='r',
49        buffering=-1,
50        errors=None,
51        newline=None,
52        closefd=True):
53    wrapped_file = io.open(
54        file,
55        mode=mode,
56        buffering=buffering,
57        encoding=encoding,
58        errors=errors,
59        newline=newline,
60        closefd=closefd)
61    new_read = _encoded_read(getattr(wrapped_file, 'read'), encoding)
62    new_write = _encoded_write(getattr(wrapped_file, 'write'), encoding)
63    setattr(wrapped_file, 'read', new_read)
64    setattr(wrapped_file, 'write', new_write)
65    return wrapped_file
66