{-# LANGUAGE BangPatterns #-}
module Data.RangeMin.Common.Unf.Slice where

import Control.Monad
-- import Control.Monad.ST
-- import Control.Monad.Primitive
-- import qualified Data.Vector.Generic as G
-- import qualified Data.Vector.Generic.Mutable as GM
import Data.RangeMin.Common.Vector
import Data.RangeMin.Common.Unf

{-# INLINE buildRowsUnf #-}
buildRowsUnf :: Vector v a => Int -> Int -> Maybe a -> Unf a -> (Int -> v a -> Unf a) -> v a
buildRowsUnf !rows !cols def firstRow sucRow = inlineCreate $ do
	!dest <- maybe (new (rows * cols)) (newWith (rows * cols)) def
	row0 <- unfoldInto dest firstRow
	let go !i !prev = when (i < rows) $ let
		!next = sliceM (cols * i) cols dest
		in go (i+1) =<< unfoldInto next (sucRow i prev)
	go 1 row0
	return dest