Skip to content

Commit

Permalink
Change signature of getIndex to return Maybe
Browse files Browse the repository at this point in the history
  • Loading branch information
rnjtranjan authored and harendra-kumar committed Jul 21, 2023
1 parent a87bf85 commit e89e5c1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
6 changes: 3 additions & 3 deletions core/src/Streamly/Internal/Data/Array/Generic/Mut/Type.hs
Original file line number Diff line number Diff line change
Expand Up @@ -468,11 +468,11 @@ getIndexUnsafe n MutArray {..} =
-- | /O(1)/ Lookup the element at the given index. Index starts from 0.
--
{-# INLINE getIndex #-}
getIndex :: MonadIO m => Int -> MutArray a -> m a
getIndex :: MonadIO m => Int -> MutArray a -> m (Maybe a)
getIndex i arr@MutArray {..} =
if i >= 0 && i < arrLen
then getIndexUnsafe i arr
else invalidIndex "getIndex" i
then Just <$> getIndexUnsafe i arr
else return Nothing

-------------------------------------------------------------------------------
-- Subarrays
Expand Down
10 changes: 6 additions & 4 deletions core/src/Streamly/Internal/Data/Array/Mut/Type.hs
Original file line number Diff line number Diff line change
Expand Up @@ -994,12 +994,12 @@ getIndexUnsafe i MutArray{..} = do
-- | /O(1)/ Lookup the element at the given index. Index starts from 0.
--
{-# INLINE getIndex #-}
getIndex :: forall m a. (MonadIO m, Unbox a) => Int -> MutArray a -> m a
getIndex :: forall m a. (MonadIO m, Unbox a) => Int -> MutArray a -> m (Maybe a)
getIndex i MutArray{..} = do
let index = INDEX_OF(arrStart,i,a)
if i >= 0 && INDEX_VALID(index,arrEnd,a)
then liftIO $ peekWith arrContents index
else invalidIndex "getIndex" i
then liftIO $ Just <$> peekWith arrContents index
else return Nothing

-- | /O(1)/ Lookup the element at the given index from the end of the array.
-- Index starts from 0.
Expand Down Expand Up @@ -1038,7 +1038,9 @@ getIndicesD liftio (D.Stream stepi sti) = Unfold step inject
case r of
D.Yield i s -> do
x <- liftio $ getIndex i (MutArray contents start end undefined)
return $ D.Yield x (GetIndicesState contents start end s)
case x of
Just v -> return $ D.Yield v (GetIndicesState contents start end s)
Nothing -> error "Invalid Index"
D.Skip s -> return $ D.Skip (GetIndicesState contents start end s)
D.Stop -> return D.Stop

Expand Down

0 comments on commit e89e5c1

Please sign in to comment.