|
| 1 | +// Copyright 2024 FastLabs Developers |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +use std::time::Duration; |
| 16 | +use std::time::Instant; |
| 17 | + |
| 18 | +use fastimer::Interval; |
| 19 | +use fastimer::MakeDelay; |
| 20 | +use fastimer::MakeDelayExt; |
| 21 | + |
| 22 | +#[track_caller] |
| 23 | +fn assert_duration_eq(actual: Duration, expected: Duration) { |
| 24 | + if expected.abs_diff(actual) > Duration::from_millis(250) { |
| 25 | + panic!("expected: {:?}, actual: {:?}", expected, actual); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +async fn assert_tick_about<D: MakeDelay>(interval: &mut Interval<D>, expected: Duration) { |
| 30 | + let start = Instant::now(); |
| 31 | + interval.tick().await; |
| 32 | + let elapsed = start.elapsed(); |
| 33 | + assert_duration_eq(elapsed, expected); |
| 34 | +} |
| 35 | + |
| 36 | +#[derive(Clone, Copy, Debug, Default)] |
| 37 | +pub struct MakeTokioDelay; |
| 38 | + |
| 39 | +impl MakeDelay for MakeTokioDelay { |
| 40 | + type Delay = tokio::time::Sleep; |
| 41 | + |
| 42 | + fn delay_util(&self, at: Instant) -> Self::Delay { |
| 43 | + tokio::time::sleep_until(tokio::time::Instant::from_std(at)) |
| 44 | + } |
| 45 | + |
| 46 | + fn delay(&self, duration: Duration) -> Self::Delay { |
| 47 | + tokio::time::sleep(duration) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +#[tokio::test] |
| 52 | +async fn test_interval_ticks() { |
| 53 | + let mut interval = MakeTokioDelay.interval(Duration::from_secs(1)); |
| 54 | + assert_tick_about(&mut interval, Duration::ZERO).await; |
| 55 | + |
| 56 | + for _ in 0..5 { |
| 57 | + assert_tick_about(&mut interval, Duration::from_secs(1)).await; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +#[tokio::test] |
| 62 | +async fn test_interval_at_ticks() { |
| 63 | + let first_tick = Instant::now() + Duration::from_secs(2); |
| 64 | + |
| 65 | + let mut interval = MakeTokioDelay.interval_at(first_tick, Duration::from_secs(1)); |
| 66 | + assert_tick_about(&mut interval, Duration::from_secs(2)).await; |
| 67 | + |
| 68 | + for _ in 0..5 { |
| 69 | + assert_tick_about(&mut interval, Duration::from_secs(1)).await; |
| 70 | + } |
| 71 | +} |
0 commit comments