Skip to content

Commit 5b6a5cc

Browse files
Add PyOS_vsnprintf % PyOS_snprintf to the capi
1 parent b25ab5e commit 5b6a5cc

1 file changed

Lines changed: 40 additions & 1 deletion

File tree

‎crates/capi/src/pyerrors.rs‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::object::define_py_check;
22
use crate::util::{CStrExt, FfiPtrExt};
33
use crate::{PyObject, pystate::with_vm};
44
use core::convert::Infallible;
5-
use core::ffi::{c_char, c_int};
5+
use core::ffi::{VaList, c_char, c_int};
66
use core::slice;
77
use rustpython_vm::builtins::{PyBaseException, PyTraceback, PyTuple, PyType};
88
use rustpython_vm::exceptions::ExceptionZoo;
@@ -381,6 +381,45 @@ pub unsafe extern "C" fn PyException_SetTraceback(exc: *mut PyObject, tb: *mut P
381381
})
382382
}
383383

384+
#[unsafe(no_mangle)]
385+
pub unsafe extern "C" fn PyOS_snprintf(
386+
str: *mut c_char,
387+
size: usize,
388+
format: *const c_char,
389+
args: ...
390+
) -> c_int {
391+
unsafe { PyOS_vsnprintf(str, size, format, args) }
392+
}
393+
394+
#[unsafe(no_mangle)]
395+
pub unsafe extern "C" fn PyOS_vsnprintf(
396+
str: *mut c_char,
397+
size: usize,
398+
format: *const c_char,
399+
args: VaList<'_>,
400+
) -> c_int {
401+
unsafe extern "C" {
402+
fn vsnprintf(
403+
str: *mut c_char,
404+
size: usize,
405+
format: *const c_char,
406+
args: VaList<'_>,
407+
) -> c_int;
408+
}
409+
410+
let len = if size > (c_int::MAX as usize - 1) {
411+
-666
412+
} else {
413+
unsafe { vsnprintf(str, size, format, args) }
414+
};
415+
416+
if size > 0 && !str.is_null() {
417+
unsafe { *str.add(size - 1) = 0 };
418+
}
419+
420+
len
421+
}
422+
384423
#[cfg(test)]
385424
mod tests {
386425
use pyo3::PyTypeInfo;

0 commit comments

Comments
 (0)