forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlib.rs
More file actions
293 lines (255 loc) · 8.47 KB
/
lib.rs
File metadata and controls
293 lines (255 loc) · 8.47 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::cell::UnsafeCell;
use std::ffi::{CStr, c_char, c_int, c_void};
use std::mem::MaybeUninit;
use std::ptr;
use std::slice;
use cpython_sys::METH_FASTCALL;
use cpython_sys::Py_DecRef;
use cpython_sys::Py_buffer;
use cpython_sys::Py_ssize_t;
use cpython_sys::PyBuffer_Release;
use cpython_sys::PyBytes_AsString;
use cpython_sys::PyBytes_FromStringAndSize;
use cpython_sys::PyErr_NoMemory;
use cpython_sys::PyErr_SetNone;
use cpython_sys::PyErr_SetObject;
use cpython_sys::PyErr_SetString;
use cpython_sys::PyExc_TypeError;
use cpython_sys::PyMethodDef;
use cpython_sys::PyMethodDefFuncPointer;
use cpython_sys::PyModuleDef;
use cpython_sys::PyModuleDef_HEAD_INIT;
use cpython_sys::PyModuleDef_Init;
use cpython_sys::PyObject;
use cpython_sys::PyObject_GetBuffer;
// Error Handling Abstraction
/// Zero-sized type indicating that a Python exception has been set.
/// Using this type will ensure `Result<&PyObject, ExecutedErr>` and `Result<PyRc, ExecutedErr>`
/// to be same size as `*mut PyObject`.
#[derive(Debug, Clone, Copy)]
pub struct ExecutedErr;
/// Enum representing different ways to set a Python exception.
///
/// This type is NOT stored in Result - it's immediately converted to
/// `ExecutedErr` via `.into()`, which triggers the actual C API call.
pub enum MakeErr {
SetString(*mut PyObject, *const c_char),
SetObject(*mut PyObject, *mut PyObject),
SetNone(*mut PyObject),
NoMemory,
}
impl MakeErr {
fn execute(self) -> ExecutedErr {
match self {
MakeErr::SetString(exc_type, msg) => {
unsafe { PyErr_SetString(exc_type, msg) };
}
MakeErr::SetObject(exc_type, value) => {
unsafe { PyErr_SetObject(exc_type, value) };
}
MakeErr::SetNone(exc_type) => {
unsafe { PyErr_SetNone(exc_type) };
}
MakeErr::NoMemory => {
unsafe { PyErr_NoMemory() };
}
}
ExecutedErr
}
#[inline]
pub fn type_error(msg: &CStr) -> Self {
Self::SetString(unsafe { PyExc_TypeError }, msg.as_ptr())
}
}
impl From<MakeErr> for ExecutedErr {
#[inline]
fn from(exc: MakeErr) -> Self {
exc.execute()
}
}
pub type PyResult<T> = Result<T, ExecutedErr>;
const PYBUF_SIMPLE: c_int = 0;
const PAD_BYTE: u8 = b'=';
const ENCODE_TABLE: [u8; 64] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#[inline]
fn encoded_output_len(input_len: usize) -> Option<usize> {
input_len
.checked_add(2)
.map(|n| n / 3)
.and_then(|blocks| blocks.checked_mul(4))
}
#[inline]
fn encode_into(input: &[u8], output: &mut [u8]) -> usize {
let mut src_index = 0;
let mut dst_index = 0;
let len = input.len();
while src_index + 3 <= len {
let chunk = (u32::from(input[src_index]) << 16)
| (u32::from(input[src_index + 1]) << 8)
| u32::from(input[src_index + 2]);
output[dst_index] = ENCODE_TABLE[((chunk >> 18) & 0x3f) as usize];
output[dst_index + 1] = ENCODE_TABLE[((chunk >> 12) & 0x3f) as usize];
output[dst_index + 2] = ENCODE_TABLE[((chunk >> 6) & 0x3f) as usize];
output[dst_index + 3] = ENCODE_TABLE[(chunk & 0x3f) as usize];
src_index += 3;
dst_index += 4;
}
match len - src_index {
0 => {}
1 => {
let chunk = u32::from(input[src_index]) << 16;
output[dst_index] = ENCODE_TABLE[((chunk >> 18) & 0x3f) as usize];
output[dst_index + 1] = ENCODE_TABLE[((chunk >> 12) & 0x3f) as usize];
output[dst_index + 2] = PAD_BYTE;
output[dst_index + 3] = PAD_BYTE;
dst_index += 4;
}
2 => {
let chunk =
(u32::from(input[src_index]) << 16) | (u32::from(input[src_index + 1]) << 8);
output[dst_index] = ENCODE_TABLE[((chunk >> 18) & 0x3f) as usize];
output[dst_index + 1] = ENCODE_TABLE[((chunk >> 12) & 0x3f) as usize];
output[dst_index + 2] = ENCODE_TABLE[((chunk >> 6) & 0x3f) as usize];
output[dst_index + 3] = PAD_BYTE;
dst_index += 4;
}
_ => unreachable!("len - src_index cannot exceed 2"),
}
dst_index
}
struct BorrowedBuffer {
view: Py_buffer,
}
impl BorrowedBuffer {
fn from_object(obj: &PyObject) -> PyResult<Self> {
let mut view = MaybeUninit::<Py_buffer>::uninit();
let buffer = unsafe {
if PyObject_GetBuffer(obj.as_raw(), view.as_mut_ptr(), PYBUF_SIMPLE) != 0 {
// PyObject_GetBuffer already set the exception
return Err(ExecutedErr);
}
Self {
view: view.assume_init(),
}
};
Ok(buffer)
}
fn len(&self) -> Py_ssize_t {
self.view.len
}
fn as_ptr(&self) -> *const u8 {
self.view.buf.cast::<u8>() as *const u8
}
fn as_slice(&self, msg: &CStr) -> PyResult<&[u8]> {
let len = self.len();
if len < 0 {
return Err(MakeErr::type_error(msg).into());
}
let slice = unsafe { slice::from_raw_parts(self.as_ptr(), len as usize) };
Ok(slice)
}
}
impl Drop for BorrowedBuffer {
fn drop(&mut self) {
unsafe {
PyBuffer_Release(&mut self.view);
}
}
}
/// # Safety
/// `module` must be a valid pointer of PyObject representing the module.
/// `args` must be a valid pointer to an array of valid PyObject pointers with length `nargs`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn standard_b64encode(
_module: *mut PyObject,
args: *mut *mut PyObject,
nargs: Py_ssize_t,
) -> *mut PyObject {
if nargs != 1 {
MakeErr::type_error(c"standard_b64encode() takes exactly one argument").execute();
return ptr::null_mut();
}
let source = unsafe { &**args };
// Safe cast by Safety
match standard_b64encode_impl(source) {
Ok(result) => result,
Err(_) => ptr::null_mut(),
}
}
fn standard_b64encode_impl(source: &PyObject) -> PyResult<*mut PyObject> {
let buffer = BorrowedBuffer::from_object(source)?;
let input = buffer.as_slice(c"standard_b64encode() argument has negative length")?;
let Some(output_len) = encoded_output_len(input.len()) else {
return Err(MakeErr::NoMemory.into());
};
if output_len > isize::MAX as usize {
return Err(MakeErr::NoMemory.into());
}
let result = unsafe { PyBytes_FromStringAndSize(ptr::null(), output_len as Py_ssize_t) };
if result.is_null() {
// PyBytes_FromStringAndSize already set the exception
return Err(ExecutedErr);
}
let dest_ptr = unsafe { PyBytes_AsString(result) };
if dest_ptr.is_null() {
unsafe {
Py_DecRef(result);
}
// PyBytes_AsString already set the exception
return Err(ExecutedErr);
}
let dest = unsafe { slice::from_raw_parts_mut(dest_ptr.cast::<u8>(), output_len) };
let written = encode_into(input, dest);
debug_assert_eq!(written, output_len);
Ok(result)
}
#[unsafe(no_mangle)]
pub extern "C" fn _base64_clear(_obj: *mut PyObject) -> c_int {
//TODO
0
}
#[unsafe(no_mangle)]
pub extern "C" fn _base64_free(_o: *mut c_void) {
//TODO
}
pub struct ModuleDef {
ffi: UnsafeCell<PyModuleDef>,
}
impl ModuleDef {
fn init_multi_phase(&'static self) -> *mut PyObject {
unsafe { PyModuleDef_Init(self.ffi.get()) }
}
}
unsafe impl Sync for ModuleDef {}
pub static _BASE64_MODULE_METHODS: [PyMethodDef; 2] = {
[
PyMethodDef {
ml_name: c"standard_b64encode".as_ptr() as *mut c_char,
ml_meth: PyMethodDefFuncPointer {
PyCFunctionFast: standard_b64encode,
},
ml_flags: METH_FASTCALL,
ml_doc: c"Demo for the _base64 module".as_ptr() as *mut c_char,
},
PyMethodDef::zeroed(),
]
};
pub static _BASE64_MODULE: ModuleDef = {
ModuleDef {
ffi: UnsafeCell::new(PyModuleDef {
m_base: PyModuleDef_HEAD_INIT,
m_name: c"_base64".as_ptr() as *mut _,
m_doc: c"A test Rust module".as_ptr() as *mut _,
m_size: 0,
m_methods: &_BASE64_MODULE_METHODS as *const PyMethodDef as *mut _,
m_slots: std::ptr::null_mut(),
m_traverse: None,
m_clear: Some(_base64_clear),
m_free: Some(_base64_free),
}),
}
};
#[unsafe(no_mangle)]
pub extern "C" fn PyInit__base64() -> *mut PyObject {
_BASE64_MODULE.init_multi_phase()
}