Absolutely! Let's simplify the code by reducing nesting and repetition. We'll also add concise and clear documentation for each function.
Simplified Code
Here’s the refactored version of the query function, with reduced nesting and duplication:
rust
/// 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.
///
/// This function supports querying in both forward and backward directions,
/// with options to include or exclude the exact timestamp in the search.
///
/// If the queried date does not exist:
/// - For `Backward`, it falls back to the last row of the previous day (if any).
/// - For `Forward`, it falls back to the first row of the next day (if any).
///
/// # Arguments
/// * `time` - The timestamp to query.
/// * `direction` - The direction to search (`Forward` or `Backward`).
/// * `bound` - Whether to include or exclude the exact timestamp match.
///
/// # Returns
/// * `Some(Array1<i32>)` - The row of data at the found timestamp.
/// * `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();
let date_index = self.days_map.get(&date).copied();
// Determine the search range based on the direction and fallback logic
let (start_index, end_index) = match (date_index, direction) {
(Some(idx), _) => self.range_for_existing_date(idx, date, direction),
(None, QueryDirection::Backward) => return self.fallback_to_previous_day(time, direction),
(None, QueryDirection::Forward) => return self.fallback_to_next_day(time, direction),
};
// Slice the search range and find the matching row
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.
///
/// # Arguments
/// * `time` - The timestamp to query.
///
/// # Returns
/// * `Some(Array1<i32>)` - The next row of data after the timestamp.
/// * `None` - If no matching data is found.
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.
///
/// # Arguments
/// * `time` - The timestamp to query.
///
/// # Returns
/// * `Some(Array1<i32>)` - The last row of data before or at the timestamp.
/// * `None` - If no matching data is found.
pub fn query_before(&self, time: &NaiveDateTime) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
self.query(time, QueryDirection::Backward, TimeQueryBound::Inclusive)
}
// Helper to determine the search range for an existing date
fn range_for_existing_date(&self, idx: usize, date: NaiveDate, direction: QueryDirection) -> (usize, usize) {
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);
let start = match direction {
QueryDirection::Backward => prev_idx.unwrap_or(idx),
QueryDirection::Forward => idx,
};
let end = match direction {
QueryDirection::Forward => next_idx.unwrap_or(self.data.nrows()) + 1,
QueryDirection::Backward => next_idx.unwrap_or(self.data.nrows()),
};
(start, end.min(self.data.nrows()))
}
// Fallback to the last row of the previous day for backward queries
fn fallback_to_previous_day(
&self,
time: &NaiveDateTime,
direction: QueryDirection,
) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
let prev_idx = self.days_map.range(..time.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 {
return Ok(Some(range.row(range.nrows() - 1).to_owned()));
}
}
Ok(None)
}
// Fallback to the first row of the next day for forward queries
fn fallback_to_next_day(
&self,
time: &NaiveDateTime,
direction: QueryDirection,
) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
let next_idx = self.days_map.range((Bound::Excluded(&time.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 {
return Ok(Some(range.row(0).to_owned()));
}
}
Ok(None)
}
/// Helper to get the date corresponding to a row index.
fn index_to_date(&self, index: usize) -> NaiveDate {
self.days_map
.iter()
.rev()
.find(|(_, &i)| i <= index)
.map(|(d, _)| *d)
.expect("Index should always map to a date")
}
}
Key Improvements
Simplified Logic:
Extracted helper functions like range_for_existing_date, fallback_to_previous_day, and fallback_to_next_day to handle specific cases.
Reduced nesting by handling missing dates early and returning immediately.
Documentation:
Added clear, concise documentation for each function, explaining its purpose, arguments, and return values.
Code Reuse:
Avoided repeating logic for determining ranges and fallbacks by encapsulating common functionality in helper methods.
Idiomatic Rust:
Used Option for missing data and Result only for exceptional errors (e.g., HDF5 issues).
Kept the use of saturating_sub for safe backward indexing.
Example Usage
rust
// Get the next value after a timestamp
if let Some(next_row) = ts.query_after(×tamp)? {
println!("Next row: {:?}", next_row);
} else {
println!("No next row found");
}
// Get the last value before or at a timestamp
if let Some(prev_row) = ts.query_before(×tamp)? {
println!("Previous row: {:?}", prev_row);
} else {
println!("No previous row found");
}
This version is cleaner, easier to read, and more maintainable while retaining all the functionality and edge-case handling. Let me know if you need further refinements!