@@ -33,9 +33,24 @@ impl SampleUniform for char {
3333#[ derive( Clone , Copy , Debug , PartialEq , Eq ) ]
3434#[ cfg_attr( feature = "serde" , derive( Serialize , Deserialize ) ) ]
3535pub struct UniformChar {
36+ #[ cfg_attr( feature = "serde" , serde( deserialize_with = "deser_sampler" ) ) ]
3637 sampler : UniformInt < u32 > ,
3738}
3839
40+ #[ cfg( feature = "serde" ) ]
41+ fn deser_sampler < ' de , D > ( d : D ) -> Result < UniformInt < u32 > , D :: Error >
42+ where
43+ D : serde:: Deserializer < ' de > ,
44+ {
45+ let sampler = <UniformInt < u32 > as serde:: Deserialize >:: deserialize ( d) ?;
46+ if sampler. max ( ) > char:: MAX as u32 - CHAR_SURROGATE_LEN {
47+ return Err ( serde:: de:: Error :: custom (
48+ "bad sampler range for UniformChar" ,
49+ ) ) ;
50+ }
51+ Ok ( sampler)
52+ }
53+
3954/// UTF-16 surrogate range start
4055const CHAR_SURROGATE_START : u32 = 0xD800 ;
4156/// UTF-16 surrogate range size
@@ -298,6 +313,24 @@ mod tests {
298313 }
299314 }
300315
316+ #[ test]
317+ #[ cfg( feature = "serde" ) ]
318+ fn test_char_bad_deser ( ) {
319+ let json = r#"{"sampler":{"low":4294967200,"range":0,"thresh":0}}"# ;
320+ let result = serde_json:: from_str :: < Uniform < char > > ( json) ;
321+ assert ! ( result. is_err( ) ) ;
322+ let err = result. unwrap_err ( ) ;
323+ assert_eq ! ( err. classify( ) , serde_json:: error:: Category :: Data ) ;
324+
325+ #[ cfg( feature = "alloc" ) ]
326+ {
327+ assert_eq ! (
328+ alloc:: string:: ToString :: to_string( & err) ,
329+ "bad sampler range for UniformChar at line 1 column 51"
330+ ) ;
331+ }
332+ }
333+
301334 #[ test]
302335 #[ cfg_attr( miri, ignore) ] // Miri is too slow
303336 fn test_durations ( ) {
0 commit comments