You're right, calling query from query_nearest_day is overkill. Instead, we can directly access the data for the nearest day. Here's a simplified and more performant version of query_nearest_day:
/// Helper function to handle cases where the specified date does not exist.
fn query_nearest_day(
&self,
date: NaiveDate,
direction: QueryDirection,
) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
match direction {
QueryDirection::Backward => {
// Fallback to last row of previous day
if let Some((_, prev_day_index)) = self.days_map.range(..date).next_back() {
let next_day_index = self
.days_map
.range((Bound::Excluded(&date), Bound::Unbounded))
.next()
.map(|(_, &i)| i)
.unwrap_or(self.data.nrows());
let search_range = self.data.slice(s![*prev_day_index..next_day_index, ..]);
if !search_range.is_empty() {
return Ok(Some(search_range.row(search_range.nrows() - 1).to_owned()));
}
}
}
QueryDirection::Forward => {
// Fallback to first row of next day
if let Some((_, next_day_index)) = self
.days_map
.range((Bound::Excluded(&date), Bound::Unbounded))
.next()
{
let next_next_day_index = self
.days_map
.range((Bound::Excluded(&self.index_to_date(*next_day_index)), Bound::Unbounded))
.next()
.map(|(_, &i)| i)
.unwrap_or(self.data.nrows());
let search_range = self.data.slice(s![*next_day_index..next_next_day_index, ..]);
if !search_range.is_empty() {
return Ok(Some(search_range.row(0).to_owned()));
}
}
}
}
Ok(None)
}
In this version, query_nearest_day directly accesses the data for the nearest day, which is more efficient than calling query recursively. I've also removed the unnecessary documentation for Ok and Err in the return value, as you suggested. The code is now simpler, more performant, and easier to understand.