module Data.StorableVector.Stream (
   from, fromList,
   to, toList,
   ) where

import qualified Data.StorableVector as SV
import Foreign.Storable (Storable, )

import qualified Data.Stream as G

import Data.Maybe.HT (toMaybe, )


from :: Storable a =>
   Int -> G.Stream a -> SV.Vector a
from size (G.Stream f s) =
   fst $
   SV.unfoldrN size
      (let go s0 =
             case f s0 of
                G.Yield a s1 -> Just (a, s1)
                G.Skip s1 -> go s1
                G.Done -> Nothing
       in  go)
      s

{-# INLINE fromList #-}
fromList :: Storable a =>
   Int -> [a] -> SV.Vector a
fromList size =
   from size . G.stream


to :: Storable a =>
   SV.Vector a -> G.Stream a
to xs =
   G.unfoldr
      (\i ->
         toMaybe (i < SV.length xs) (SV.index xs i, succ i))
   0

{-# INLINE toList #-}
toList :: Storable a =>
   SV.Vector a -> [a]
toList = G.unstream . to