Skip to content

Commit 4cd2c34

Browse files
committed
ensure IndPtr is deserialized correctly
1 parent 571bbab commit 4cd2c34

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

sprs-tests/tests/tests.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,29 @@ mod serde_tests {
5959
serde_json::from_str(&json_mat);
6060
assert!(mat.is_err());
6161
}
62+
63+
#[test]
64+
fn valid_indptr() {
65+
let indptr = r#"{ "storage": [0, 0, 1, 2, 2, 6] }"#;
66+
let indptr: IndPtr<usize> = serde_json::from_str(&indptr).unwrap();
67+
assert_eq!(indptr.raw_storage(), &[0, 0, 1, 2, 2, 6]);
68+
69+
let indptr = r#"{ "storage": [5, 5, 8, 9] }"#;
70+
let indptr: IndPtr<usize> = serde_json::from_str(&indptr).unwrap();
71+
assert_eq!(indptr.raw_storage(), &[5, 5, 8, 9]);
72+
}
73+
74+
#[test]
75+
fn invalid_indptr() {
76+
let indptr = r#"{ "storage": [0, 0, 1, 2, 2, 1] }"#;
77+
let indptr: Result<IndPtr<usize>, _> = serde_json::from_str(&indptr);
78+
assert!(indptr.is_err());
79+
let indptr = r#"{ "storage": [2, 1, 2, 2, 2, 7] }"#;
80+
let indptr: Result<IndPtr<usize>, _> = serde_json::from_str(&indptr);
81+
assert!(indptr.is_err());
82+
// Larger than permitted by i16
83+
let indptr = r#"{ "storage": [0, 32768] }"#;
84+
let indptr: Result<IndPtr<i16>, _> = serde_json::from_str(&indptr);
85+
assert!(indptr.is_err());
86+
}
6287
}

src/sparse/indptr.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
//!
44
//! [`CsMatBase`]: type.CsMatBase.html
55
6+
#[cfg(feature = "serde")]
7+
use super::serde_traits::IndPtrBaseShadow;
68
use crate::errors::SprsError;
79
use crate::indexing::SpIndex;
810
#[cfg(feature = "serde")]
@@ -12,6 +14,10 @@ use std::ops::{Deref, DerefMut};
1214

1315
#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
1416
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
17+
#[cfg_attr(
18+
feature = "serde",
19+
serde(try_from = "IndPtrBaseShadow<Iptr, Storage>")
20+
)]
1521
pub struct IndPtrBase<Iptr, Storage>
1622
where
1723
Iptr: SpIndex,

src/sparse/serde_traits.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,26 @@ where
7171
.map_err(|(_, _, _, e)| e)
7272
}
7373
}
74+
75+
#[derive(Deserialize)]
76+
pub struct IndPtrBaseShadow<Iptr, Storage>
77+
where
78+
Iptr: SpIndex,
79+
Storage: Deref<Target = [Iptr]>,
80+
{
81+
storage: Storage,
82+
}
83+
84+
impl<Iptr: SpIndex, Storage> TryFrom<IndPtrBaseShadow<Iptr, Storage>>
85+
for IndPtrBase<Iptr, Storage>
86+
where
87+
Storage: Deref<Target = [Iptr]>,
88+
{
89+
type Error = SprsError;
90+
fn try_from(
91+
val: IndPtrBaseShadow<Iptr, Storage>,
92+
) -> Result<Self, Self::Error> {
93+
let IndPtrBaseShadow { storage } = val;
94+
Self::new(storage)
95+
}
96+
}

0 commit comments

Comments
 (0)