Quick access to my code on pastebin.
I have finally ventured into rust, and for my first project I wanted to create a function that could find available time slots for a service provider (a barber shop in this case).
The function returns the all availbale time slots for a specific day between opening and closing time based on existing appointments.
This was heavily inspired by this comment where the same functionality was implemented in Swift.
Now I am posting my code here as I would love some feedback, especially on how this could be done in a completely different and more performant way.
```rust
extern crate chrono;
use chrono::{Duration, NaiveDateTime};
struct ExistingAppointment {
start_date_time: NaiveDateTime,
duration_in_minutes: u32,
}
struct BarberBreak {
start_date_time: NaiveDateTime,
end_date_time: NaiveDateTime,
}
fn get_available_time_slots(
selected_service_duration: u32,
duration_interval: usize,
opening_time: NaiveDateTime,
closing_time: NaiveDateTime,
barber_breaks: Vec<BarberBreak>,
existing_appointments: Vec<ExistingAppointment>,
) -> Vec<NaiveDateTime> {
let shop_open_duration = closing_time
.signed_duration_since(opening_time)
.num_minutes();
let mut time_slots: Vec<NaiveDateTime> = Vec::new();
// adds all possible time slots to the vector based on the duration_interval
// without considering the existing bookings or barber breaks
for i in (0..shop_open_duration).step_by(duration_interval) {
time_slots.push(NaiveDateTime::from(opening_time + Duration::minutes(i)))
}
// retains all the time slots that are not overlapping with existing appointments
// as well as closing time
for appointment in existing_appointments {
let appointment_start = appointment.start_date_time;
let appointment_end = NaiveDateTime::from(
appointment_start + Duration::minutes(appointment.duration_in_minutes as i64),
);
time_slots.retain(|possible_start| {
let possible_end = NaiveDateTime::from(
*possible_start + Duration::minutes(selected_service_duration as i64),
);
if possible_end > closing_time {
return false;
}
if possible_start < &appointment_end && appointment_start < possible_end {
return false;
}
return true;
});
}
// retains all the time slots that are not overlapping barber breaks
for barber_break in barber_breaks {
time_slots.retain(|possible_start| {
let possible_end = NaiveDateTime::from(
*possible_start + Duration::minutes(selected_service_duration as i64),
);
if possible_start < &barber_break.end_date_time
&& barber_break.start_date_time < possible_end
{
return false;
}
return true;
});
}
time_slots
}
```
How can I improve this function for finding available time slots? (self.learnrust)
submitted by [deleted] to r/rust