Skip to content

Commit

Permalink
feat: Support Python 3.12
Browse files Browse the repository at this point in the history
Signed-off-by: Dmitry Dygalo <[email protected]>
  • Loading branch information
Stranger6667 committed Mar 3, 2024
1 parent f0828cb commit d9f4053
Show file tree
Hide file tree
Showing 10 changed files with 67 additions and 64 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-20.04, macos-12, windows-2022]
python-version: ['3.7', '3.8', '3.9', '3.10', '3.11']
python-version: ['3.7', '3.8', '3.9', '3.10', '3.11', '3.12']

name: Python ${{ matrix.python-version }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
Expand Down
4 changes: 4 additions & 0 deletions bindings/python/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [Unreleased]

### Added

- Support for Python 3.12 [#439](https://github.com/Stranger6667/jsonschema-rs/issues/439)

### Changed

- Expose drafts 2019-09 and 2020-12 to Python
Expand Down
5 changes: 3 additions & 2 deletions bindings/python/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions bindings/python/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ crate-type = ["cdylib"]

[build-dependencies]
built = { version = "0.7.1", features = ["cargo-lock", "chrono"] }
pyo3-build-config = { version = "0.20.3", features = ["resolve-config"] }

[dependencies.jsonschema]
path = "../../jsonschema"
Expand Down
1 change: 1 addition & 0 deletions bindings/python/build.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
fn main() {
built::write_built_file().expect("Failed to acquire build-time information");
pyo3_build_config::use_pyo3_cfgs();
}
2 changes: 1 addition & 1 deletion bindings/python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,5 @@ python-source = "python"
strip = true

[build-system]
requires = ["maturin>=0.14.11,<0.15"]
requires = ["maturin>=1.1"]
build-backend = "maturin"
6 changes: 3 additions & 3 deletions bindings/python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use jsonschema::{paths::JSONPointer, Draft};
use pyo3::{
exceptions::{self, PyValueError},
ffi::PyUnicode_AsUTF8AndSize,
prelude::*,
types::{PyAny, PyList, PyType},
wrap_pyfunction,
Expand All @@ -28,7 +29,6 @@ extern crate pyo3_built;

mod ffi;
mod ser;
mod string;
mod types;

const DRAFT7: u8 = 7;
Expand Down Expand Up @@ -385,8 +385,8 @@ impl JSONSchema {
)))
} else {
let mut str_size: pyo3::ffi::Py_ssize_t = 0;
let uni = unsafe { string::read_utf8_from_str(obj_ptr, &mut str_size) };
let slice = unsafe { std::slice::from_raw_parts(uni, str_size as usize) };
let ptr = unsafe { PyUnicode_AsUTF8AndSize(obj_ptr, &mut str_size) };
let slice = unsafe { std::slice::from_raw_parts(ptr.cast::<u8>(), str_size as usize) };
let raw_schema = serde_json::from_slice(slice)
.map_err(|error| PyValueError::new_err(format!("Invalid string: {}", error)))?;
let options = make_options(draft, with_meta_schemas)?;
Expand Down
58 changes: 51 additions & 7 deletions bindings/python/src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use pyo3::{
exceptions,
ffi::{
PyDictObject, PyFloat_AS_DOUBLE, PyList_GET_ITEM, PyList_GET_SIZE, PyLong_AsLongLong,
PyObject_GetAttr, PyTuple_GET_ITEM, PyTuple_GET_SIZE, Py_TYPE,
PyObject_GetAttr, PyTuple_GET_ITEM, PyTuple_GET_SIZE, PyUnicode_AsUTF8AndSize, Py_DECREF,
Py_TYPE,
},
prelude::*,
types::PyAny,
Expand All @@ -12,7 +13,7 @@ use serde::{
Serializer,
};

use crate::{ffi, string, types};
use crate::{ffi, types};
use std::ffi::CStr;

pub const RECURSION_LIMIT: u8 = 255;
Expand Down Expand Up @@ -114,6 +115,31 @@ pub fn get_object_type(object_type: *mut pyo3::ffi::PyTypeObject) -> ObjectType
}
}

macro_rules! bail_on_integer_conversion_error {
($value:expr) => {
if !$value.is_null() {
let repr = unsafe { pyo3::ffi::PyObject_Str($value) };
let mut size = 0;
let ptr = unsafe { PyUnicode_AsUTF8AndSize(repr, &mut size) };
return if !ptr.is_null() {
let slice = unsafe {
std::str::from_utf8_unchecked(std::slice::from_raw_parts(
ptr.cast::<u8>(),
size as usize,
))
};
let message = String::from(slice);
unsafe { Py_DECREF(repr) };
Err(ser::Error::custom(message))
} else {
Err(ser::Error::custom(
"Internal Error: Failed to convert exception to string",
))
};
}
};
}

/// Convert a Python value to `serde_json::Value`
impl Serialize for SerializePyObject {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
Expand All @@ -123,16 +149,34 @@ impl Serialize for SerializePyObject {
match self.object_type {
ObjectType::Str => {
let mut str_size: pyo3::ffi::Py_ssize_t = 0;
let uni = unsafe { string::read_utf8_from_str(self.object, &mut str_size) };
let ptr = unsafe { PyUnicode_AsUTF8AndSize(self.object, &mut str_size) };
let slice = unsafe {
std::str::from_utf8_unchecked(std::slice::from_raw_parts(
uni,
ptr.cast::<u8>(),
str_size as usize,
))
};
serializer.serialize_str(slice)
}
ObjectType::Int => serializer.serialize_i64(unsafe { PyLong_AsLongLong(self.object) }),
ObjectType::Int => {
let value = unsafe { PyLong_AsLongLong(self.object) };
if value == -1 {
#[cfg(Py_3_12)]
{
let exception = unsafe { pyo3::ffi::PyErr_GetRaisedException() };
bail_on_integer_conversion_error!(exception);
};
#[cfg(not(Py_3_12))]
{
let mut ptype: *mut pyo3::ffi::PyObject = std::ptr::null_mut();
let mut pvalue: *mut pyo3::ffi::PyObject = std::ptr::null_mut();
let mut ptraceback: *mut pyo3::ffi::PyObject = std::ptr::null_mut();
unsafe { pyo3::ffi::PyErr_Fetch(&mut ptype, &mut pvalue, &mut ptraceback) };
bail_on_integer_conversion_error!(pvalue);
};
}
serializer.serialize_i64(value)
}
ObjectType::Float => {
serializer.serialize_f64(unsafe { PyFloat_AS_DOUBLE(self.object) })
}
Expand All @@ -156,10 +200,10 @@ impl Serialize for SerializePyObject {
pyo3::ffi::PyDict_Next(self.object, &mut pos, &mut key, &mut value);
}
check_type_is_str(key)?;
let uni = unsafe { string::read_utf8_from_str(key, &mut str_size) };
let ptr = unsafe { PyUnicode_AsUTF8AndSize(key, &mut str_size) };
let slice = unsafe {
std::str::from_utf8_unchecked(std::slice::from_raw_parts(
uni,
ptr.cast::<u8>(),
str_size as usize,
))
};
Expand Down
48 changes: 0 additions & 48 deletions bindings/python/src/string.rs

This file was deleted.

4 changes: 2 additions & 2 deletions bindings/python/tests-py/test_jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,14 @@ def test_initialization_errors(schema, draft, error):

@given(minimum=st.integers().map(abs))
def test_minimum(minimum):
with suppress(SystemError):
with suppress(SystemError, ValueError):
assert is_valid({"minimum": minimum}, minimum)
assert is_valid({"minimum": minimum}, minimum - 1) is False


@given(maximum=st.integers().map(abs))
def test_maximum(maximum):
with suppress(SystemError):
with suppress(SystemError, ValueError):
assert is_valid({"maximum": maximum}, maximum)
assert is_valid({"maximum": maximum}, maximum + 1) is False

Expand Down

0 comments on commit d9f4053

Please sign in to comment.