r"""Encode data to bytes. The primary use case is for base64/mime style 7-bit ascii encoding where the encoder input must be bytes. "safe" means that the conversion always returns bytes and will not raise codec exceptions. If data is text then an 8-bit ascii encoding is attempted, then the
(data)
| 755 | |
| 756 | |
| 757 | def EncodeToBytes(data): |
| 758 | r"""Encode data to bytes. |
| 759 | |
| 760 | The primary use case is for base64/mime style 7-bit ascii encoding where the |
| 761 | encoder input must be bytes. "safe" means that the conversion always returns |
| 762 | bytes and will not raise codec exceptions. |
| 763 | |
| 764 | If data is text then an 8-bit ascii encoding is attempted, then the console |
| 765 | encoding, and finally utf-8. |
| 766 | |
| 767 | Args: |
| 768 | data: Any bytes, string, or object that has str() or unicode() methods. |
| 769 | |
| 770 | Returns: |
| 771 | A bytes string representation of the data. |
| 772 | """ |
| 773 | if data is None: |
| 774 | return b'' |
| 775 | if isinstance(data, bytes): |
| 776 | # Already bytes - our work is done. |
| 777 | return data |
| 778 | |
| 779 | # Coerce to text that will be converted to bytes. |
| 780 | s = str(data) |
| 781 | |
| 782 | try: |
| 783 | # Assume the text can be directly converted to bytes (8-bit ascii). |
| 784 | return s.encode('iso-8859-1') |
| 785 | except UnicodeEncodeError: |
| 786 | pass |
| 787 | |
| 788 | try: |
| 789 | # Try the output encoding. |
| 790 | return s.encode(GetConsoleAttr().GetEncoding()) |
| 791 | except UnicodeEncodeError: |
| 792 | pass |
| 793 | |
| 794 | # Punt to utf-8. |
| 795 | return s.encode('utf-8') |
| 796 | |
| 797 | |
| 798 | def Decode(data, encoding=None): |
nothing calls this directly
no test coverage detected