diff --git a/obj-rs/src/error.rs b/obj-rs/src/error.rs index 86e95b1..d0dcb02 100644 --- a/obj-rs/src/error.rs +++ b/obj-rs/src/error.rs @@ -67,7 +67,7 @@ implmnt!(Load, LoadError); #[derive(PartialEq, Eq, Clone, Debug)] pub struct LoadError { kind: LoadErrorKind, - message: &'static str, + message: String, } impl LoadError { @@ -101,6 +101,7 @@ pub enum LoadErrorKind { impl LoadError { /// Creates a new custom error from a specified kind and message. pub fn new(kind: LoadErrorKind, message: &'static str) -> Self { + let message = message.to_string(); LoadError { kind, message } } } @@ -136,3 +137,13 @@ macro_rules! make_error { } pub(crate) use make_error; + +pub(super) fn index_out_of_range(index: usize) -> ObjResult { + let name = std::any::type_name::(); + Err(ObjError::Load(LoadError { + kind: LoadErrorKind::IndexOutOfRange, + message: format!( + "Given index type '{name}' is not large enough to contain the index '{index}'" + ), + })) +} diff --git a/obj-rs/src/lib.rs b/obj-rs/src/lib.rs index 2bbe2d8..d2d4993 100644 --- a/obj-rs/src/lib.rs +++ b/obj-rs/src/lib.rs @@ -30,7 +30,7 @@ pub mod raw; pub use crate::error::{LoadError, LoadErrorKind, ObjError, ObjResult}; -use crate::error::make_error; +use crate::error::{index_out_of_range, make_error}; use crate::raw::object::Polygon; use num_traits::FromPrimitive; use std::collections::hash_map::{Entry, HashMap}; @@ -130,10 +130,7 @@ impl FromRawVertex for Vertex { }; let index = match I::from_usize(vb.len()) { Some(val) => val, - None => make_error!( - IndexOutOfRange, - "Unable to convert the index from usize" - ), + None => return index_out_of_range::<_, I>(vb.len()), }; vb.push(vertex); entry.insert(index); @@ -207,7 +204,7 @@ impl FromRawVertex for Position { let mut map = |pi: usize| -> ObjResult<()> { ib.push(match I::from_usize(pi) { Some(val) => val, - None => make_error!(IndexOutOfRange, "Unable to convert the index from usize"), + None => return index_out_of_range::<_, I>(pi), }); Ok(()) }; @@ -285,10 +282,7 @@ impl FromRawVertex for TexturedVertex { }; let index = match I::from_usize(vb.len()) { Some(val) => val, - None => make_error!( - IndexOutOfRange, - "Unable to convert the index from usize" - ), + None => return index_out_of_range::<_, I>(vb.len()), }; vb.push(vertex); entry.insert(index); diff --git a/obj-rs/tests/issue-63.rs b/obj-rs/tests/issue-63.rs index 94bc35d..c06802c 100644 --- a/obj-rs/tests/issue-63.rs +++ b/obj-rs/tests/issue-63.rs @@ -5,11 +5,7 @@ fn do_test + std::fmt::Debug>(test_case: &str) { let err = load_obj::(Cursor::new(test_case)) .expect_err("Should error out due to index out of bounds"); if let obj::ObjError::Load(err) = err { - let expected_error = obj::LoadError::new( - obj::LoadErrorKind::IndexOutOfRange, - "Unable to convert the index from usize", - ); - assert_eq!(err.to_string(), expected_error.to_string()); + assert_eq!(*err.kind(), obj::LoadErrorKind::IndexOutOfRange); } else { panic!("Expected a LoadError"); }