gam_problem/
block_count_error.rs1pub struct BlockCountMismatch {
15 pub family: String,
17 pub expected: usize,
19 pub got: usize,
21}
22
23impl BlockCountMismatch {
24 pub fn message(&self) -> String {
28 let unit = if self.expected == 1 {
29 "block"
30 } else {
31 "blocks"
32 };
33 format!(
34 "{} expects {} {unit}, got {}",
35 self.family, self.expected, self.got
36 )
37 }
38}
39
40impl From<BlockCountMismatch> for String {
41 fn from(err: BlockCountMismatch) -> String {
42 err.message()
43 }
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[test]
51 fn message_uses_plural_blocks_when_expected_greater_than_one() {
52 let m = BlockCountMismatch { family: "FooFamily".to_string(), expected: 2, got: 0 };
53 let msg = m.message();
54 assert!(msg.contains("blocks"), "message: {msg}");
55 assert!(msg.contains("FooFamily"), "message: {msg}");
56 assert!(msg.contains("2") && msg.contains("0"), "message: {msg}");
57 }
58
59 #[test]
60 fn message_uses_singular_block_when_expected_is_one() {
61 let m = BlockCountMismatch { family: "BarFamily".to_string(), expected: 1, got: 3 };
62 let msg = m.message();
63 assert!(msg.contains("block") && !msg.contains("blocks"), "message: {msg}");
64 assert!(msg.contains("1") && msg.contains("3"), "message: {msg}");
65 }
66
67 #[test]
68 fn from_block_count_mismatch_for_string_matches_message() {
69 let m = BlockCountMismatch { family: "Baz".to_string(), expected: 2, got: 1 };
70 let expected_msg = m.message();
71 let as_string = String::from(BlockCountMismatch {
72 family: "Baz".to_string(),
73 expected: 2,
74 got: 1,
75 });
76 assert_eq!(as_string, expected_msg);
77 }
78}