Mastodon Icon RSS Icon GitHub Icon LinkedIn Icon RSS Icon

MovingAI-Rust 2.1.0: Now panic-free!

A small update to my pathfinding benchmark parser

Since my Ph.D. days, I maintain a small Rust library for parsing and using the benchmark maps of the MovingAI suite: a popular (at least in academia) collection of benchmark maps and scenarios designed to measure the performance of pathfinding algorithms.

This week I released version 2.1.0. It is not a big change, but it is a breaking change and I care for my semantic versioning. At least for libraries.

The main changes are that I vastly reduced chance triggering panic when parsing malformed data. In fact, in Rust, it is not good practice to make a library panic for recoverable errors: it is messy for a library to dictate to the host application how they should handle errors. It is kinda bad that I left so many “panics” for so long.

The idiomatic way to handle errors is with Result. So, for instance, I changed this block:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let param: Vec<&str> = line.split(' ').collect();
if param.len() == 2 {
	let key = param[0];
	let value = param[1];
	if key == "type" {
		map_type = String::from(value);
	} else if key == "height" {
		height = value.parse::<usize>().expect("Error parsing map height.");
	} else if key == "width" {
		width = value.parse::<usize>().expect("Error parsing map width.");
	}
}

with this

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
let param: Vec<&str> = line.split_whitespace().collect();
if param.len() == 2 {
	let key = param[0];
	let value = param[1];
	match key {
		"type" => map_type = value.to_string(),
		"height" => {
			height = value.parse::<usize>().map_err(|_| {
				io::Error::new(io::ErrorKind::InvalidData, "Error parsing map height.")
			})?
		}
		"width" => {
			width = value.parse::<usize>().map_err(|_| {
				io::Error::new(io::ErrorKind::InvalidData, "Error parsing map width.")
			})?
		}
		_ => {}
	}

In the old version, if value.parse returned an error, the library panicked with a message. Now, the library maps the error in an InvalidData Error and returns the error. Much more idiomatic.

There are other small places where I followed a similar approach and the result is that the library is now 100% panic-free (or, at least, it should).