toon/decode/
validation.rs1use crate::decode::parser::ArrayHeaderInfo;
2use crate::decode::scanner::{BlankLineInfo, Depth, ParsedLine};
3use crate::error::{Result, ToonError};
4use crate::shared::constants::{COLON, LIST_ITEM_PREFIX};
5use crate::shared::string_utils::find_unquoted_char;
6
7pub fn assert_expected_count(
13 actual: usize,
14 expected: usize,
15 item_type: &str,
16 strict: bool,
17) -> Result<()> {
18 if strict && actual != expected {
19 return Err(ToonError::message(format!(
20 "Expected {expected} {item_type}, but got {actual}"
21 )));
22 }
23 Ok(())
24}
25
26pub fn validate_no_extra_list_items(
32 next_line: Option<&ParsedLine>,
33 item_depth: Depth,
34 expected_count: usize,
35 strict: bool,
36) -> Result<()> {
37 if strict
38 && let Some(line) = next_line
39 && line.depth == item_depth
40 && line.content.starts_with(LIST_ITEM_PREFIX)
41 {
42 return Err(ToonError::message(format!(
43 "Expected {expected_count} list array items, but found more"
44 )));
45 }
46 Ok(())
47}
48
49pub fn validate_no_extra_tabular_rows(
55 next_line: Option<&ParsedLine>,
56 row_depth: Depth,
57 header: &ArrayHeaderInfo,
58 strict: bool,
59) -> Result<()> {
60 if strict
61 && let Some(line) = next_line
62 && line.depth == row_depth
63 && !line.content.starts_with(LIST_ITEM_PREFIX)
64 && is_data_row(&line.content, header.delimiter)
65 {
66 return Err(ToonError::message(format!(
67 "Expected {} tabular rows, but found more",
68 header.length
69 )));
70 }
71 Ok(())
72}
73
74pub fn validate_no_blank_lines_in_range(
80 start_line: usize,
81 end_line: usize,
82 blank_lines: &[BlankLineInfo],
83 strict: bool,
84 context: &str,
85) -> Result<()> {
86 if !strict {
87 return Ok(());
88 }
89
90 if let Some(first_blank) = blank_lines
91 .iter()
92 .find(|blank| blank.line_number > start_line && blank.line_number < end_line)
93 {
94 return Err(ToonError::message(format!(
95 "Line {}: Blank lines inside {context} are not allowed in strict mode",
96 first_blank.line_number
97 )));
98 }
99
100 Ok(())
101}
102
103fn is_data_row(content: &str, delimiter: char) -> bool {
104 let colon_pos = find_unquoted_char(content, COLON, 0);
106 let delimiter_pos = find_unquoted_char(content, delimiter, 0);
107
108 if colon_pos.is_none() {
110 return true;
111 }
112
113 if let Some(delimiter_pos) = delimiter_pos
115 && let Some(colon_pos) = colon_pos
116 {
117 return delimiter_pos < colon_pos;
118 }
119
120 false
121}