-
-
Notifications
You must be signed in to change notification settings - Fork 405
/
string.pxd
78 lines (62 loc) · 2.52 KB
/
string.pxd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#*****************************************************************************
# Copyright (C) 2017 Erik M. Bray <erik.bray@lri.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import absolute_import
cdef extern from "string_impl.h":
str _cstr_to_str(const char* c, encoding, errors)
bytes _str_to_bytes(s, encoding, errors)
cdef inline str char_to_str(const char* c, encoding=None, errors=None):
r"""
Convert a C string to a Python ``str``.
"""
# Implemented in C to avoid relying on PY_MAJOR_VERSION
# compile-time variable. We keep the Cython wrapper to deal with
# the default arguments.
return _cstr_to_str(c, encoding, errors)
cpdef inline str bytes_to_str(b, encoding=None, errors=None):
r"""
Convert ``bytes`` to ``str``.
This decodes the given ``bytes`` to a Python 3 unicode ``str`` using
the specified encoding. It is a no-op on ``str`` input.
EXAMPLES::
sage: from sage.cpython.string import bytes_to_str
sage: s = bytes_to_str(b'\xcf\x80')
sage: s == u'π'
True
sage: bytes_to_str([])
Traceback (most recent call last):
...
TypeError: expected bytes, list found
"""
if isinstance(b, str):
return b
if type(b) is not bytes:
raise TypeError(f"expected bytes, {type(b).__name__} found")
return _cstr_to_str(<bytes>b, encoding, errors)
cpdef inline bytes str_to_bytes(s, encoding=None, errors=None):
r"""
Convert ``str`` or ``unicode`` to ``bytes``.
It encodes the given ``str`` to a Python 3 ``bytes``
using the specified encoding. It is a no-op on ``bytes`` input.
EXAMPLES::
sage: from sage.cpython.string import str_to_bytes
sage: bs = [str_to_bytes(u'π')]
sage: all(b == b'\xcf\x80' for b in bs)
True
sage: str_to_bytes([])
Traceback (most recent call last):
...
TypeError: expected str... list found
"""
# Implemented in C to avoid relying on PY_MAJOR_VERSION
# compile-time variable. We keep the Cython wrapper to deal with
# the default arguments.
if isinstance(s, bytes):
return s
return _str_to_bytes(s, encoding, errors)