on master help sign in
Refactor getIndexUnsafe, putIndexUnsafe
3d5cd85Harendra Kumar
src/Streamly/Internal/Data/Array/Foreign/Mut/Type.hs+14−9
@@ -317,13 +317,19 @@ unsafeWithNewArray count f = do
317-- Mutation
317-- Mutation
318-------------------------------------------------------------------------------
318-------------------------------------------------------------------------------
319
319
320+-- | Write the given element to the given index of the array. Does not check if
321+-- the index is out of bounds of the array.
322+--
323+-- /Pre-release/
320{-# INLINE putIndexUnsafe #-}
324{-# INLINE putIndexUnsafe #-}
321putIndexUnsafe :: forall m a. (MonadIO m, Storable a)
325putIndexUnsafe :: forall m a. (MonadIO m, Storable a)
322 => Array a -> Int -> a -> m ()
326 => Array a -> Int -> a -> m ()
323−putIndexUnsafe Array {..} i x =
327+putIndexUnsafe Array{..} i x =
324− unsafeWithForeignPtrM aStart
328+ unsafeWithForeignPtrM aStart $ \ptr -> do
325− $ \begin -> do
326− liftIO $ poke (begin `plusPtr` (i * sizeOf (undefined :: a))) x
329+ let elemSize = sizeOf (undefined :: a)
330+ elemPtr = ptr `plusPtr` (elemSize * i)
331+ assert (i >= 0 && elemPtr `plusPtr` elemSize <= aEnd) (return ())
332+ liftIO $ poke elemPtr x
327
333
328-- Internal routine for when the array is being created. Appends one item at
334-- Internal routine for when the array is being created. Appends one item at
329-- the end of the array. Useful when sequentially writing a stream to the
335-- the end of the array. Useful when sequentially writing a stream to the
@@ -421,12 +427,11 @@ shrinkToFit arr@Array{..} = do
421{-# INLINE_NORMAL getIndexUnsafe #-}
427{-# INLINE_NORMAL getIndexUnsafe #-}
422getIndexUnsafe :: forall m a. (MonadIO m, Storable a) => Array a -> Int -> m a
428getIndexUnsafe :: forall m a. (MonadIO m, Storable a) => Array a -> Int -> m a
423getIndexUnsafe Array {..} i =
429getIndexUnsafe Array {..} i =
424− unsafeWithForeignPtrM aStart $ \p -> do
430+ unsafeWithForeignPtrM aStart $ \ptr -> do
425 let elemSize = sizeOf (undefined :: a)
431 let elemSize = sizeOf (undefined :: a)
426− elemOff = p `plusPtr` (elemSize * i)
432+ elemPtr = ptr `plusPtr` (elemSize * i)
427− assert (i >= 0 && elemOff `plusPtr` elemSize <= aEnd)
433+ assert (i >= 0 && elemPtr `plusPtr` elemSize <= aEnd) (return ())
428− (return ())
429− liftIO $ peek elemOff
434+ liftIO $ peek elemPtr
430
435
431-------------------------------------------------------------------------------
436-------------------------------------------------------------------------------
432-- Size
437-- Size