1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Boost.Polygon library detail/robust_fpt.hpp header file

//          Copyright Andrii Sydorchuk 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

// See http://www.boost.org for updates, documentation, and revision history of C++ code..

// Ported from C++ boost 1.76.0 to Rust in 2020/2021 by Eadf (github.com/eadf)

//! Utility for reading example files.

use crate::{cast, geometry, BvError};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;

#[derive(Debug)]
enum InputData<T: crate::InputType> {
    Number(usize),
    Point(geometry::Point<T>),
    Line(geometry::Line<T>),
}

#[derive(Eq, PartialEq, Debug)]
enum StateMachine {
    StartingPoints,
    ExpectPoints,
    StartingLines,
    ExpectLines,
}

fn line_to_data<I: crate::InputType>(line: &str) -> Option<InputData<I>> {
    let line = line.split(' ').collect::<Vec<&str>>();
    //tln!("line split: {:?}", line);
    match line.len() {
        1 => {
            if let Ok(n) = line[0].parse::<usize>() {
                return Some(InputData::Number(n));
            } else {
                eprintln!("failed to parse {}, ignoring line", line[0]);
            }
        }
        2 => {
            if let Ok(x1) = line[0].parse::<i32>() {
                if let Ok(y1) = line[1].parse::<i32>() {
                    return Some(InputData::Point(geometry::Point::<I> {
                        x: cast::<i32, I>(x1),
                        y: cast::<i32, I>(y1),
                    }));
                } else {
                    println!("failed to parse {}, ignoring line", line[1]);
                }
            } else {
                println!("failed to parse {}, ignoring line", line[0]);
            }
        }
        4 => {
            if let Ok(x1) = line[0].parse::<i32>() {
                if let Ok(y1) = line[1].parse::<i32>() {
                    if let Ok(x2) = line[2].parse::<i32>() {
                        if let Ok(y2) = line[3].parse::<i32>() {
                            return Some(InputData::Line(geometry::Line::<I>::from([
                                cast::<i32, I>(x1),
                                cast::<i32, I>(y1),
                                cast::<i32, I>(x2),
                                cast::<i32, I>(y2),
                            ])));
                        } else {
                            println!("failed to parse {}, ignoring line", line[3]);
                        }
                    } else {
                        println!("failed to parse {}, ignoring line", line[2]);
                    }
                } else {
                    println!("failed to parse {}, ignoring line", line[1]);
                }
            } else {
                println!("failed to parse {}, ignoring line", line[0]);
            }
        }
        _ => println!("failed to parse {:?}, ignoring line", line),
    }
    None
}

/// Reads an example file in the file format used by C++ boost voronoi:
///
/// `[number of points]`<br>
/// `[X] [Y] (repeats)`<br>
/// `[number of lines]`<br>
/// `[X1] [Y1] [X2] [Y2](repeats)`
// This entire module is implemented in about 20 lines of code in C++ boost :/
#[allow(clippy::type_complexity)]
pub fn read_boost_input_file<I: crate::InputType>(
    filename: &Path,
) -> Result<(Vec<geometry::Point<I>>, Vec<geometry::Line<I>>), BvError> {
    if !filename.is_file() {
        return Err(BvError::ValueError(format!("{:?} not a file", filename)));
    }
    // Open the file in read-only mode
    let file = File::open(filename)?;
    let reader = BufReader::new(file);
    read_boost_input_buffer::<I, _>(reader)
}

/// Reads an example from a buffer using the format used by C++ boost voronoi:
///
/// `[number of points]`<br>
/// `[X] [Y] (repeats)`<br>
/// `[number of lines]`<br>
/// `[X1] [Y1] [X2] [Y2](repeats)`
#[allow(clippy::type_complexity)]
pub fn read_boost_input_buffer<I: crate::InputType, F: std::io::Read>(
    reader: BufReader<F>,
) -> Result<(Vec<geometry::Point<I>>, Vec<geometry::Line<I>>), BvError> {
    let mut points = Vec::<geometry::Point<I>>::default();
    let mut lines = Vec::<geometry::Line<I>>::default();
    let mut state = StateMachine::StartingPoints;
    let mut expected_points = 0;
    let mut expected_lines = 0;

    // Read the file line by line using the lines() iterator from std::io::BufRead.
    for (index, line) in reader.lines().enumerate() {
        if let Ok(line) = line {
            //println!("got {:?}, state:{:?}", line, state);
            if let Some(data) = line_to_data::<I>(&line) {
                if state == StateMachine::StartingPoints {
                    if let InputData::Number(n) = data {
                        expected_points = n;
                        if expected_points == 0 {
                            state = StateMachine::StartingLines
                        } else {
                            state = StateMachine::ExpectPoints
                        }
                        continue;
                    } else {
                        println!(
                            "#{}: can't read line {}. state:{:?} ignoring line",
                            index + 1,
                            line,
                            state
                        );
                        break;
                    }
                } else if state == StateMachine::ExpectPoints {
                    if expected_points > points.len() {
                        if let InputData::Point(geometry::Point::<I> { x, y }) = data {
                            points.push(geometry::Point { x, y });
                            if expected_points == points.len() {
                                state = StateMachine::StartingLines;
                            }
                        } else {
                            println!(
                                "#{}: can't read line {}. state:{:?} ignoring line",
                                index + 1,
                                line,
                                state
                            );
                            break;
                        }
                        continue;
                    } else {
                        println!(
                            "#{}: Got too many points {}. state:{:?} ignoring it",
                            index + 1,
                            line,
                            state
                        );
                        break;
                    }
                } else if state == StateMachine::StartingLines {
                    if let InputData::Number(n) = data {
                        expected_lines = n;
                        state = StateMachine::ExpectLines;
                        continue;
                    } else {
                        println!(
                            "#{}: can't read line {}. state:{:?} ignoring line",
                            index + 1,
                            line,
                            state
                        );
                        break;
                    }
                } else if state == StateMachine::ExpectLines {
                    if expected_lines > lines.len() {
                        if let InputData::Line(a_line) = data {
                            lines.push(a_line);
                            if expected_lines == lines.len() {
                                break;
                            }
                            continue;
                        } else {
                            println!(
                                "#{}: can't read line {} state:{:?} ignoring line",
                                index + 1,
                                line,
                                state
                            );
                            break;
                        }
                    } else {
                        println!(
                            "#{}: Got too many lines {}. state:{:?} ignoring line",
                            index + 1,
                            line,
                            state
                        );
                        break;
                    }
                }
            };
            println!(
                "#{}: can't parse line {}. state:{:?} ignoring line",
                index + 1,
                line,
                state
            );
            break;
        }
    }
    if expected_lines < lines.len() {
        println!(
            "Expected to get {} lines, got {}",
            expected_lines,
            lines.len()
        );
    }
    if expected_points < points.len() {
        println!(
            "Expected to get {} points, got {}",
            expected_points,
            points.len()
        );
    }
    Ok((points, lines))
}