Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rebased and fixed #347 #402

Merged
merged 4 commits into from
Aug 11, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions vector/src/Data/Vector/Generic.hs
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,10 @@ infixl 9 !?
-- | O(1) Safe indexing.
(!?) :: Vector v a => v a -> Int -> Maybe a
{-# INLINE_FUSED (!?) #-}
v !? i | i < 0 || i >= length v = Nothing
| otherwise = Just $ unsafeIndex v i
-- Use basicUnsafeIndexM @Maybe to perform the indexing eagerly.
Shimuuar marked this conversation as resolved.
Show resolved Hide resolved
v !? i | i `inRange` length v = case basicUnsafeIndexM v i of Box a -> Just a
| otherwise = Nothing


-- | /O(1)/ First element.
head :: Vector v a => v a -> a
Expand Down
10 changes: 8 additions & 2 deletions vector/src/Data/Vector/Internal/Check.hs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ module Data.Vector.Internal.Check (
Checks(..), doChecks,

internalError,
check, checkIndex, checkLength, checkSlice
check, checkIndex, checkLength, checkSlice,
inRange
) where

import GHC.Base( Int(..) )
Expand Down Expand Up @@ -112,7 +113,7 @@ checkIndex_msg# i# n# = "index out of bounds " ++ show (I# i#, I# n#)
checkIndex :: HasCallStack => Checks -> Int -> Int -> a -> a
{-# INLINE checkIndex #-}
checkIndex kind i n x
= check kind (checkIndex_msg i n) (i >= 0 && i<n) x
= check kind (checkIndex_msg i n) (inRange i n) x


checkLength_msg :: Int -> String
Expand Down Expand Up @@ -141,3 +142,8 @@ checkSlice :: HasCallStack => Checks -> Int -> Int -> Int -> a -> a
checkSlice kind i m n x
= check kind (checkSlice_msg i m n) (i >= 0 && m >= 0 && m <= n - i) x

-- Lengths are never negative, so we can check 0 <= i < length v
Shimuuar marked this conversation as resolved.
Show resolved Hide resolved
-- using one unsigned comparison.
inRange :: Int -> Int -> Bool
{-# INLINE inRange #-}
inRange i n = (fromIntegral i :: Word) < (fromIntegral n :: Word)