Great idea! Returning Option instead of a custom NotFound error is more idiomatic in Rust when the absence of a result is expected and not an exceptional condition. This simplifies the API and makes it more ergonomic for the caller.
You also asked for improved behavior when querying a date that doesn't exist in the dataset:
- If the date is missing and the direction is Backward, return the last row of the previous day (if any).
- If the date is missing and the direction is Forward, return the first row of the next day (if any).
This makes the query behavior more intuitive and useful.
✅ Summary of changes:
- Return Option instead of Result<_, QueryError> for queries.
- Handle missing dates by falling back to previous/next day depending on direction.
- Keep HDF5 errors as Result (since they are truly exceptional).
- Keep saturating_sub for safe backward indexing.
- Clean, idiomatic, and robust.
Here’s the updated code:
/// Represents the bound type for time series queries
#[derive(Debug, Clone, Copy)]
pub enum TimeQueryBound {
/// Include the exact timestamp if it exists
Inclusive,
/// Exclude the exact timestamp
Exclusive,
}
/// Direction for querying in the time series
#[derive(Debug, Clone, Copy)]
pub enum QueryDirection {
/// Search forward in time
Forward,
/// Search backward in time
Backward,
}
impl TimeSeriesData {
/// Queries the time series for a value at or around the specified timestamp.
///
/// Returns `None` if no matching data is found.
pub fn query(
&self,
time: &NaiveDateTime,
direction: QueryDirection,
bound: TimeQueryBound,
) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
let date = time.date();
// Determine the base index for the current date
let date_index = self.days_map.get(&date).copied();
// If the date is not found, fallback to previous or next day depending on direction
let (start_index, end_index) = match (date_index, direction) {
(Some(idx), _) => {
// Date exists, determine range based on direction
let prev_idx = self
.days_map
.range(..date)
.next_back()
.map(|(_, &i)| i);
let next_idx = self
.days_map
.range((Bound::Excluded(&date), Bound::Unbounded))
.next()
.map(|(_, &i)| i)
.unwrap_or(self.data.nrows());
let start = match direction {
QueryDirection::Backward => prev_idx.unwrap_or(idx),
QueryDirection::Forward => idx,
};
let end = match direction {
QueryDirection::Forward => next_idx + 1,
QueryDirection::Backward => next_idx,
};
(start, end.min(self.data.nrows()))
}
(None, QueryDirection::Backward) => {
// Fallback to last row of previous day
let prev_idx = self
.days_map
.range(..date)
.next_back()
.map(|(_, &i)| i);
if let Some(start) = prev_idx {
let end = self
.days_map
.range((Bound::Excluded(&self.index_to_date(start)), Bound::Unbounded))
.next()
.map(|(_, &i)| i)
.unwrap_or(self.data.nrows());
let range = self.data.slice(s![start..end, ..]);
if range.nrows() > 0 {
let last_row = range.row(range.nrows() - 1).to_owned();
return Ok(Some(last_row));
}
}
return Ok(None);
}
(None, QueryDirection::Forward) => {
// Fallback to first row of next day
let next_idx = self
.days_map
.range((Bound::Excluded(&date), Bound::Unbounded))
.next()
.map(|(_, &i)| i);
if let Some(start) = next_idx {
let end = self
.days_map
.range((Bound::Excluded(&self.index_to_date(start)), Bound::Unbounded))
.next()
.map(|(_, &i)| i)
.unwrap_or(self.data.nrows());
let range = self.data.slice(s![start..end, ..]);
if range.nrows() > 0 {
let first_row = range.row(0).to_owned();
return Ok(Some(first_row));
}
}
return Ok(None);
}
};
let search_range = self.data.slice(s![start_index..end_index, ..]);
let timestamp = Self::time_to_timestamp(time, self.timestamp_factor);
let row_index = match (direction, bound) {
(QueryDirection::Forward, TimeQueryBound::Inclusive) => {
search_range
.column(0)
.to_vec()
.partition_point(|ts| ts < ×tamp)
}
(QueryDirection::Forward, TimeQueryBound::Exclusive) => {
search_range
.column(0)
.to_vec()
.partition_point(|ts| ts <= ×tamp)
}
(QueryDirection::Backward, TimeQueryBound::Inclusive) => {
search_range
.column(0)
.to_vec()
.partition_point(|ts| ts <= ×tamp)
.saturating_sub(1)
}
(QueryDirection::Backward, TimeQueryBound::Exclusive) => {
search_range
.column(0)
.to_vec()
.partition_point(|ts| ts < ×tamp)
.saturating_sub(1)
}
};
if row_index >= search_range.nrows() {
return Ok(None);
}
Ok(Some(search_range.row(row_index).to_owned()))
}
/// Convenience method to get the next value after the specified time
pub fn query_after(&self, time: &NaiveDateTime) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
self.query(time, QueryDirection::Forward, TimeQueryBound::Exclusive)
}
/// Convenience method to get the last value before or at the specified time
pub fn query_before(&self, time: &NaiveDateTime) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
self.query(time, QueryDirection::Backward, TimeQueryBound::Inclusive)
}
/// Helper to get the date corresponding to a row index
fn index_to_date(&self, index: usize) -> NaiveDate {
// This assumes days_map is sorted and maps to the first row of each day
// So we reverse search for the largest index <= given index
self.days_map
.iter()
.rev()
.find(|(_, &i)| i <= index)
.map(|(d, _)| *d)
.expect("Index should always map to a date")
}
}
🧠 Notes:
- The fallback logic for missing dates is now direction-aware and returns the first/last row of the adjacent day.
- The query returns Option instead of Result<Option<_>, _> unless there's an HDF5 error.
- The index_to_date helper is used to reverse-map an index to a date for fallback range calculation.
- The saturating_sub is still necessary for safe backward indexing.
✅ Example usage:
if let Some(row) = ts.query_after(×tamp)? {
println!("Next row: {:?}", row);
} else {
println!("No next row found");
}
Let me know if you'd like to support range queries or batch results next!