sudachi/util/
check_params.rs1use crate::dic::grammar::Grammar;
18use crate::error::{SudachiError, SudachiResult};
19
20pub trait CheckParams {
21 fn check_left_id<T: Into<i64>>(&self, raw: T) -> SudachiResult<u16>;
22 fn check_right_id<T: Into<i64>>(&self, raw: T) -> SudachiResult<u16>;
23 fn check_cost<T: Into<i64>>(&self, raw: T) -> SudachiResult<i16>;
24}
25
26impl<'a> CheckParams for Grammar<'a> {
27 fn check_left_id<T: Into<i64>>(&self, raw: T) -> SudachiResult<u16> {
28 let x = raw.into();
29 if x < 0 {
30 return Err(SudachiError::InvalidDataFormat(
31 0,
32 format!("leftId was negative ({}), it must be positive", x),
33 ));
34 }
35 let ux = x as usize;
36 if ux > self.conn_matrix().num_left() {
37 return Err(SudachiError::InvalidDataFormat(
38 ux,
39 format!("max grammar leftId is {}", self.conn_matrix().num_left()),
40 ));
41 }
42 Ok(x as u16)
43 }
44
45 fn check_right_id<T: Into<i64>>(&self, raw: T) -> SudachiResult<u16> {
46 let x = raw.into();
47 if x < 0 {
48 return Err(SudachiError::InvalidDataFormat(
49 0,
50 format!("rightId was negative ({}), it must be positive", x),
51 ));
52 }
53 let ux = x as usize;
54 if ux > self.conn_matrix().num_right() {
55 return Err(SudachiError::InvalidDataFormat(
56 ux,
57 format!("max grammar rightId is {}", self.conn_matrix().num_right()),
58 ));
59 }
60 Ok(x as u16)
61 }
62
63 fn check_cost<T: Into<i64>>(&self, raw: T) -> SudachiResult<i16> {
64 let x = raw.into();
65 if x < (i16::MIN as i64) {
66 return Err(SudachiError::InvalidDataFormat(
67 0,
68 format!(
69 "cost ({}) was lower than the lowest acceptable value ({})",
70 x,
71 i16::MIN
72 ),
73 ));
74 }
75 if x > (i16::MAX as i64) {
76 return Err(SudachiError::InvalidDataFormat(
77 0,
78 format!(
79 "cost ({}) was higher than highest acceptable value ({})",
80 x,
81 i16::MAX
82 ),
83 ));
84 }
85 Ok(x as i16)
86 }
87}