Skip to content

Commit e42763b

Browse files
Improve takeInterval and dropInterval
takeInterval: merge the stream with a timer stream of a single element, instead of an endless stream of ticks generated by interject. dropInterval: read the clock for each element until the interval has passed, in a hand-written state machine. It requires only MonadIO instead of MonadAsync. Drop all the elements if the interval in nanoseconds overflows an Int64. Both: for a zero, negative or NaN interval, takeInterval takes nothing and dropInterval drops nothing. Add tests for zero, negative, NaN and overflowing intervals, and for takeInterval on a stream blocked in its evaluation. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 56baef4 commit e42763b

2 files changed

Lines changed: 131 additions & 18 deletions

File tree

  • src/Streamly/Internal/Data/Stream
  • test/Streamly/Test/Data/Stream/Prelude

‎src/Streamly/Internal/Data/Stream/Time.hs‎

Lines changed: 76 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,12 @@ module Streamly.Internal.Data.Stream.Time
5757
)
5858
where
5959

60+
#include "inline.hs"
61+
6062
import Control.Exception (assert)
6163
import Control.Monad.IO.Class (MonadIO(..))
6264
import Data.Heap (Entry(..))
65+
import Data.Int (Int64)
6366
import Data.Kind (Type)
6467
import Data.Map (Map)
6568
import Data.Maybe (isJust, isNothing)
@@ -70,7 +73,7 @@ import Streamly.Internal.Data.Array (Array)
7073
import Streamly.Internal.Data.Fold (Fold (..))
7174
import Streamly.Internal.Data.IsMap (IsMap(..))
7275
import Streamly.Internal.Data.Channel.Types (Rate)
73-
import Streamly.Internal.Data.Stream (Stream)
76+
import Streamly.Internal.Data.Stream (Stream, Step(..))
7477
import Streamly.Internal.Data.Stream.Channel.Type (rate)
7578
import Streamly.Internal.Data.Time.Units
7679
( AbsTime
@@ -79,7 +82,9 @@ import Streamly.Internal.Data.Time.Units
7982
, toAbsTime
8083
, toRelTime
8184
)
82-
import Streamly.Internal.Data.Time.Units (NanoSecond64(..), toRelTime64)
85+
import Streamly.Internal.Data.Time.Clock (Clock(Monotonic), getTime)
86+
import Streamly.Internal.Data.Time.Units
87+
(NanoSecond64(..), addToAbsTime64, toRelTime64)
8388

8489
import qualified Data.Heap as H
8590
import qualified Streamly.Internal.Data.Array as Array
@@ -90,7 +95,8 @@ import qualified Streamly.Data.Unfold as Unfold
9095
import qualified Streamly.Internal.Data.Fold as Fold (Step(..))
9196
import qualified Streamly.Internal.Data.IsMap as IsMap
9297
import qualified Streamly.Internal.Data.Stream as Stream
93-
( scanlMAfter'
98+
( Stream(Stream)
99+
, scanlMAfter'
94100
, sleep
95101
, timeIndexed
96102
, timestamped
@@ -179,19 +185,23 @@ ticksRate r = parBuffered (rate (Just r)) $ Stream.repeatM (return ())
179185
interject :: MonadAsync m => m a -> Double -> Stream m a -> Stream m a
180186
interject f n xs = parListEagerFst [xs, periodic f n]
181187

182-
-- XXX No element should be yielded if the duration is zero.
183-
184188
-- | @takeInterval interval@ runs the stream only upto the specified time
185-
-- @interval@ in seconds.
189+
-- @interval@ in seconds. No element is yielded if the interval is zero,
190+
-- negative or NaN.
186191
--
187192
-- The interval starts when the stream is evaluated for the first time.
188193
--
189194
{-# INLINE takeInterval #-}
190195
takeInterval :: MonadAsync m => Double -> Stream m a -> Stream m a
191-
takeInterval d =
192-
Stream.catMaybes
193-
. Stream.takeWhile isJust
194-
. interject (return Nothing) d . fmap Just
196+
takeInterval d xs
197+
| not (d > 0) = Stream.nil
198+
| otherwise =
199+
Stream.catMaybes
200+
$ Stream.takeWhile isJust
201+
$ parListEagerFst
202+
[ fmap Just xs
203+
, Stream.fromEffect (Stream.sleep d >> return Nothing)
204+
]
195205

196206
-- | Take time interval @i@ seconds at the end of the stream.
197207
--
@@ -203,19 +213,68 @@ takeLastInterval :: -- MonadAsync m =>
203213
Double -> Stream m a -> Stream m a
204214
takeLastInterval = undefined
205215

206-
-- XXX All elements should be yielded if the duration is zero.
216+
data DropIntervalState s
217+
= DropIntervalInit s
218+
| DropIntervalDrop !AbsTime s
219+
| DropIntervalDropAll s
220+
| DropIntervalYield s
207221

208222
-- | @dropInterval interval@ drops all the stream elements that are generated
209-
-- before the specified @interval@ in seconds has passed.
223+
-- before the specified @interval@ in seconds has passed. No element is dropped
224+
-- if the interval is zero, negative or NaN. All the elements are dropped if the
225+
-- interval is too large to be represented in nanoseconds as an 'Int64'.
210226
--
211227
-- The interval begins when the stream is evaluated for the first time.
212228
--
229+
-- An element is dropped or yielded depending on the time at which it is
230+
-- generated, not on the time at which the action generating it starts.
231+
--
213232
{-# INLINE dropInterval #-}
214-
dropInterval :: MonadAsync m => Double -> Stream m a -> Stream m a
215-
dropInterval d =
216-
Stream.catMaybes
217-
. Stream.dropWhile isJust
218-
. interject (return Nothing) d . fmap Just
233+
dropInterval :: MonadIO m => Double -> Stream m a -> Stream m a
234+
dropInterval d (Stream.Stream step state) =
235+
Stream.Stream step1 (DropIntervalInit state)
236+
237+
where
238+
239+
-- The interval in nanoseconds must fit in an Int64, with a margin of one
240+
-- second as it is added to the nanoseconds of the current time.
241+
maxInterval :: Double
242+
maxInterval = fromIntegral (maxBound :: Int64) / 1000000000 - 1
243+
244+
-- The clock is read only until the interval has passed.
245+
{-# INLINE_LATE step1 #-}
246+
step1 _ (DropIntervalInit st)
247+
| not (d > 0) = return $ Skip $ DropIntervalYield st
248+
| d >= maxInterval = return $ Skip $ DropIntervalDropAll st
249+
| otherwise = do
250+
now <- liftIO $ getTime Monotonic
251+
let i = toRelTime64 (NanoSecond64 (round (d * 1000000000)))
252+
return $ Skip $ DropIntervalDrop (addToAbsTime64 now i) st
253+
step1 gst (DropIntervalDrop end st) = do
254+
r <- step gst st
255+
case r of
256+
Yield x s -> do
257+
now <- liftIO $ getTime Monotonic
258+
return
259+
$ if now >= end
260+
then Yield x (DropIntervalYield s)
261+
else Skip (DropIntervalDrop end s)
262+
Skip s -> return $ Skip (DropIntervalDrop end s)
263+
Stop -> return Stop
264+
step1 gst (DropIntervalDropAll st) = do
265+
r <- step gst st
266+
return
267+
$ case r of
268+
Yield _ s -> Skip (DropIntervalDropAll s)
269+
Skip s -> Skip (DropIntervalDropAll s)
270+
Stop -> Stop
271+
step1 gst (DropIntervalYield st) = do
272+
r <- step gst st
273+
return
274+
$ case r of
275+
Yield x s -> Yield x (DropIntervalYield s)
276+
Skip s -> Skip (DropIntervalYield s)
277+
Stop -> Stop
219278

220279
-- | Drop time interval @i@ seconds at the end of the stream.
221280
--

‎test/Streamly/Test/Data/Stream/Prelude/Time.hs‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@
1414
module Streamly.Test.Data.Stream.Prelude.Time (main) where
1515

1616
import Control.Concurrent ( threadDelay )
17-
#ifdef DEVBUILD
1817
import Control.Monad ( when)
18+
import System.Timeout (timeout)
19+
#ifdef DEVBUILD
1920
import Data.Int (Int64)
2021
import Streamly.Internal.Data.Time.Clock (Clock(Monotonic), getTime)
2122
import Streamly.Internal.Data.Time.Units
@@ -102,6 +103,39 @@ dropIntervalAll =
102103
$ Stream.dropInterval longInterval
103104
$ Stream.fromList [1..10]
104105

106+
-- Zero, negative and NaN intervals.
107+
takeIntervalOf :: Double -> IO [Int]
108+
takeIntervalOf d =
109+
Stream.fold Fold.toList
110+
$ Stream.takeInterval d
111+
$ Stream.fromList [1..10]
112+
113+
dropIntervalOf :: Double -> IO [Int]
114+
dropIntervalOf d =
115+
Stream.fold Fold.toList
116+
$ Stream.dropInterval d
117+
$ Stream.fromList [1..10]
118+
119+
nan :: Double
120+
nan = 0 / 0
121+
122+
-- The stream blocks for a long time after its first element, takeInterval
123+
-- must end it at the end of the interval nevertheless.
124+
takeIntervalBlocked :: IO (Maybe [Int])
125+
takeIntervalBlocked =
126+
timeout 10000000
127+
$ Stream.fold Fold.toList
128+
$ Stream.takeInterval shortInterval
129+
$ Stream.mapM (\x -> when (x > 1) (threadDelay 100000000) >> return x)
130+
$ Stream.fromList [1..10]
131+
132+
-- An interval that overflows an Int64 when converted to nanoseconds.
133+
dropIntervalHuge :: Double -> IO [Int]
134+
dropIntervalHuge d =
135+
Stream.fold Fold.toList
136+
$ Stream.dropInterval d
137+
$ Stream.fromList [1..10]
138+
105139
-- The stream is endless, so this returns only if takeInterval ends it. The
106140
-- elements taken must be the beginning of the stream.
107141
takeIntervalPrefix :: IO Bool
@@ -149,4 +183,24 @@ main = hspec
149183
(dropIntervalAll `shouldReturn` [])
150184
it "dropInterval yields the elements after the interval"
151185
(dropIntervalSuffix `shouldReturn` True)
186+
it "takeInterval takes nothing if the interval is zero"
187+
(takeIntervalOf 0 `shouldReturn` [])
188+
it "takeInterval takes nothing if the interval is negative"
189+
(takeIntervalOf (-1) `shouldReturn` [])
190+
it "takeInterval takes nothing if the interval is NaN"
191+
(takeIntervalOf nan `shouldReturn` [])
192+
it "takeInterval ends a blocked stream after the interval"
193+
(takeIntervalBlocked `shouldReturn` Just [1])
194+
it "dropInterval drops nothing if the interval is zero"
195+
(dropIntervalOf 0 `shouldReturn` [1..10])
196+
it "dropInterval drops nothing if the interval is negative"
197+
(dropIntervalOf (-1) `shouldReturn` [1..10])
198+
it "dropInterval drops nothing if the interval is NaN"
199+
(dropIntervalOf nan `shouldReturn` [1..10])
200+
it "dropInterval drops everything if the interval is 1e10 seconds"
201+
(dropIntervalHuge 1e10 `shouldReturn` [])
202+
it "dropInterval drops everything if the interval is 1e300 seconds"
203+
(dropIntervalHuge 1e300 `shouldReturn` [])
204+
it "dropInterval drops everything if the interval is infinite"
205+
(dropIntervalHuge (1/0) `shouldReturn` [])
152206

0 commit comments

Comments
 (0)