Okay, I agree that the previous version was getting a bit complex with the nested matches and fallback logic. Here's a simplified and refactored version, along with comprehensive function documentation, that addresses your concern about code complexity. The core logic remains the same, but it's reorganized to be more readable and less repetitive.
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.
///
/// If the specified date does not exist in the dataset, this function will attempt to
/// return the first value of the next day (if direction is `Forward`) or the last
/// value of the previous day (if direction is `Backward`).
///
/// # Arguments
///
/// * `time`: The timestamp to query.
/// * `direction`: The direction in which to search.
/// * `bound`: Whether to include or exclude the exact timestamp match.
///
/// # Returns
///
/// * `Ok(Some(Array1<i32>))`: The row of data at the found timestamp.
/// * `Ok(None)`: If no matching data is found.
/// * `Err(hdf5::Error)`: If there's an error accessing the data.
pub fn query(
&self,
time: &NaiveDateTime,
direction: QueryDirection,
bound: TimeQueryBound,
) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
let date = time.date();
// Try to find the index for the specified date.
match self.days_map.get(&date).copied() {
Some(date_index) => {
// Date exists, perform query within its range.
self.query_in_range(time, direction, bound, date_index)
}
None => {
// Date does not exist, fallback to the nearest day.
self.query_nearest_day(date, direction)
}
}
}
/// Convenience method to get the next value after the specified time
/// Returns None if no such value exists, or an HDF5 error if there is a problem accessing the data.
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.
/// Returns None if no such value exists, or an HDF5 error if there is a problem accessing the data.
pub fn query_before(&self, time: &NaiveDateTime) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
self.query(time, QueryDirection::Backward, TimeQueryBound::Inclusive)
}
/// Helper function to query within a known date range.
fn query_in_range(
&self,
time: &NaiveDateTime,
direction: QueryDirection,
bound: TimeQueryBound,
date_index: usize,
) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
let date = time.date();
let next_day_index = self
.days_map
.range((Bound::Excluded(&date), Bound::Unbounded))
.next()
.map(|(_, &i)| i)
.unwrap_or(self.data.nrows());
let start_index = date_index;
let end_index = next_day_index.min(self.data.nrows());
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()))
}
/// 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
let prev_date = self.days_map.range(..date).next_back().map(|(d, _)| *d);
if let Some(prev_date) = prev_date {
let time = NaiveDateTime::new(prev_date, time::time!(23:59:59));
return self.query(
&time,
QueryDirection::Backward,
TimeQueryBound::Inclusive,
);
}
}
QueryDirection::Forward => {
// Fallback to first row of next day
let next_date = self
.days_map
.range((Bound::Excluded(&date), Bound::Unbounded))
.next()
.map(|(d, _)| *d);
if let Some(next_date) = next_date {
let time = NaiveDateTime::new(next_date, time::time!(00:00:00));
return self.query(&time, QueryDirection::Forward, TimeQueryBound::Inclusive);
}
}
}
Ok(None)
}
/// 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")
}
}
Key improvements in this version:
Separation of concerns: I've split the query function into three separate functions:
query: This is the main entry point that determines whether to query within a range or fallback to the nearest day.
query_in_range: This function handles the query within a known date range.
query_nearest_day: This function handles the case where the specified date does not exist and falls back to the nearest day.
Reduced nesting: The code is less nested, making it easier to follow the logic.
Improved readability: The code is more readable and easier to understand.
Comprehensive documentation: Each function is fully documented.
This refactored version addresses your concerns about code complexity while maintaining the robustness and functionality of the previous version.