{-|
General utilities for immutable vectors.
-}
{-# LANGUAGE RankNTypes #-}
module Control.Foldl.Util.Vector where

import Data.Vector.Generic
import Control.Monad.ST
import qualified Data.Vector.Generic.Mutable as M
import qualified Control.Foldl.Util.MVector as M


{-|
>>> fromReverseListN 3 [1,2,3] :: Data.Vector.Vector Int
[3,2,1]
-}
{-# INLINE fromReverseListN #-}
fromReverseListN :: Vector v a => Int -> [a] -> v a
fromReverseListN :: forall (v :: * -> *) a. Vector v a => Int -> [a] -> v a
fromReverseListN Int
size [a]
list =
  forall (v :: * -> *) a.
Vector v a =>
Int -> (forall s. Mutable v s a -> ST s ()) -> v a
initialized Int
size forall a b. (a -> b) -> a -> b
$ \ Mutable v s a
mv -> forall (v :: * -> * -> *) a s.
MVector v a =>
v s a -> Int -> [a] -> ST s ()
M.writeListInReverseOrderStartingFrom Mutable v s a
mv (forall a. Enum a => a -> a
pred Int
size) [a]
list

{-# INLINE initialized #-}
initialized :: Vector v a => Int -> (forall s. Mutable v s a -> ST s ()) -> v a
initialized :: forall (v :: * -> *) a.
Vector v a =>
Int -> (forall s. Mutable v s a -> ST s ()) -> v a
initialized Int
size forall s. Mutable v s a -> ST s ()
initialize = forall a. (forall s. ST s a) -> a
runST forall a b. (a -> b) -> a -> b
$ do
  Mutable v s a
mv <- forall (m :: * -> *) (v :: * -> * -> *) a.
(PrimMonad m, MVector v a) =>
Int -> m (v (PrimState m) a)
M.unsafeNew Int
size
  forall s. Mutable v s a -> ST s ()
initialize Mutable v s a
mv
  forall (m :: * -> *) (v :: * -> *) a.
(PrimMonad m, Vector v a) =>
Mutable v (PrimState m) a -> m (v a)
unsafeFreeze Mutable v s a
mv