@@ -3,12 +3,11 @@ use pyo3::once_cell::GILOnceCell;
33use std:: fmt;
44
55use pyo3:: prelude:: * ;
6- use pyo3:: types:: { PyList , PyString , PyTuple } ;
6+ use pyo3:: types:: { PyList , PyTuple } ;
77use serde:: ser:: SerializeSeq ;
88use serde:: { Serialize , Serializer } ;
99
1010use crate :: lookup_key:: { LookupPath , PathItem } ;
11- use crate :: tools:: extract_i64;
1211
1312/// Used to store individual items of the error location, e.g. a string for key/field names
1413/// or a number for array indices.
@@ -35,6 +34,12 @@ impl fmt::Display for LocItem {
3534 }
3635}
3736
37+ // TODO rename to ToLocItem
38+ pub trait AsLocItem {
39+ // TODO rename to to_loc_item
40+ fn as_loc_item ( & self ) -> LocItem ;
41+ }
42+
3843impl From < String > for LocItem {
3944 fn from ( s : String ) -> Self {
4045 Self :: S ( s)
@@ -82,21 +87,6 @@ impl ToPyObject for LocItem {
8287 }
8388}
8489
85- impl TryFrom < & PyAny > for LocItem {
86- type Error = PyErr ;
87-
88- fn try_from ( loc_item : & PyAny ) -> PyResult < Self > {
89- if let Ok ( py_str) = loc_item. downcast :: < PyString > ( ) {
90- let str = py_str. to_str ( ) ?. to_string ( ) ;
91- Ok ( Self :: S ( str) )
92- } else if let Ok ( int) = extract_i64 ( loc_item) {
93- Ok ( Self :: I ( int) )
94- } else {
95- Err ( PyTypeError :: new_err ( "Item in a location must be a string or int" ) )
96- }
97- }
98- }
99-
10090impl Serialize for LocItem {
10191 fn serialize < S > ( & self , serializer : S ) -> Result < S :: Ok , S :: Error >
10292 where
@@ -211,9 +201,9 @@ impl TryFrom<Option<&PyAny>> for Location {
211201 fn try_from ( location : Option < & PyAny > ) -> PyResult < Self > {
212202 if let Some ( location) = location {
213203 let mut loc_vec: Vec < LocItem > = if let Ok ( tuple) = location. downcast :: < PyTuple > ( ) {
214- tuple. iter ( ) . map ( LocItem :: try_from ) . collect :: < PyResult < _ > > ( ) ?
204+ tuple. iter ( ) . map ( AsLocItem :: as_loc_item ) . collect ( )
215205 } else if let Ok ( list) = location. downcast :: < PyList > ( ) {
216- list. iter ( ) . map ( LocItem :: try_from ) . collect :: < PyResult < _ > > ( ) ?
206+ list. iter ( ) . map ( AsLocItem :: as_loc_item ) . collect ( )
217207 } else {
218208 return Err ( PyTypeError :: new_err (
219209 "Location must be a list or tuple of strings and ints" ,
0 commit comments