|
| 1 | +use pyo3::intern; |
| 2 | +use pyo3::prelude::*; |
| 3 | +use pyo3::types::{PyDict, PyType}; |
| 4 | + |
| 5 | +use crate::build_tools::SchemaDict; |
| 6 | +use crate::errors::{ErrorKind, ValError, ValResult}; |
| 7 | +use crate::input::Input; |
| 8 | +use crate::recursion_guard::RecursionGuard; |
| 9 | + |
| 10 | +use super::{BuildContext, BuildValidator, CombinedValidator, Extra, Validator}; |
| 11 | + |
| 12 | +#[derive(Debug, Clone)] |
| 13 | +pub struct IsSubclassValidator { |
| 14 | + class: Py<PyType>, |
| 15 | + class_repr: String, |
| 16 | + name: String, |
| 17 | +} |
| 18 | + |
| 19 | +impl BuildValidator for IsSubclassValidator { |
| 20 | + const EXPECTED_TYPE: &'static str = "is-subclass"; |
| 21 | + |
| 22 | + fn build( |
| 23 | + schema: &PyDict, |
| 24 | + _config: Option<&PyDict>, |
| 25 | + _build_context: &mut BuildContext, |
| 26 | + ) -> PyResult<CombinedValidator> { |
| 27 | + let py = schema.py(); |
| 28 | + let class: &PyType = schema.get_as_req(intern!(py, "cls"))?; |
| 29 | + |
| 30 | + let class_repr = match schema.get_as(intern!(py, "cls_repr"))? { |
| 31 | + Some(s) => s, |
| 32 | + None => class.name()?.to_string(), |
| 33 | + }; |
| 34 | + let name = format!("{}[{}]", Self::EXPECTED_TYPE, class_repr); |
| 35 | + Ok(Self { |
| 36 | + class: class.into(), |
| 37 | + class_repr, |
| 38 | + name, |
| 39 | + } |
| 40 | + .into()) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl Validator for IsSubclassValidator { |
| 45 | + fn validate<'s, 'data>( |
| 46 | + &'s self, |
| 47 | + py: Python<'data>, |
| 48 | + input: &'data impl Input<'data>, |
| 49 | + _extra: &Extra, |
| 50 | + _slots: &'data [CombinedValidator], |
| 51 | + _recursion_guard: &'s mut RecursionGuard, |
| 52 | + ) -> ValResult<'data, PyObject> { |
| 53 | + match input.input_is_subclass(self.class.as_ref(py))? { |
| 54 | + true => Ok(input.to_object(py)), |
| 55 | + false => Err(ValError::new( |
| 56 | + ErrorKind::IsSubclassOf { |
| 57 | + class: self.class_repr.clone(), |
| 58 | + }, |
| 59 | + input, |
| 60 | + )), |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + fn get_name(&self) -> &str { |
| 65 | + &self.name |
| 66 | + } |
| 67 | +} |
0 commit comments