{-# OPTIONS_GHC -fno-warn-orphans #-}
--
-- Module      : StorableVector
-- Copyright   : (c) The University of Glasgow 2001,
--               (c) David Roundy 2003-2005,
--               (c) Simon Marlow 2005
--               (c) Don Stewart 2005-2006
--               (c) Bjorn Bringert 2006
--               (c) Spencer Janssen 2006
--               (c) Henning Thielemann 2008-2017
--
--
-- License     : BSD-style
--
-- Maintainer  : Henning Thielemann
-- Stability   : experimental
-- Portability : portable, requires ffi and cpp
-- Tested with : GHC 6.4.1 and Hugs March 2005
--

--
-- | A time and space-efficient implementation of vectors using
-- packed arrays, suitable for high performance use, both in terms
-- of large data quantities, or high speed requirements. Vectors
-- are encoded as strict arrays, held in a 'ForeignPtr',
-- and can be passed between C and Haskell with little effort.
--
-- This module is intended to be imported @qualified@, to avoid name
-- clashes with "Prelude" functions.  eg.
--
-- > import qualified Data.StorableVector as V
--
-- Original GHC implementation by Bryan O\'Sullivan. Rewritten to use
-- UArray by Simon Marlow. Rewritten to support slices and use
-- ForeignPtr by David Roundy. Polished and extended by Don Stewart.
-- Generalized to any Storable value by Spencer Janssen.
-- Chunky lazy stream, also with chunk pattern control,
-- mutable access in ST monad, Builder monoid by Henning Thieleman.

module Data.StorableVector (

        -- * The @Vector@ type
        Vector,

        -- * Introducing and eliminating 'Vector's
        empty,
        singleton,
        pack,
        unpack,
        packN,
        packWith,
        unpackWith,

        -- * Basic interface
        cons,
        snoc,
        append,
        head,
        last,
        tail,
        init,
        null,
        length,
        viewL,
        viewR,
        switchL,
        switchR,

        -- * Transforming 'Vector's
        map,
        mapIndexed,
        reverse,
        intersperse,
        transpose,

        -- * Reducing 'Vector's (folds)
        foldl,
        foldl',
        foldl1,
        foldl1',
        foldr,
        foldr1,

        -- ** Special folds
        concat,
        concatMap,
        foldMap,
        monoidConcatMap,
        any,
        all,
        maximum,
        minimum,

        -- * Building 'Vector's
        -- ** Scans
        scanl,
        scanl1,
        scanr,
        scanr1,

        -- ** Accumulating maps
        mapAccumL,
        mapAccumR,
        crochetL,
        crochetLResult,

        -- ** Unfolding 'Vector's
        replicate,
        iterateN,
        unfoldr,
        unfoldrN,
        unfoldrResultN,
        sample,

        -- * Substrings

        -- ** Breaking strings
        take,
        drop,
        splitAt,
        takeWhile,
        dropWhile,
        span,
        spanEnd,
        break,
        breakEnd,
        group,
        groupBy,
        inits,
        tails,

        -- ** Breaking into many substrings
        split,
        splitWith,
        tokens,
        sliceVertical,

        -- ** Joining strings
        join,

        -- * Predicates
        isPrefixOf,
        isSuffixOf,

        -- * Searching 'Vector's

        -- ** Searching by equality
        elem,
        notElem,

        -- ** Searching with a predicate
        find,
        filter,

        -- * Indexing 'Vector's
        index,
        elemIndex,
        elemIndices,
        elemIndexEnd,
        findIndex,
        findIndices,
        count,
        findIndexOrEnd,

        -- * Zipping and unzipping 'Vector's
        zip,
        zipWith,
        zipWith3,
        zipWith4,
        unzip,
        copy,

        -- * Interleaved 'Vector's
        sieve,
        deinterleave,
        interleave,

        -- * IO
        poke,
        peek,
        hGet,
        hPut,
        readFile,
        writeFile,
        appendFile,

  ) where

import Data.StorableVector.Base

import qualified System.Unsafe as Unsafe

import Control.Exception        (assert, bracket, )
import System.IO                (IO, FilePath, Handle, IOMode(..),
                                 openBinaryFile, hClose, hFileSize,
                                 hGetBuf, hPutBuf, )

import qualified Foreign.Storable as St
import Foreign.ForeignPtr       (ForeignPtr, withForeignPtr, )
import Foreign.Marshal.Array    (advancePtr, copyArray, withArray, )
import Foreign.Ptr              (Ptr, minusPtr, )
import Foreign.Storable         (Storable(sizeOf, alignment,
                                          pokeElemOff, peekElemOff), )

import qualified Test.QuickCheck as QC

import qualified Control.Monad.Trans.Cont as MC
import Control.Monad            (mplus, guard, when, liftM2, liftM3, liftM4,
                                 mapM, sequence_, return, (=<<), (>>=), (>>), )
import Data.Functor             (fmap, )
import Data.Monoid              (Monoid, mempty, mappend, mconcat, )
import Data.Semigroup           (Semigroup, (<>), )

import qualified Data.List as List
import qualified Data.List.HT as ListHT
import qualified Data.Strictness.HT as Strict
import Text.Show (show, )
import Data.Function (flip, id, const, ($), (.), )
import Data.List (and, (++), )
import Data.Tuple.HT (mapSnd, )
import Data.Tuple (uncurry, curry, fst, snd, )
import Data.Either (Either(Left, Right), )
import Data.Maybe.HT (toMaybe, )
import Data.Maybe (Maybe(Just, Nothing), maybe, fromMaybe, isJust, )
import Data.Bool (Bool(False, True), not, otherwise, (&&), (||), )
import Data.Ord (Ord, min, max, (<), (<=), (>), (>=), )
import Data.Eq (Eq, (==), (/=), )

import qualified Prelude as P
import Prelude
          (String, Int, (*), (-), (+), div, mod,
           fromIntegral, error, undefined, )


-- -----------------------------------------------------------------------------

instance (Storable a, Eq a) => Eq (Vector a) where
    == :: Vector a -> Vector a -> Bool
(==) = forall a. (Storable a, Eq a) => Vector a -> Vector a -> Bool
equal

instance (Storable a) => Semigroup (Vector a) where
    <> :: Vector a -> Vector a -> Vector a
(<>) = forall a. Storable a => Vector a -> Vector a -> Vector a
append

instance (Storable a) => Monoid (Vector a) where
    mempty :: Vector a
mempty  = forall a. Storable a => Vector a
empty
    mappend :: Vector a -> Vector a -> Vector a
mappend = forall a. Storable a => Vector a -> Vector a -> Vector a
append
    mconcat :: [Vector a] -> Vector a
mconcat = forall a. Storable a => [Vector a] -> Vector a
concat

instance (Storable a, QC.Arbitrary a) => QC.Arbitrary (Vector a) where
    arbitrary :: Gen (Vector a)
arbitrary = forall a. Storable a => [a] -> Vector a
pack forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` forall a. Arbitrary a => Gen a
QC.arbitrary

-- | /O(n)/ Equality on the 'Vector' type.
equal :: (Storable a, Eq a) => Vector a -> Vector a -> Bool
equal :: forall a. (Storable a, Eq a) => Vector a -> Vector a -> Bool
equal Vector a
a Vector a
b =
   forall a. IO a -> a
Unsafe.performIO forall a b. (a -> b) -> a -> b
$
   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr Vector a
a forall a b. (a -> b) -> a -> b
$ \Ptr a
paf Int
la ->
   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr Vector a
b forall a b. (a -> b) -> a -> b
$ \Ptr a
pbf Int
lb ->
    if Int
la forall a. Eq a => a -> a -> Bool
/= Int
lb
      then
        forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
      else
        if Ptr a
paf forall a. Eq a => a -> a -> Bool
== Ptr a
pbf
          then forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
          else
            let go :: Ptr a -> Ptr a -> Int -> IO Bool
go = forall a b c x. (a -> b -> c -> x) -> a -> b -> c -> x
Strict.arguments3 forall a b. (a -> b) -> a -> b
$ \Ptr a
p Ptr a
q Int
l ->
                   if Int
lforall a. Eq a => a -> a -> Bool
==Int
0
                     then forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
                     else
                       do a
x <- forall a. Storable a => Ptr a -> IO a
St.peek Ptr a
p
                          a
y <- forall a. Storable a => Ptr a -> IO a
St.peek Ptr a
q
                          if a
xforall a. Eq a => a -> a -> Bool
==a
y
                            then Ptr a -> Ptr a -> Int -> IO Bool
go (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
p) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
q) (Int
lforall a. Num a => a -> a -> a
-Int
1)
                            else forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
            in  Ptr a -> Ptr a -> Int -> IO Bool
go Ptr a
paf Ptr a
pbf Int
la
{-# INLINE equal #-}

-- -----------------------------------------------------------------------------
-- Introducing and eliminating 'Vector's

-- | /O(1)/ The empty 'Vector'
empty :: (Storable a) => Vector a
empty :: forall a. Storable a => Vector a
empty = forall a. Storable a => Int -> (Ptr a -> IO ()) -> Vector a
unsafeCreate Int
0 forall a b. (a -> b) -> a -> b
$ forall a b. a -> b -> a
const forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a. Monad m => a -> m a
return ()
{-# NOINLINE empty #-}

-- | /O(1)/ Construct a 'Vector' containing a single element
singleton :: (Storable a) => a -> Vector a
singleton :: forall a. Storable a => a -> Vector a
singleton a
c = forall a. Storable a => Int -> (Ptr a -> IO ()) -> Vector a
unsafeCreate Int
1 forall a b. (a -> b) -> a -> b
$ \Ptr a
p -> forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr a
p a
c
{-# INLINE singleton #-}

-- | /O(n)/ Convert a '[a]' into a 'Vector a'.
--
pack :: (Storable a) => [a] -> Vector a
pack :: forall a. Storable a => [a] -> Vector a
pack [a]
str = forall a. Storable a => Int -> (Ptr a -> IO ()) -> Vector a
unsafeCreate (forall (t :: * -> *) a. Foldable t => t a -> Int
P.length [a]
str) forall a b. (a -> b) -> a -> b
$ \Ptr a
p -> Ptr a -> [a] -> IO ()
go Ptr a
p [a]
str
    where
      go :: Ptr a -> [a] -> IO ()
go = forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \Ptr a
p ->
        forall b a. b -> (a -> [a] -> b) -> [a] -> b
ListHT.switchL
           (forall (m :: * -> *) a. Monad m => a -> m a
return ())
           (\a
x [a]
xs -> forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr a
p a
x forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Ptr a -> [a] -> IO ()
go (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
p) [a]
xs)

-- | /O(n)/ Convert first @n@ elements of a '[a]' into a 'Vector a'.
--
packN :: (Storable a) => Int -> [a] -> (Vector a, [a])
packN :: forall a. Storable a => Int -> [a] -> (Vector a, [a])
packN Int
n =
   forall b c a. (b -> c) -> (a, b) -> (a, c)
mapSnd (forall a. a -> Maybe a -> a
fromMaybe []) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN Int
n forall a. [a] -> Maybe (a, [a])
ListHT.viewL

-- | /O(n)/ Converts a 'Vector a' to a '[a]'.
unpack :: (Storable a) => Vector a -> [a]
unpack :: forall a. Storable a => Vector a -> [a]
unpack = forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr (:) []
{-# INLINE unpack #-}

------------------------------------------------------------------------

-- | /O(n)/ Convert a list into a 'Vector' using a conversion function
packWith :: (Storable b) => (a -> b) -> [a] -> Vector b
packWith :: forall b a. Storable b => (a -> b) -> [a] -> Vector b
packWith a -> b
k [a]
str = forall a. Storable a => Int -> (Ptr a -> IO ()) -> Vector a
unsafeCreate (forall (t :: * -> *) a. Foldable t => t a -> Int
P.length [a]
str) forall a b. (a -> b) -> a -> b
$ \Ptr b
p -> Ptr b -> [a] -> IO ()
go Ptr b
p [a]
str
    where
      go :: Ptr b -> [a] -> IO ()
go = forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \Ptr b
p ->
        forall b a. b -> (a -> [a] -> b) -> [a] -> b
ListHT.switchL
           (forall (m :: * -> *) a. Monad m => a -> m a
return ())
           (\a
x [a]
xs -> forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr b
p (a -> b
k a
x) forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Ptr b -> [a] -> IO ()
go (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr b
p) [a]
xs)
                          -- less space than pokeElemOff
{-# INLINE packWith #-}

{-
*Data.StorableVector> List.take 10 $ unpackWith id $ pack [0..10000000::Int]
[0,1,2,3,4,5,6,7,8,9]
(19.18 secs, 2327851592 bytes)
-}
-- | /O(n)/ Convert a 'Vector' into a list using a conversion function
unpackWith :: (Storable a) => (a -> b) -> Vector a -> [b]
unpackWith :: forall a b. Storable a => (a -> b) -> Vector a -> [b]
unpackWith a -> b
f = forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr ((:) forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> b
f) []
{-# INLINE unpackWith #-}

{-
That's too inefficient, since it builds the list from back to front,
that is, in a too strict manner.

-- | /O(n)/ Convert a 'Vector' into a list using a conversion function
unpackWith :: (Storable a) => (a -> b) -> Vector a -> [b]
unpackWith _ (SV _  _ 0) = []
unpackWith k v@(SV ps s l) = inlinePerformIO $ withStartPtr v $ \p ->
        go p (l - 1) []
    where
        STRICT3(go)
        go p 0 acc = St.peek p          >>= \e -> return (k e : acc)
        go p n acc = peekElemOff p n >>= \e -> go p (n-1) (k e : acc)
{-# INLINE unpackWith #-}


*Data.StorableVector> List.take 10 $ unpack $ pack [0..10000000::Int]
[0,1,2,3,4,5,6,7,8,9]
(18.57 secs, 2323959948 bytes)
*Data.StorableVector> unpack $ take 10 $ pack [0..10000000::Int]
[0,1,2,3,4,5,6,7,8,9]
(18.40 secs, 2324002120 bytes)
*Data.StorableVector> List.take 10 $ unpackWith id $ pack [0..10000000::Int]
Interrupted.
-}

-- ---------------------------------------------------------------------
-- Basic interface

-- | /O(1)/ Test whether a 'Vector' is empty.
null :: Vector a -> Bool
null :: forall a. Vector a -> Bool
null (SV ForeignPtr a
_ Int
_ Int
l) = forall a. (?callStack::CallStack) => Bool -> a -> a
assert (Int
l forall a. Ord a => a -> a -> Bool
>= Int
0) forall a b. (a -> b) -> a -> b
$ Int
l forall a. Ord a => a -> a -> Bool
<= Int
0
{-# INLINE null #-}

-- ---------------------------------------------------------------------
-- | /O(1)/ 'length' returns the length of a 'Vector' as an 'Int'.
length :: Vector a -> Int
length :: forall a. Vector a -> Int
length (SV ForeignPtr a
_ Int
_ Int
l) = forall a. (?callStack::CallStack) => Bool -> a -> a
assert (Int
l forall a. Ord a => a -> a -> Bool
>= Int
0) forall a b. (a -> b) -> a -> b
$ Int
l

--
-- length/loop fusion. When taking the length of any fuseable loop,
-- rewrite it as a foldl', and thus avoid allocating the result buffer
-- worth around 10% in speed testing.
--

{-# INLINE [1] length #-}

------------------------------------------------------------------------

-- | /O(n)/ 'cons' is analogous to (:) for lists, but of different
-- complexity, as it requires a memcpy.
cons :: (Storable a) => a -> Vector a -> Vector a
cons :: forall a. Storable a => a -> Vector a -> Vector a
cons a
c Vector a
v =
   forall a b. Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr Vector a
v forall a b. (a -> b) -> a -> b
$ \Ptr a
f Int
l ->
   forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create (Int
l forall a. Num a => a -> a -> a
+ Int
1) forall a b. (a -> b) -> a -> b
$ \Ptr a
p -> do
      forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr a
p a
c
      forall a. Storable a => Ptr a -> Ptr a -> Int -> IO ()
copyArray (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
p) Ptr a
f (forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
l)
{-# INLINE cons #-}

-- | /O(n)/ Append an element to the end of a 'Vector'
snoc :: (Storable a) => Vector a -> a -> Vector a
snoc :: forall a. Storable a => Vector a -> a -> Vector a
snoc Vector a
v a
c =
   forall a b. Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr Vector a
v forall a b. (a -> b) -> a -> b
$ \Ptr a
f Int
l ->
   forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create (Int
l forall a. Num a => a -> a -> a
+ Int
1) forall a b. (a -> b) -> a -> b
$ \Ptr a
p -> do
      forall a. Storable a => Ptr a -> Ptr a -> Int -> IO ()
copyArray Ptr a
p Ptr a
f Int
l
      forall a. Storable a => Ptr a -> Int -> a -> IO ()
pokeElemOff Ptr a
p Int
l a
c
{-# INLINE snoc #-}

-- | /O(1)/ Extract the first element of a 'Vector', which must be non-empty.
-- It is a checked error to pass an empty 'Vector'.
head :: (Storable a) => Vector a -> a
head :: forall a. Storable a => Vector a -> a
head =
   forall a b.
String -> (ForeignPtr a -> Int -> Int -> b) -> Vector a -> b
withNonEmptyVector String
"head" forall a b. (a -> b) -> a -> b
$ \ ForeignPtr a
p Int
s Int
_l -> forall a. Storable a => ForeignPtr a -> Int -> a
foreignPeek ForeignPtr a
p Int
s
{-# INLINE head #-}

-- | /O(1)/ Extract the elements after the head of a 'Vector', which must be non-empty.
-- It is a checked error to pass an empty 'Vector'.
tail :: (Storable a) => Vector a -> Vector a
tail :: forall a. Storable a => Vector a -> Vector a
tail =
   forall a b.
String -> (ForeignPtr a -> Int -> Int -> b) -> Vector a -> b
withNonEmptyVector String
"tail" forall a b. (a -> b) -> a -> b
$ \ ForeignPtr a
p Int
s Int
l -> forall a. ForeignPtr a -> Int -> Int -> Vector a
SV ForeignPtr a
p (Int
sforall a. Num a => a -> a -> a
+Int
1) (Int
lforall a. Num a => a -> a -> a
-Int
1)
{-# INLINE tail #-}

laxTail :: (Storable a) => Vector a -> Vector a
laxTail :: forall a. Storable a => Vector a -> Vector a
laxTail v :: Vector a
v@(SV ForeignPtr a
fp Int
s Int
l) =
   if Int
lforall a. Ord a => a -> a -> Bool
<=Int
0
     then Vector a
v
     else forall a. ForeignPtr a -> Int -> Int -> Vector a
SV ForeignPtr a
fp (Int
sforall a. Num a => a -> a -> a
+Int
1) (Int
lforall a. Num a => a -> a -> a
-Int
1)
{-# INLINE laxTail #-}

-- | /O(1)/ Extract the last element of a 'Vector', which must be finite and non-empty.
-- It is a checked error to pass an empty 'Vector'.
last :: (Storable a) => Vector a -> a
last :: forall a. Storable a => Vector a -> a
last =
   forall a b.
String -> (ForeignPtr a -> Int -> Int -> b) -> Vector a -> b
withNonEmptyVector String
"last" forall a b. (a -> b) -> a -> b
$ \ ForeignPtr a
p Int
s Int
l -> forall a. Storable a => ForeignPtr a -> Int -> a
foreignPeek ForeignPtr a
p (Int
sforall a. Num a => a -> a -> a
+Int
lforall a. Num a => a -> a -> a
-Int
1)
{-# INLINE last #-}

-- | /O(1)/ Return all the elements of a 'Vector' except the last one.
-- It is a checked error to pass an empty 'Vector'.
init :: Vector a -> Vector a
init :: forall a. Vector a -> Vector a
init =
   forall a b.
String -> (ForeignPtr a -> Int -> Int -> b) -> Vector a -> b
withNonEmptyVector String
"init" forall a b. (a -> b) -> a -> b
$ \ ForeignPtr a
p Int
s Int
l -> forall a. ForeignPtr a -> Int -> Int -> Vector a
SV ForeignPtr a
p Int
s (Int
lforall a. Num a => a -> a -> a
-Int
1)
{-# INLINE init #-}

-- | /O(n)/ Append two Vectors
append :: (Storable a) => Vector a -> Vector a -> Vector a
append :: forall a. Storable a => Vector a -> Vector a -> Vector a
append Vector a
xs Vector a
ys = forall a. Storable a => [Vector a] -> Vector a
concat [Vector a
xs,Vector a
ys]
{-# INLINE append #-}

-- ---------------------------------------------------------------------
-- Transformations

-- | /O(n)/ 'map' @f xs@ is the 'Vector' obtained by applying @f@ to each
-- element of @xs@.
map :: (Storable a, Storable b) => (a -> b) -> Vector a -> Vector b
map :: forall a b.
(Storable a, Storable b) =>
(a -> b) -> Vector a -> Vector b
map a -> b
f Vector a
v =
   forall a b. Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr Vector a
v forall a b. (a -> b) -> a -> b
$ \Ptr a
a Int
len ->
   forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create Int
len forall a b. (a -> b) -> a -> b
$ \Ptr b
p ->
      let go :: Int -> Ptr a -> Ptr b -> IO ()
go = forall a b c x. (a -> b -> c -> x) -> a -> b -> c -> x
Strict.arguments3 forall a b. (a -> b) -> a -> b
$
             \ Int
n Ptr a
p1 Ptr b
p2 ->
               forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
nforall a. Ord a => a -> a -> Bool
>Int
0) forall a b. (a -> b) -> a -> b
$
                 do forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr b
p2 forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> b
f forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< forall a. Storable a => Ptr a -> IO a
St.peek Ptr a
p1
                    Int -> Ptr a -> Ptr b -> IO ()
go (Int
nforall a. Num a => a -> a -> a
-Int
1) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
p1) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr b
p2)
      in  Int -> Ptr a -> Ptr b -> IO ()
go Int
len Ptr a
a Ptr b
p
{-# INLINE map #-}

{-
mapByIndex :: (Storable a, Storable b) => (a -> b) -> Vector a -> Vector b
mapByIndex f v = inlinePerformIO $ withStartPtr v $ \a len ->
    create len $ \p2 ->
       let go = Strict.arguments1 $ \ n ->
              when (n<len) $
                do pokeElemOff p2 n . f =<< peekElemOff a n
                   go (n+1)
       in  go 0
-}

-- | /O(n)/ 'reverse' @xs@ efficiently returns the elements of @xs@ in reverse order.
reverse :: (Storable a) => Vector a -> Vector a
reverse :: forall a. Storable a => Vector a -> Vector a
reverse Vector a
v =
   forall a b. Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr Vector a
v forall a b. (a -> b) -> a -> b
$ \Ptr a
f Int
l ->
   forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create Int
l forall a b. (a -> b) -> a -> b
$ \Ptr a
p ->
   forall (t :: * -> *) (m :: * -> *) a.
(Foldable t, Monad m) =>
t (m a) -> m ()
sequence_ [forall a. Storable a => Ptr a -> Int -> IO a
peekElemOff Ptr a
f Int
i forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. Storable a => Ptr a -> Int -> a -> IO ()
pokeElemOff Ptr a
p (Int
l forall a. Num a => a -> a -> a
- Int
i forall a. Num a => a -> a -> a
- Int
1)
                 | Int
i <- [Int
0 .. Int
l forall a. Num a => a -> a -> a
- Int
1]]

-- | /O(n)/ The 'intersperse' function takes a element and a
-- 'Vector' and \`intersperses\' that element between the elements of
-- the 'Vector'.  It is analogous to the intersperse function on
-- Lists.
intersperse :: (Storable a) => a -> Vector a -> Vector a
intersperse :: forall a. Storable a => a -> Vector a -> Vector a
intersperse a
c = forall a. Storable a => [a] -> Vector a
pack forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. a -> [a] -> [a]
List.intersperse a
c forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Storable a => Vector a -> [a]
unpack

-- | The 'transpose' function transposes the rows and columns of its
-- 'Vector' argument.
transpose :: (Storable a) => [Vector a] -> [Vector a]
transpose :: forall a. Storable a => [Vector a] -> [Vector a]
transpose [Vector a]
ps = forall a b. (a -> b) -> [a] -> [b]
P.map forall a. Storable a => [a] -> Vector a
pack (forall a. [[a]] -> [[a]]
List.transpose (forall a b. (a -> b) -> [a] -> [b]
P.map forall a. Storable a => Vector a -> [a]
unpack [Vector a]
ps))

-- ---------------------------------------------------------------------
-- Reducing 'Vector's

-- | 'foldl', applied to a binary operator, a starting value (typically
-- the left-identity of the operator), and a Vector, reduces the
-- 'Vector' using the binary operator, from left to right.
foldl :: (Storable a) => (b -> a -> b) -> b -> Vector a -> b
foldl :: forall a b. Storable a => (b -> a -> b) -> b -> Vector a -> b
foldl b -> a -> b
f b
v Vector a
xs =
   forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr (\a
x b -> b
k b
acc -> b -> b
k (b -> a -> b
f b
acc a
x)) forall a. a -> a
id Vector a
xs b
v
{-# INLINE foldl #-}

-- | 'foldl\'' is like 'foldl', but strict in the accumulator.
foldl' :: (Storable a) => (b -> a -> b) -> b -> Vector a -> b
foldl' :: forall a b. Storable a => (b -> a -> b) -> b -> Vector a -> b
foldl' b -> a -> b
f b
b Vector a
v =
   forall a. IO a -> a
Unsafe.performIO forall a b. (a -> b) -> a -> b
$ forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr Vector a
v forall a b. (a -> b) -> a -> b
$ \Ptr a
ptr Int
l ->
      let q :: Ptr a
q  = Ptr a
ptr forall a. Storable a => Ptr a -> Int -> Ptr a
`advancePtr` Int
l
          go :: Ptr a -> b -> IO b
go = forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \Ptr a
p b
z ->
             if Ptr a
p forall a. Eq a => a -> a -> Bool
== Ptr a
q
               then forall (m :: * -> *) a. Monad m => a -> m a
return b
z
               else Ptr a -> b -> IO b
go (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
p) forall b c a. (b -> c) -> (a -> b) -> a -> c
. b -> a -> b
f b
z forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< forall a. Storable a => Ptr a -> IO a
St.peek Ptr a
p
      in  Ptr a -> b -> IO b
go Ptr a
ptr b
b
{-# INLINE foldl' #-}

-- | 'foldr', applied to a binary operator, a starting value
-- (typically the right-identity of the operator), and a 'Vector',
-- reduces the 'Vector' using the binary operator, from right to left.
-- However, it is not the same as 'foldl' applied to the reversed vector.
-- Actually 'foldr' starts processing with the first element,
-- and thus can be used for efficiently building a singly linked list
-- by @foldr (:) [] vec@.
-- Unfortunately 'foldr' is quite slow for low-level loops,
-- since GHC (up to 6.12.1) cannot detect the loop.
foldr :: (Storable a) => (a -> b -> b) -> b -> Vector a -> b
foldr :: forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr = forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldrByLoop
{-# INLINE foldr #-}

{-
*Data.StorableVector> List.length $ foldrBySwitch (:) [] $ replicate 1000000 'a'
1000000
(11.29 secs, 1183476300 bytes)
*Data.StorableVector> List.length $ foldrByIO (:) [] $ replicate 1000000 'a'
1000000
(7.86 secs, 1033901140 bytes)
*Data.StorableVector> List.length $ foldrByIndex (:) [] $ replicate 1000000 'a'
1000000
(7.86 secs, 914340420 bytes)
*Data.StorableVector> List.length $ foldrByLoop (:) [] $ replicate 1000000 'a'
1000000
(6.38 secs, 815355460 bytes)
-}
{-
We cannot simply increment the pointer,
since ForeignPtr cannot be incremented.
We also cannot convert from ForeignPtr to Ptr
and increment that instead,
because we need to keep the reference to ForeignPtr,
otherwise memory might be freed.
We can also not perform loop entirely in strict IO,
since this eat up the stack quickly
and 'foldr' might be used to build a list lazily.
-}
foldrByLoop :: (Storable a) => (a -> b -> b) -> b -> Vector a -> b
foldrByLoop :: forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldrByLoop a -> b -> b
f b
z (SV ForeignPtr a
fp Int
s Int
l) =
   let end :: Int
end = Int
sforall a. Num a => a -> a -> a
+Int
l
       go :: Int -> b
go = forall a x. (a -> x) -> a -> x
Strict.arguments1 forall a b. (a -> b) -> a -> b
$ \Int
k ->
          if Int
kforall a. Ord a => a -> a -> Bool
<Int
end
            then a -> b -> b
f (forall a. Storable a => ForeignPtr a -> Int -> a
foreignPeek ForeignPtr a
fp Int
k) (Int -> b
go (Int -> Int
succ Int
k))
            else b
z
   in  Int -> b
go Int
s
{-# INLINE foldrByLoop #-}

{-
foldrByIO :: (Storable a) => (a -> b -> b) -> b -> Vector a -> b
foldrByIO f z v@(SV fp _ _) =
   unsafeWithStartPtr v $
   let go = Strict.arguments2 $ \p l ->
          Unsafe.interleaveIO $
          if l>0
            then liftM2 f (St.peek p) (go (incPtr p) (pred l))
            else touchForeignPtr fp >> return z
   in  go
{-# INLINE foldrByIO #-}

foldrByIndex :: (Storable a) => (a -> b -> b) -> b -> Vector a -> b
foldrByIndex k z xs =
   let recourse n =
          if n < length xs
            then k (unsafeIndex xs n) (recourse (succ n))
            else z
   in  recourse 0
{-# INLINE foldrByIndex #-}

{-
This implementation is a bit inefficient,
since switchL creates a new Vector structure
instead of just incrementing an index.
-}
foldrBySwitch :: (Storable a) => (a -> b -> b) -> b -> Vector a -> b
foldrBySwitch k z =
   let recourse = switchL z (\h t -> k h (recourse t))
   in  recourse
{-# INLINE foldrBySwitch #-}
-}


-- | 'foldl1' is a variant of 'foldl' that has no starting value
-- argument, and thus must be applied to non-empty 'Vector's.
-- It is a checked error to pass an empty 'Vector'.
foldl1 :: (Storable a) => (a -> a -> a) -> Vector a -> a
foldl1 :: forall a. Storable a => (a -> a -> a) -> Vector a -> a
foldl1 a -> a -> a
f =
   forall a b.
Storable a =>
b -> (a -> Vector a -> b) -> Vector a -> b
switchL
      (forall a. String -> a
errorEmpty String
"foldl1")
      (forall a b. Storable a => (b -> a -> b) -> b -> Vector a -> b
foldl a -> a -> a
f)
{-# INLINE foldl1 #-}

-- | 'foldl1\'' is like 'foldl1', but strict in the accumulator.
-- It is a checked error to pass an empty 'Vector'.
foldl1' :: (Storable a) => (a -> a -> a) -> Vector a -> a
foldl1' :: forall a. Storable a => (a -> a -> a) -> Vector a -> a
foldl1' a -> a -> a
f =
   forall a b.
Storable a =>
b -> (a -> Vector a -> b) -> Vector a -> b
switchL
      (forall a. String -> a
errorEmpty String
"foldl1'")
      (forall a b. Storable a => (b -> a -> b) -> b -> Vector a -> b
foldl' a -> a -> a
f)
{-# INLINE foldl1' #-}

-- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
-- and thus must be applied to non-empty 'Vector's
-- It is a checked error to pass an empty 'Vector'.
foldr1 :: (Storable a) => (a -> a -> a) -> Vector a -> a
foldr1 :: forall a. Storable a => (a -> a -> a) -> Vector a -> a
foldr1 a -> a -> a
f =
   forall a b.
Storable a =>
b -> (Vector a -> a -> b) -> Vector a -> b
switchR
      (forall a. String -> a
errorEmpty String
"foldr1")
      (forall a b c. (a -> b -> c) -> b -> a -> c
flip (forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr a -> a -> a
f))
{-# INLINE foldr1 #-}

-- ---------------------------------------------------------------------
-- Special folds

{-
We filter out empty chunks in order to benefit from the special cases
zero chunks and one chunk.
In the other cases the preprocessing does not help much.
-}
-- | /O(n)/ Concatenate a list of 'Vector's.
concat :: (Storable a) => [Vector a] -> Vector a
concat :: forall a. Storable a => [Vector a] -> Vector a
concat = forall a. Storable a => [Vector a] -> Vector a
concatCore forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. (a -> Bool) -> [a] -> [a]
List.filter (Bool -> Bool
not forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Vector a -> Bool
null)

concatCore :: (Storable a) => [Vector a] -> Vector a
concatCore :: forall a. Storable a => [Vector a] -> Vector a
concatCore []     = forall a. Storable a => Vector a
empty
concatCore [Vector a
ps]   = Vector a
ps
concatCore [Vector a]
xs     = forall a. Storable a => Int -> (Ptr a -> IO ()) -> Vector a
unsafeCreate Int
len forall a b. (a -> b) -> a -> b
$ \Ptr a
ptr -> Ptr a -> [Vector a] -> IO ()
go Ptr a
ptr [Vector a]
xs
  where len :: Int
len = forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
P.sum forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (a -> b) -> [a] -> [b]
P.map forall a. Vector a -> Int
length forall a b. (a -> b) -> a -> b
$ [Vector a]
xs
        go :: Ptr a -> [Vector a] -> IO ()
go =
          forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \Ptr a
ptr ->
             forall b a. b -> (a -> [a] -> b) -> [a] -> b
ListHT.switchL
                (forall (m :: * -> *) a. Monad m => a -> m a
return ())
                (\Vector a
v [Vector a]
ps -> do
                   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr Vector a
v forall a b. (a -> b) -> a -> b
$ forall a. Storable a => Ptr a -> Ptr a -> Int -> IO ()
copyArray Ptr a
ptr
                   Ptr a -> [Vector a] -> IO ()
go (Ptr a
ptr forall a. Storable a => Ptr a -> Int -> Ptr a
`advancePtr` forall a. Vector a -> Int
length Vector a
v) [Vector a]
ps)

-- | Map a function over a 'Vector' and concatenate the results
concatMap :: (Storable a, Storable b) => (a -> Vector b) -> Vector a -> Vector b
concatMap :: forall a b.
(Storable a, Storable b) =>
(a -> Vector b) -> Vector a -> Vector b
concatMap a -> Vector b
f = forall a. Storable a => [Vector a] -> Vector a
concat forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. Storable a => (a -> b) -> Vector a -> [b]
unpackWith a -> Vector b
f
{-# INLINE concatMap #-}

-- | This is like @mconcat . map f@,
-- but in many cases the result of @f@ will not be storable.
foldMap :: (Storable a, Monoid m) => (a -> m) -> Vector a -> m
foldMap :: forall a m. (Storable a, Monoid m) => (a -> m) -> Vector a -> m
foldMap a -> m
f = forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr (forall a. Monoid a => a -> a -> a
mappend forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> m
f) forall a. Monoid a => a
mempty
{-# INLINE foldMap #-}

{-# DEPRECATED monoidConcatMap "Use foldMap instead." #-}
monoidConcatMap :: (Storable a, Monoid m) => (a -> m) -> Vector a -> m
monoidConcatMap :: forall a m. (Storable a, Monoid m) => (a -> m) -> Vector a -> m
monoidConcatMap = forall a m. (Storable a, Monoid m) => (a -> m) -> Vector a -> m
foldMap
{-# INLINE monoidConcatMap #-}

-- | /O(n)/ Applied to a predicate and a 'Vector', 'any' determines if
-- any element of the 'Vector' satisfies the predicate.
any :: (Storable a) => (a -> Bool) -> Vector a -> Bool
any :: forall a. Storable a => (a -> Bool) -> Vector a -> Bool
any a -> Bool
f = forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr (Bool -> Bool -> Bool
(||) forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Bool
f) Bool
False
{-# INLINE any #-}

-- | /O(n)/ Applied to a predicate and a 'Vector', 'all' determines
-- if all elements of the 'Vector' satisfy the predicate.
all :: (Storable a) => (a -> Bool) -> Vector a -> Bool
all :: forall a. Storable a => (a -> Bool) -> Vector a -> Bool
all a -> Bool
f = forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr (Bool -> Bool -> Bool
(&&) forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Bool
f) Bool
True
{-# INLINE all #-}

------------------------------------------------------------------------

-- | /O(n)/ 'maximum' returns the maximum value from a 'Vector'
-- This function will fuse.
-- It is a checked error to pass an empty 'Vector'.
maximum :: (Storable a, Ord a) => Vector a -> a
maximum :: forall a. (Storable a, Ord a) => Vector a -> a
maximum = forall a. Storable a => (a -> a -> a) -> Vector a -> a
foldl1' forall a. Ord a => a -> a -> a
max

-- | /O(n)/ 'minimum' returns the minimum value from a 'Vector'
-- This function will fuse.
-- It is a checked error to pass an empty 'Vector'.
minimum :: (Storable a, Ord a) => Vector a -> a
minimum :: forall a. (Storable a, Ord a) => Vector a -> a
minimum = forall a. Storable a => (a -> a -> a) -> Vector a -> a
foldl1' forall a. Ord a => a -> a -> a
min

------------------------------------------------------------------------

switchL :: Storable a => b -> (a -> Vector a -> b) -> Vector a -> b
switchL :: forall a b.
Storable a =>
b -> (a -> Vector a -> b) -> Vector a -> b
switchL b
n a -> Vector a -> b
j Vector a
x =
   if forall a. Vector a -> Bool
null Vector a
x
     then b
n
     else a -> Vector a -> b
j (forall a. Storable a => Vector a -> a
unsafeHead Vector a
x) (forall a. Storable a => Vector a -> Vector a
unsafeTail Vector a
x)
{-# INLINE switchL #-}

switchR :: Storable a => b -> (Vector a -> a -> b) -> Vector a -> b
switchR :: forall a b.
Storable a =>
b -> (Vector a -> a -> b) -> Vector a -> b
switchR b
n Vector a -> a -> b
j Vector a
x =
   if forall a. Vector a -> Bool
null Vector a
x
     then b
n
     else Vector a -> a -> b
j (forall a. Storable a => Vector a -> Vector a
unsafeInit Vector a
x) (forall a. Storable a => Vector a -> a
unsafeLast Vector a
x)
{-# INLINE switchR #-}

viewL :: Storable a => Vector a -> Maybe (a, Vector a)
viewL :: forall a. Storable a => Vector a -> Maybe (a, Vector a)
viewL = forall a b.
Storable a =>
b -> (a -> Vector a -> b) -> Vector a -> b
switchL forall a. Maybe a
Nothing (forall a b c. ((a, b) -> c) -> a -> b -> c
curry forall a. a -> Maybe a
Just)
{-# INLINE viewL #-}

viewR :: Storable a => Vector a -> Maybe (Vector a, a)
viewR :: forall a. Storable a => Vector a -> Maybe (Vector a, a)
viewR = forall a b.
Storable a =>
b -> (Vector a -> a -> b) -> Vector a -> b
switchR forall a. Maybe a
Nothing (forall a b c. ((a, b) -> c) -> a -> b -> c
curry forall a. a -> Maybe a
Just)
{-# INLINE viewR #-}

-- | The 'mapAccumL' function behaves like a combination of 'map' and
-- 'foldl'; it applies a function to each element of a 'Vector',
-- passing an accumulating parameter from left to right, and returning a
-- final value of this accumulator together with the new list.
mapAccumL :: (Storable a, Storable b) => (acc -> a -> (acc, b)) -> acc -> Vector a -> (acc, Vector b)
mapAccumL :: forall a b acc.
(Storable a, Storable b) =>
(acc -> a -> (acc, b)) -> acc -> Vector a -> (acc, Vector b)
mapAccumL acc -> a -> (acc, b)
f acc
acc0 Vector a
as0 =
   let (Vector b
bs, Just (acc
acc2, Vector a
_)) =
          forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN (forall a. Vector a -> Int
length Vector a
as0)
             (\(acc
acc,Vector a
as) ->
                 forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap
                    (\(a
asHead,Vector a
asTail) ->
                        let (acc
acc1,b
b) = acc -> a -> (acc, b)
f acc
acc a
asHead
                        in  (b
b, (acc
acc1, Vector a
asTail)))
                    (forall a. Storable a => Vector a -> Maybe (a, Vector a)
viewL Vector a
as))
             (acc
acc0,Vector a
as0)
   in  (acc
acc2, Vector b
bs)
{-# INLINE mapAccumL #-}

-- | The 'mapAccumR' function behaves like a combination of 'map' and
-- 'foldr'; it applies a function to each element of a 'Vector',
-- passing an accumulating parameter from right to left, and returning a
-- final value of this accumulator together with the new 'Vector'.
mapAccumR :: (Storable a, Storable b) => (acc -> a -> (acc, b)) -> acc -> Vector a -> (acc, Vector b)
mapAccumR :: forall a b acc.
(Storable a, Storable b) =>
(acc -> a -> (acc, b)) -> acc -> Vector a -> (acc, Vector b)
mapAccumR acc -> a -> (acc, b)
f acc
acc0 Vector a
as0 =
   let (Vector b
bs, Just (acc
acc2, Vector a
_)) =
          forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldlN (forall a. Vector a -> Int
length Vector a
as0)
             (\(acc
acc,Vector a
as) ->
                 forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap
                    (\(Vector a
asInit,a
asLast) ->
                        let (acc
acc1,b
b) = acc -> a -> (acc, b)
f acc
acc a
asLast
                        in  (b
b, (acc
acc1, Vector a
asInit)))
                    (forall a. Storable a => Vector a -> Maybe (Vector a, a)
viewR Vector a
as))
             (acc
acc0,Vector a
as0)
   in  (acc
acc2, Vector b
bs)
{-# INLINE mapAccumR #-}

crochetLResult ::
   (Storable x, Storable y) =>
      (x -> acc -> Maybe (y, acc))
   -> acc
   -> Vector x
   -> (Vector y, Maybe acc)
crochetLResult :: forall x y acc.
(Storable x, Storable y) =>
(x -> acc -> Maybe (y, acc))
-> acc -> Vector x -> (Vector y, Maybe acc)
crochetLResult x -> acc -> Maybe (y, acc)
f acc
acc0 Vector x
x0 =
   forall b c a. (b -> c) -> (a, b) -> (a, c)
mapSnd (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b. (a, b) -> a
fst) forall a b. (a -> b) -> a -> b
$
   forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN
      (forall a. Vector a -> Int
length Vector x
x0)
      (\(acc
acc,Vector x
xt) ->
         do (x
x,Vector x
xs) <- forall a. Storable a => Vector a -> Maybe (a, Vector a)
viewL Vector x
xt
            (y
y,acc
acc') <- x -> acc -> Maybe (y, acc)
f x
x acc
acc
            forall (m :: * -> *) a. Monad m => a -> m a
return (y
y, (acc
acc',Vector x
xs)))
      (acc
acc0, Vector x
x0)
{-# INLINE crochetLResult #-}

crochetL ::
   (Storable x, Storable y) =>
      (x -> acc -> Maybe (y, acc))
   -> acc
   -> Vector x
   -> Vector y
crochetL :: forall x y acc.
(Storable x, Storable y) =>
(x -> acc -> Maybe (y, acc)) -> acc -> Vector x -> Vector y
crochetL x -> acc -> Maybe (y, acc)
f acc
acc = forall a b. (a, b) -> a
fst forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall x y acc.
(Storable x, Storable y) =>
(x -> acc -> Maybe (y, acc))
-> acc -> Vector x -> (Vector y, Maybe acc)
crochetLResult x -> acc -> Maybe (y, acc)
f acc
acc
{-# INLINE crochetL #-}


-- | /O(n)/ map functions, provided with the index at each position
mapIndexed :: (Storable a, Storable b) => (Int -> a -> b) -> Vector a -> Vector b
mapIndexed :: forall a b.
(Storable a, Storable b) =>
(Int -> a -> b) -> Vector a -> Vector b
mapIndexed Int -> a -> b
f = forall a b. (a, b) -> b
snd forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b acc.
(Storable a, Storable b) =>
(acc -> a -> (acc, b)) -> acc -> Vector a -> (acc, Vector b)
mapAccumL (\Int
i a
e -> (Int
i forall a. Num a => a -> a -> a
+ Int
1, Int -> a -> b
f Int
i a
e)) Int
0
{-# INLINE mapIndexed #-}

-- ---------------------------------------------------------------------
-- Building 'Vector's

-- | 'scanl' is similar to 'foldl', but returns a list of successive
-- reduced values from the left. This function will fuse.
--
-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--
-- Note that
--
-- > last (scanl f z xs) == foldl f z xs.
scanl :: (Storable a, Storable b) => (a -> b -> a) -> a -> Vector b -> Vector a
scanl :: forall a b.
(Storable a, Storable b) =>
(a -> b -> a) -> a -> Vector b -> Vector a
scanl a -> b -> a
f a
acc0 Vector b
as0 =
   forall a b. (a, b) -> a
fst forall a b. (a -> b) -> a -> b
$
      forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN (Int -> Int
succ (forall a. Vector a -> Int
length Vector b
as0))
         (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b. (a -> b) -> a -> b
$ \(a
acc,Vector b
as) ->
             (a
acc,
              forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap
                 (\(b
asHead,Vector b
asTail) ->
                     (a -> b -> a
f a
acc b
asHead, Vector b
asTail))
                 (forall a. Storable a => Vector a -> Maybe (a, Vector a)
viewL Vector b
as)))
         (forall a. a -> Maybe a
Just (a
acc0, Vector b
as0))

-- less efficient but much more comprehensible
-- scanl f z ps =
--   cons z (snd (mapAccumL (\acc a -> let b = f acc a in (b,b)) z ps))

    -- n.b. haskell's List scan returns a list one bigger than the
    -- input, so we need to snoc here to get some extra space, however,
    -- it breaks map/up fusion (i.e. scanl . map no longer fuses)
{-# INLINE scanl #-}

-- | 'scanl1' is a variant of 'scanl' that has no starting value argument.
-- This function will fuse.
--
-- > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
scanl1 :: (Storable a) => (a -> a -> a) -> Vector a -> Vector a
scanl1 :: forall a. Storable a => (a -> a -> a) -> Vector a -> Vector a
scanl1 a -> a -> a
f = forall a b.
Storable a =>
b -> (a -> Vector a -> b) -> Vector a -> b
switchL forall a. Storable a => Vector a
empty (forall a b.
(Storable a, Storable b) =>
(a -> b -> a) -> a -> Vector b -> Vector a
scanl a -> a -> a
f)
{-# INLINE scanl1 #-}

-- | scanr is the right-to-left dual of scanl.
scanr :: (Storable a, Storable b) => (a -> b -> b) -> b -> Vector a -> Vector b
scanr :: forall a b.
(Storable a, Storable b) =>
(a -> b -> b) -> b -> Vector a -> Vector b
scanr a -> b -> b
f b
acc0 Vector a
as0 =
   forall a b. (a, b) -> a
fst forall a b. (a -> b) -> a -> b
$
      forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldlN (Int -> Int
succ (forall a. Vector a -> Int
length Vector a
as0))
         (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b. (a -> b) -> a -> b
$ \(b
acc,Vector a
as) ->
             (b
acc,
              forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap
                 (\(Vector a
asInit,a
asLast) ->
                     (a -> b -> b
f a
asLast b
acc, Vector a
asInit))
                 (forall a. Storable a => Vector a -> Maybe (Vector a, a)
viewR Vector a
as)))
         (forall a. a -> Maybe a
Just (b
acc0, Vector a
as0))
{-# INLINE scanr #-}

-- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
scanr1 :: (Storable a) => (a -> a -> a) -> Vector a -> Vector a
scanr1 :: forall a. Storable a => (a -> a -> a) -> Vector a -> Vector a
scanr1 a -> a -> a
f = forall a b.
Storable a =>
b -> (Vector a -> a -> b) -> Vector a -> b
switchR forall a. Storable a => Vector a
empty (forall a b c. (a -> b -> c) -> b -> a -> c
flip (forall a b.
(Storable a, Storable b) =>
(a -> b -> a) -> a -> Vector b -> Vector a
scanl a -> a -> a
f))
{-# INLINE scanr1 #-}

-- ---------------------------------------------------------------------
-- Unfolds and replicates

-- | /O(n)/ 'replicate' @n x@ is a 'Vector' of length @n@ with @x@
-- the value of every element.
--
{- nice implementation
replicate :: (Storable a) => Int -> a -> Vector a
replicate n c =
   fst $ unfoldrN n (const $ Just (c, ())) ()
-}

{-
fast implementation

Maybe it could be made even faster by plainly copying the bit pattern of the first element.
Since there is no function like 'memset',
we could not warrant that the implementation is really efficient
for the actual machine we run on.
-}
replicate :: (Storable a) => Int -> a -> Vector a
replicate :: forall a. Storable a => Int -> a -> Vector a
replicate Int
n a
c =
   if Int
n forall a. Ord a => a -> a -> Bool
<= Int
0
     then forall a. Storable a => Vector a
empty
     else forall a. Storable a => Int -> (Ptr a -> IO ()) -> Vector a
unsafeCreate Int
n forall a b. (a -> b) -> a -> b
$
       let go :: Int -> Ptr a -> IO ()
go = forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \Int
i Ptr a
p ->
              if Int
i forall a. Eq a => a -> a -> Bool
== Int
0
                then forall (m :: * -> *) a. Monad m => a -> m a
return ()
                else forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr a
p a
c forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Int -> Ptr a -> IO ()
go (Int -> Int
pred Int
i) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
p)
       in  Int -> Ptr a -> IO ()
go Int
n
{-# INLINE replicate #-}
{-
For 'replicate 10000000 (42::Int)' generates:

Main_zdwa_info:
	movl (%ebp),%eax
	testl %eax,%eax
	jne .LcfIQ
	movl $ghczmprim_GHCziUnit_Z0T_closure+1,%esi
	addl $8,%ebp
	jmp *(%ebp)
.LcfIQ:
	movl 4(%ebp),%ecx
	movl $42,(%ecx)
	decl %eax
	addl $4,4(%ebp)
	movl %eax,(%ebp)
	jmp Main_zdwa_info

that is, the inner loop consists of 9 instructions,
where I would write something like:
	# counter in %ecx
	testl %ecx
	jz skip_loop
	movl $42,%ebx
start_loop:
	movl %ebx,(%edx)
	addl $4,%edx
	loop start_loop
skip_loop:

and need only 3 instructions in the loop.
-}


-- | /O(n)/ 'iterateN' @n f x@ is a 'Vector' of length @n@
-- where the elements are generated by repeated application of @f@,
-- starting at @x@.
--
iterateN :: (Storable a) => Int -> (a -> a) -> a -> Vector a
iterateN :: forall a. Storable a => Int -> (a -> a) -> a -> Vector a
iterateN Int
n a -> a
f =
   forall a b. (a, b) -> a
fst forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN Int
n (\a
a -> forall a. a -> Maybe a
Just (a
a, a -> a
f a
a))
{-# INLINE iterateN #-}

-- | /O(n)/, where /n/ is the length of the result.  The 'unfoldr'
-- function is analogous to the List \'unfoldr\'.  'unfoldr' builds a
-- 'Vector' from a seed value.  The function takes the element and
-- returns 'Nothing' if it is done producing the 'Vector or returns
-- 'Just' @(a,b)@, in which case, @a@ is the next element in the 'Vector',
-- and @b@ is the seed value for further production.
--
-- Examples:
--
-- >    unfoldr (\x -> if x <= 5 then Just (x, x + 1) else Nothing) 0
-- > == pack [0, 1, 2, 3, 4, 5]
--
unfoldr :: (Storable b) => (a -> Maybe (b, a)) -> a -> Vector b
unfoldr :: forall b a. Storable b => (a -> Maybe (b, a)) -> a -> Vector b
unfoldr a -> Maybe (b, a)
f = forall a. Storable a => [Vector a] -> Vector a
concat forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Int -> a -> [Vector b]
unfoldChunk Int
32 Int
64
  where unfoldChunk :: Int -> Int -> a -> [Vector b]
unfoldChunk Int
n Int
n' a
x =
          case forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN Int
n a -> Maybe (b, a)
f a
x of
            (Vector b
s, Maybe a
mx) -> Vector b
s forall a. a -> [a] -> [a]
: forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (Int -> Int -> a -> [Vector b]
unfoldChunk Int
n' (Int
nforall a. Num a => a -> a -> a
+Int
n')) Maybe a
mx
{-# INLINE unfoldr #-}

-- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a 'Vector' from a seed
-- value.  However, the length of the result is limited by the first
-- argument to 'unfoldrN'.  This function is more efficient than 'unfoldr'
-- when the maximum length of the result is known.
--
-- The following equation relates 'unfoldrN' and 'unfoldr':
--
-- > fst (unfoldrN n f s) == take n (unfoldr f s)
--
unfoldrN :: (Storable b) => Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN :: forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN Int
n a -> Maybe (b, a)
f a
x0 =
   if Int
n forall a. Ord a => a -> a -> Bool
<= Int
0
     then (forall a. Storable a => Vector a
empty, forall a. a -> Maybe a
Just a
x0)
     else forall a. IO a -> a
Unsafe.performIO forall a b. (a -> b) -> a -> b
$ forall a b.
Storable a =>
Int -> (Ptr a -> IO (Int, Int, b)) -> IO (Vector a, b)
createAndTrim' Int
n forall a b. (a -> b) -> a -> b
$ \Ptr b
p -> Ptr b -> Int -> a -> IO (Int, Int, Maybe a)
go Ptr b
p Int
n a
x0
       {-
       go must not be strict in the accumulator
       since otherwise packN would be too strict.
       -}
       where
          go :: Ptr b -> Int -> a -> IO (Int, Int, Maybe a)
go = forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \Ptr b
p Int
i -> \a
x ->
             if Int
i forall a. Eq a => a -> a -> Bool
== Int
0
               then forall (m :: * -> *) a. Monad m => a -> m a
return (Int
0, Int
nforall a. Num a => a -> a -> a
-Int
i, forall a. a -> Maybe a
Just a
x)
               else
                 case a -> Maybe (b, a)
f a
x of
                   Maybe (b, a)
Nothing     -> forall (m :: * -> *) a. Monad m => a -> m a
return (Int
0, Int
nforall a. Num a => a -> a -> a
-Int
i, forall a. Maybe a
Nothing)
                   Just (b
w,a
x') -> do forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr b
p b
w
                                     Ptr b -> Int -> a -> IO (Int, Int, Maybe a)
go (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr b
p) (Int
iforall a. Num a => a -> a -> a
-Int
1) a
x'
{-# INLINE unfoldrN #-}

{-
Examples:

f i = Just (i::Char, succ i)

f i = toMaybe (i<='p') (i::Char, succ i)

-}
-- | /O(n)/ Like 'unfoldrN' this function builds a 'Vector'
-- from a seed value with limited size.
-- Additionally it returns a value, that depends on the state,
-- but is not necessarily the state itself.
-- If end of vector and end of the generator coincide,
-- then the result is as if only the end of vector is reached.
--
-- Example:
--
-- > unfoldrResultN 30 Char.ord (\c -> if c>'z' then Left 1000 else Right (c, succ c)) 'a'
--
-- The following equation relates 'unfoldrN' and 'unfoldrResultN':
--
-- > unfoldrN n f s ==
-- >    unfoldrResultN n Just
-- >       (maybe (Left Nothing) Right . f) s
--
-- It is not possible to express 'unfoldrResultN' in terms of 'unfoldrN'.
--
unfoldrResultN :: (Storable b) => Int -> (a -> c) -> (a -> Either c (b, a)) -> a -> (Vector b, c)
unfoldrResultN :: forall b a c.
Storable b =>
Int -> (a -> c) -> (a -> Either c (b, a)) -> a -> (Vector b, c)
unfoldrResultN Int
i a -> c
g a -> Either c (b, a)
f a
x0 =
   if Int
i forall a. Ord a => a -> a -> Bool
<= Int
0
     then (forall a. Storable a => Vector a
empty, a -> c
g a
x0)
     else forall a. IO a -> a
Unsafe.performIO forall a b. (a -> b) -> a -> b
$ forall a b.
Storable a =>
Int -> (Ptr a -> IO (Int, Int, b)) -> IO (Vector a, b)
createAndTrim' Int
i forall a b. (a -> b) -> a -> b
$ \Ptr b
p -> Ptr b -> Int -> a -> IO (Int, Int, c)
go Ptr b
p Int
0 a
x0
       {-
       go must not be strict in the accumulator
       since otherwise packN would be too strict.
       -}
       where
          go :: Ptr b -> Int -> a -> IO (Int, Int, c)
go = forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \Ptr b
p Int
n -> \a
a0 ->
             if Int
n forall a. Eq a => a -> a -> Bool
== Int
i
               then forall (m :: * -> *) a. Monad m => a -> m a
return (Int
0, Int
n, a -> c
g a
a0)
               else
                 case a -> Either c (b, a)
f a
a0 of
                   Left c
c -> forall (m :: * -> *) a. Monad m => a -> m a
return (Int
0, Int
n, c
c)
                   Right (b
b,a
a1) -> do forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr b
p b
b
                                      Ptr b -> Int -> a -> IO (Int, Int, c)
go (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr b
p) (Int
nforall a. Num a => a -> a -> a
+Int
1) a
a1
{-# INLINE unfoldrResultN #-}

unfoldlN :: (Storable b) => Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldlN :: forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldlN Int
i a -> Maybe (b, a)
f a
x0
    | Int
i forall a. Ord a => a -> a -> Bool
< Int
0     = (forall a. Storable a => Vector a
empty, forall a. a -> Maybe a
Just a
x0)
    | Bool
otherwise = forall a. IO a -> a
Unsafe.performIO forall a b. (a -> b) -> a -> b
$ forall a b.
Storable a =>
Int -> (Ptr a -> IO (Int, Int, b)) -> IO (Vector a, b)
createAndTrim' Int
i forall a b. (a -> b) -> a -> b
$ \Ptr b
p -> Ptr b -> Int -> a -> IO (Int, Int, Maybe a)
go (Ptr b
p forall a. Storable a => Ptr a -> Int -> Ptr a
`advancePtr` Int
i) Int
i a
x0
  where go :: Ptr b -> Int -> a -> IO (Int, Int, Maybe a)
go = forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \Ptr b
p Int
n -> \a
x ->
           if Int
n forall a. Eq a => a -> a -> Bool
== Int
0
             then forall (m :: * -> *) a. Monad m => a -> m a
return (Int
n, Int
i, forall a. a -> Maybe a
Just a
x)
             else
               case a -> Maybe (b, a)
f a
x of
                 Maybe (b, a)
Nothing     -> forall (m :: * -> *) a. Monad m => a -> m a
return (Int
n, Int
i, forall a. Maybe a
Nothing)
                 Just (b
w,a
x') ->
                    let p' :: Ptr b
p' = Ptr b
p forall a. Storable a => Ptr a -> Int -> Ptr a
`advancePtr` (-Int
1)
                    in  do forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr b
p' b
w
                           Ptr b -> Int -> a -> IO (Int, Int, Maybe a)
go Ptr b
p' (Int
nforall a. Num a => a -> a -> a
-Int
1) a
x'
{-# INLINE unfoldlN #-}


-- | /O(n)/, where /n/ is the length of the result.
-- This function constructs a vector by evaluating a function
-- that depends on the element index.
-- It is a special case of 'unfoldrN' and can in principle be parallelized.
--
-- Examples:
--
-- >    sample 26 (\x -> chr(ord 'a'+x))
-- > == pack "abcdefghijklmnopqrstuvwxyz"
--
sample :: (Storable a) => Int -> (Int -> a) -> Vector a
sample :: forall a. Storable a => Int -> (Int -> a) -> Vector a
sample Int
n Int -> a
f =
   forall a b. (a, b) -> a
fst forall a b. (a -> b) -> a -> b
$ forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN Int
n (\Int
i -> forall a. a -> Maybe a
Just (Int -> a
f Int
i, Int -> Int
succ Int
i)) Int
0
{-# INLINE sample #-}


-- ---------------------------------------------------------------------
-- Substrings

-- | /O(1)/ 'take' @n@, applied to a 'Vector' @xs@, returns the prefix
-- of @xs@ of length @n@, or @xs@ itself if @n > 'length' xs@.
take :: (Storable a) => Int -> Vector a -> Vector a
take :: forall a. Storable a => Int -> Vector a -> Vector a
take Int
n ps :: Vector a
ps@(SV ForeignPtr a
x Int
s Int
l)
    | Int
n forall a. Ord a => a -> a -> Bool
<= Int
0    = forall a. Storable a => Vector a
empty
    | Int
n forall a. Ord a => a -> a -> Bool
>= Int
l    = Vector a
ps
    | Bool
otherwise = forall a. ForeignPtr a -> Int -> Int -> Vector a
SV ForeignPtr a
x Int
s Int
n
{-# INLINE take #-}

-- | /O(1)/ 'drop' @n xs@ returns the suffix of @xs@ after the first @n@
-- elements, or 'empty' if @n > 'length' xs@.
drop  :: (Storable a) => Int -> Vector a -> Vector a
drop :: forall a. Storable a => Int -> Vector a -> Vector a
drop Int
n ps :: Vector a
ps@(SV ForeignPtr a
x Int
s Int
l)
    | Int
n forall a. Ord a => a -> a -> Bool
<= Int
0    = Vector a
ps
    | Int
n forall a. Ord a => a -> a -> Bool
>= Int
l    = forall a. Storable a => Vector a
empty
    | Bool
otherwise = forall a. ForeignPtr a -> Int -> Int -> Vector a
SV ForeignPtr a
x (Int
sforall a. Num a => a -> a -> a
+Int
n) (Int
lforall a. Num a => a -> a -> a
-Int
n)
{-# INLINE drop #-}

-- | /O(1)/ 'splitAt' @n xs@ is equivalent to @('take' n xs, 'drop' n xs)@.
splitAt :: (Storable a) => Int -> Vector a -> (Vector a, Vector a)
splitAt :: forall a. Storable a => Int -> Vector a -> (Vector a, Vector a)
splitAt Int
n ps :: Vector a
ps@(SV ForeignPtr a
x Int
s Int
l)
    | Int
n forall a. Ord a => a -> a -> Bool
<= Int
0    = (forall a. Storable a => Vector a
empty, Vector a
ps)
    | Int
n forall a. Ord a => a -> a -> Bool
>= Int
l    = (Vector a
ps, forall a. Storable a => Vector a
empty)
    | Bool
otherwise = (forall a. ForeignPtr a -> Int -> Int -> Vector a
SV ForeignPtr a
x Int
s Int
n, forall a. ForeignPtr a -> Int -> Int -> Vector a
SV ForeignPtr a
x (Int
sforall a. Num a => a -> a -> a
+Int
n) (Int
lforall a. Num a => a -> a -> a
-Int
n))
{-# INLINE splitAt #-}

{- | 'sliceVertical' @n xs@ divides vector in chunks of size @n@.
Requires time proportionally to length of result list,
i.e. @ceiling (length xs / n)@. -}
sliceVertical :: (Storable a) => Int -> Vector a -> [Vector a]
sliceVertical :: forall a. Storable a => Int -> Vector a -> [Vector a]
sliceVertical Int
n =
   forall b a. (b -> Maybe (a, b)) -> b -> [a]
List.unfoldr (\Vector a
x -> forall a. Bool -> a -> Maybe a
toMaybe (Bool -> Bool
not (forall a. Vector a -> Bool
null Vector a
x)) (forall a. Storable a => Int -> Vector a -> (Vector a, Vector a)
splitAt Int
n Vector a
x))
{-# INLINE sliceVertical #-}

_sliceVertical :: (Storable a) => Int -> Vector a -> [Vector a]
_sliceVertical :: forall a. Storable a => Int -> Vector a -> [Vector a]
_sliceVertical Int
n Vector a
xs =
   forall a b. (a -> b) -> [a] -> [b]
List.map (forall a. Storable a => Int -> Vector a -> Vector a
take Int
n forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c. (a -> b -> c) -> b -> a -> c
flip forall a. Storable a => Int -> Vector a -> Vector a
drop Vector a
xs) forall a b. (a -> b) -> a -> b
$
   forall a. (a -> Bool) -> [a] -> [a]
List.takeWhile (forall a. Ord a => a -> a -> Bool
< forall a. Vector a -> Int
length Vector a
xs) forall a b. (a -> b) -> a -> b
$ forall a. (a -> a) -> a -> [a]
List.iterate (Int
nforall a. Num a => a -> a -> a
+) Int
0


-- | 'takeWhile', applied to a predicate @p@ and a 'Vector' @xs@,
-- returns the longest prefix (possibly empty) of @xs@ of elements that
-- satisfy @p@.
takeWhile :: (Storable a) => (a -> Bool) -> Vector a -> Vector a
takeWhile :: forall a. Storable a => (a -> Bool) -> Vector a -> Vector a
takeWhile a -> Bool
f Vector a
ps = forall a. Storable a => Int -> Vector a -> Vector a
unsafeTake (forall a. Storable a => (a -> Bool) -> Vector a -> Int
findIndexOrEnd (Bool -> Bool
not forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Bool
f) Vector a
ps) Vector a
ps
{-# INLINE takeWhile #-}

-- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
dropWhile :: (Storable a) => (a -> Bool) -> Vector a -> Vector a
dropWhile :: forall a. Storable a => (a -> Bool) -> Vector a -> Vector a
dropWhile a -> Bool
f Vector a
ps = forall a. Storable a => Int -> Vector a -> Vector a
unsafeDrop (forall a. Storable a => (a -> Bool) -> Vector a -> Int
findIndexOrEnd (Bool -> Bool
not forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Bool
f) Vector a
ps) Vector a
ps
{-# INLINE dropWhile #-}

-- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
break :: (Storable a) => (a -> Bool) -> Vector a -> (Vector a, Vector a)
break :: forall a.
Storable a =>
(a -> Bool) -> Vector a -> (Vector a, Vector a)
break a -> Bool
p Vector a
ps = case forall a. Storable a => (a -> Bool) -> Vector a -> Int
findIndexOrEnd a -> Bool
p Vector a
ps of Int
n -> (forall a. Storable a => Int -> Vector a -> Vector a
unsafeTake Int
n Vector a
ps, forall a. Storable a => Int -> Vector a -> Vector a
unsafeDrop Int
n Vector a
ps)
{-# INLINE break #-}

-- | 'breakEnd' behaves like 'break' but from the end of the 'Vector'
--
-- breakEnd p == spanEnd (not.p)
breakEnd :: (Storable a) => (a -> Bool) -> Vector a -> (Vector a, Vector a)
breakEnd :: forall a.
Storable a =>
(a -> Bool) -> Vector a -> (Vector a, Vector a)
breakEnd  a -> Bool
p Vector a
ps = forall a. Storable a => Int -> Vector a -> (Vector a, Vector a)
splitAt (forall a. Storable a => (a -> Bool) -> Vector a -> Int
findFromEndUntil a -> Bool
p Vector a
ps) Vector a
ps

-- | 'span' @p xs@ breaks the 'Vector' into two segments. It is
-- equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
span :: (Storable a) => (a -> Bool) -> Vector a -> (Vector a, Vector a)
span :: forall a.
Storable a =>
(a -> Bool) -> Vector a -> (Vector a, Vector a)
span a -> Bool
p Vector a
ps = forall a.
Storable a =>
(a -> Bool) -> Vector a -> (Vector a, Vector a)
break (Bool -> Bool
not forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Bool
p) Vector a
ps
{-# INLINE span #-}

-- | 'spanEnd' behaves like 'span' but from the end of the 'Vector'.
-- We have
--
-- > spanEnd (not.isSpace) "x y z" == ("x y ","z")
--
-- and
--
-- > spanEnd (not . isSpace) ps
-- >    ==
-- > let (x,y) = span (not.isSpace) (reverse ps) in (reverse y, reverse x)
--
spanEnd :: (Storable a) => (a -> Bool) -> Vector a -> (Vector a, Vector a)
spanEnd :: forall a.
Storable a =>
(a -> Bool) -> Vector a -> (Vector a, Vector a)
spanEnd  a -> Bool
p Vector a
ps = forall a. Storable a => Int -> Vector a -> (Vector a, Vector a)
splitAt (forall a. Storable a => (a -> Bool) -> Vector a -> Int
findFromEndUntil (Bool -> Bool
notforall b c a. (b -> c) -> (a -> b) -> a -> c
.a -> Bool
p) Vector a
ps) Vector a
ps

-- | /O(n)/ Splits a 'Vector' into components delimited by
-- separators, where the predicate returns True for a separator element.
-- The resulting components do not contain the separators.  Two adjacent
-- separators result in an empty component in the output.  eg.
--
-- > splitWith (=='a') "aabbaca" == ["","","bb","c",""]
-- > splitWith (=='a') []        == []
--
splitWith :: (Storable a) => (a -> Bool) -> Vector a -> [Vector a]
splitWith :: forall a. Storable a => (a -> Bool) -> Vector a -> [Vector a]
splitWith a -> Bool
_ (SV ForeignPtr a
_ Int
_ Int
0) = []
splitWith a -> Bool
p Vector a
ps = Vector a -> [Vector a]
loop Vector a
ps
    where
        loop :: Vector a -> [Vector a]
loop =
           forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry (:) forall b c a. (b -> c) -> (a -> b) -> a -> c
.
           forall b c a. (b -> c) -> (a, b) -> (a, c)
mapSnd (forall a b.
Storable a =>
b -> (a -> Vector a -> b) -> Vector a -> b
switchL [] (\ a
_ Vector a
t -> Vector a -> [Vector a]
loop Vector a
t)) forall b c a. (b -> c) -> (a -> b) -> a -> c
.
           forall a.
Storable a =>
(a -> Bool) -> Vector a -> (Vector a, Vector a)
break a -> Bool
p
{-# INLINE splitWith #-}

-- | /O(n)/ Break a 'Vector' into pieces separated by the
-- argument, consuming the delimiter. I.e.
--
-- > split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
-- > split 'a'  "aXaXaXa"    == ["","X","X","X"]
-- > split 'x'  "x"          == ["",""]
--
-- and
--
-- > join [c] . split c == id
-- > split == splitWith . (==)
--
-- As for all splitting functions in this library, this function does
-- not copy the substrings, it just constructs new 'Vector's that
-- are slices of the original.
--
split :: (Storable a, Eq a) => a -> Vector a -> [Vector a]
split :: forall a. (Storable a, Eq a) => a -> Vector a -> [Vector a]
split a
w Vector a
v = forall a. Storable a => (a -> Bool) -> Vector a -> [Vector a]
splitWith (a
wforall a. Eq a => a -> a -> Bool
==) Vector a
v
{-# INLINE split #-}

-- | Like 'splitWith', except that sequences of adjacent separators are
-- treated as a single separator. eg.
--
-- > tokens (=='a') "aabbaca" == ["bb","c"]
--
tokens :: (Storable a) => (a -> Bool) -> Vector a -> [Vector a]
tokens :: forall a. Storable a => (a -> Bool) -> Vector a -> [Vector a]
tokens a -> Bool
f = forall a. (a -> Bool) -> [a] -> [a]
P.filter (Bool -> Bool
notforall b c a. (b -> c) -> (a -> b) -> a -> c
.forall a. Vector a -> Bool
null) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Storable a => (a -> Bool) -> Vector a -> [Vector a]
splitWith a -> Bool
f
{-# INLINE tokens #-}

-- | The 'group' function takes a 'Vector' and returns a list of
-- 'Vector's such that the concatenation of the result is equal to the
-- argument.  Moreover, each sublist in the result contains only equal
-- elements.  For example,
--
-- > group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]
--
-- It is a special case of 'groupBy', which allows the programmer to
-- supply their own equality test. It is about 40% faster than
-- /groupBy (==)/
group :: (Storable a, Eq a) => Vector a -> [Vector a]
group :: forall a. (Storable a, Eq a) => Vector a -> [Vector a]
group Vector a
xs =
   forall a b.
Storable a =>
b -> (a -> Vector a -> b) -> Vector a -> b
switchL []
      (\ a
h Vector a
_ ->
          let (Vector a
ys, Vector a
zs) = forall a.
Storable a =>
(a -> Bool) -> Vector a -> (Vector a, Vector a)
span (forall a. Eq a => a -> a -> Bool
== a
h) Vector a
xs
          in  Vector a
ys forall a. a -> [a] -> [a]
: forall a. (Storable a, Eq a) => Vector a -> [Vector a]
group Vector a
zs)
      Vector a
xs

-- | The 'groupBy' function is the non-overloaded version of 'group'.
groupBy :: (Storable a) => (a -> a -> Bool) -> Vector a -> [Vector a]
groupBy :: forall a. Storable a => (a -> a -> Bool) -> Vector a -> [Vector a]
groupBy a -> a -> Bool
k Vector a
xs =
   forall a b.
Storable a =>
b -> (a -> Vector a -> b) -> Vector a -> b
switchL []
      (\ a
h Vector a
t ->
          let n :: Int
n = Int
1 forall a. Num a => a -> a -> a
+ forall a. Storable a => (a -> Bool) -> Vector a -> Int
findIndexOrEnd (Bool -> Bool
not forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> a -> Bool
k a
h) Vector a
t
          in  forall a. Storable a => Int -> Vector a -> Vector a
unsafeTake Int
n Vector a
xs forall a. a -> [a] -> [a]
: forall a. Storable a => (a -> a -> Bool) -> Vector a -> [Vector a]
groupBy a -> a -> Bool
k (forall a. Storable a => Int -> Vector a -> Vector a
unsafeDrop Int
n Vector a
xs))
      Vector a
xs
{-# INLINE groupBy #-}


-- | /O(n)/ The 'join' function takes a 'Vector' and a list of
-- 'Vector's and concatenates the list after interspersing the first
-- argument between each element of the list.
join :: (Storable a) => Vector a -> [Vector a] -> Vector a
join :: forall a. Storable a => Vector a -> [Vector a] -> Vector a
join Vector a
s = forall a. Storable a => [Vector a] -> Vector a
concat forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. a -> [a] -> [a]
List.intersperse Vector a
s
{-# INLINE join #-}

-- ---------------------------------------------------------------------
-- Indexing 'Vector's

-- | /O(1)/ 'Vector' index (subscript) operator, starting from 0.
index :: (Storable a) => Vector a -> Int -> a
index :: forall a. Storable a => Vector a -> Int -> a
index Vector a
ps Int
n
    | Int
n forall a. Ord a => a -> a -> Bool
< Int
0          = forall a. String -> String -> a
moduleError String
"index" (String
"negative index: " forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show Int
n)
    | Int
n forall a. Ord a => a -> a -> Bool
>= forall a. Vector a -> Int
length Vector a
ps = forall a. String -> String -> a
moduleError String
"index" (String
"index too large: " forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show Int
n
                                         forall a. [a] -> [a] -> [a]
++ String
", length = " forall a. [a] -> [a] -> [a]
++ forall a. Show a => a -> String
show (forall a. Vector a -> Int
length Vector a
ps))
    | Bool
otherwise      = Vector a
ps forall a. Storable a => Vector a -> Int -> a
`unsafeIndex` Int
n
{-# INLINE index #-}

-- | /O(n)/ The 'elemIndex' function returns the index of the first
-- element in the given 'Vector' which is equal to the query
-- element, or 'Nothing' if there is no such element.
elemIndex :: (Storable a, Eq a) => a -> Vector a -> Maybe Int
elemIndex :: forall a. (Storable a, Eq a) => a -> Vector a -> Maybe Int
elemIndex a
c = forall a. Storable a => (a -> Bool) -> Vector a -> Maybe Int
findIndex (a
cforall a. Eq a => a -> a -> Bool
==)
{-# INLINE elemIndex #-}

-- | /O(n)/ The 'elemIndexEnd' function returns the last index of the
-- element in the given 'Vector' which is equal to the query
-- element, or 'Nothing' if there is no such element. The following
-- holds:
--
-- > elemIndexEnd c xs ==
-- > (-) (length xs - 1) `fmap` elemIndex c (reverse xs)
--
elemIndexEnd :: (Storable a, Eq a) => a -> Vector a -> Maybe Int
elemIndexEnd :: forall a. (Storable a, Eq a) => a -> Vector a -> Maybe Int
elemIndexEnd a
c =
   forall a b. (a, b) -> a
fst forall b c a. (b -> c) -> (a -> b) -> a -> c
.
   forall a b. Storable a => (b -> a -> b) -> b -> Vector a -> b
foldl
      (\(Maybe Int
ri,Int
i) a
x -> (if a
cforall a. Eq a => a -> a -> Bool
==a
x then forall a. a -> Maybe a
Just Int
i else Maybe Int
ri, Int -> Int
succ Int
i))
      (forall a. Maybe a
Nothing,Int
0)
{-# INLINE elemIndexEnd #-}

-- | /O(n)/ The 'elemIndices' function extends 'elemIndex', by returning
-- the indices of all elements equal to the query element, in ascending order.
elemIndices :: (Storable a, Eq a) => a -> Vector a -> [Int]
elemIndices :: forall a. (Storable a, Eq a) => a -> Vector a -> [Int]
elemIndices a
c = forall a. Storable a => (a -> Bool) -> Vector a -> [Int]
findIndices (a
cforall a. Eq a => a -> a -> Bool
==)
{-# INLINE elemIndices #-}

-- | count returns the number of times its argument appears in the 'Vector'
--
-- > count = length . elemIndices
--
-- But more efficiently than using length on the intermediate list.
count :: (Storable a, Eq a) => a -> Vector a -> Int
count :: forall a. (Storable a, Eq a) => a -> Vector a -> Int
count a
w =
   forall a b. Storable a => (b -> a -> b) -> b -> Vector a -> b
foldl (forall a b c. (a -> b -> c) -> b -> a -> c
flip forall a b. (a -> b) -> a -> b
$ \a
c -> if a
cforall a. Eq a => a -> a -> Bool
==a
w then Int -> Int
succ else forall a. a -> a
id) Int
0
{-
count w sv =
   List.length $ elemIndices w sv
-}
{-# INLINE count #-}

-- | The 'findIndex' function takes a predicate and a 'Vector' and
-- returns the index of the first element in the 'Vector'
-- satisfying the predicate.
findIndex :: (Storable a) => (a -> Bool) -> Vector a -> Maybe Int
findIndex :: forall a. Storable a => (a -> Bool) -> Vector a -> Maybe Int
findIndex a -> Bool
p Vector a
xs =
   {- The implementation is in principle the same as for findIndices,
      but we use the First monoid, instead of the List/append monoid.
      We could also implement findIndex in terms of monoidConcatMap. -}
   forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr
      (\a
x Int -> Maybe Int
k Int
n ->
         forall a. Bool -> a -> Maybe a
toMaybe (a -> Bool
p a
x) Int
n forall (m :: * -> *) a. MonadPlus m => m a -> m a -> m a
`mplus` Int -> Maybe Int
k (Int -> Int
succ Int
n))
      (forall a b. a -> b -> a
const forall a. Maybe a
Nothing) Vector a
xs Int
0
{-# INLINE findIndex #-}

-- | The 'findIndices' function extends 'findIndex', by returning the
-- indices of all elements satisfying the predicate, in ascending order.
findIndices :: (Storable a) => (a -> Bool) -> Vector a -> [Int]
findIndices :: forall a. Storable a => (a -> Bool) -> Vector a -> [Int]
findIndices a -> Bool
p Vector a
xs =
   forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr
      (\a
x Int -> [Int]
k Int
n ->
         (if a -> Bool
p a
x then (Int
nforall a. a -> [a] -> [a]
:) else forall a. a -> a
id)
            (Int -> [Int]
k (Int -> Int
succ Int
n)))
      (forall a b. a -> b -> a
const []) Vector a
xs Int
0
{-# INLINE findIndices #-}

-- | 'findIndexOrEnd' is a variant of findIndex, that returns the length
-- of the string if no element is found, rather than Nothing.
findIndexOrEnd :: (Storable a) => (a -> Bool) -> Vector a -> Int
findIndexOrEnd :: forall a. Storable a => (a -> Bool) -> Vector a -> Int
findIndexOrEnd a -> Bool
p Vector a
xs =
   forall a b. Storable a => (a -> b -> b) -> b -> Vector a -> b
foldr
      (\a
x Int -> Int
k Int
n ->
         if a -> Bool
p a
x then Int
n else Int -> Int
k (Int -> Int
succ Int
n))
      forall a. a -> a
id Vector a
xs Int
0
{-# INLINE findIndexOrEnd #-}

-- ---------------------------------------------------------------------
-- Searching Vectors

-- | /O(n)/ 'elem' is the 'Vector' membership predicate.
elem :: (Storable a, Eq a) => a -> Vector a -> Bool
elem :: forall a. (Storable a, Eq a) => a -> Vector a -> Bool
elem a
c Vector a
ps = forall a. Maybe a -> Bool
isJust forall a b. (a -> b) -> a -> b
$ forall a. (Storable a, Eq a) => a -> Vector a -> Maybe Int
elemIndex a
c Vector a
ps
{-# INLINE elem #-}

-- | /O(n)/ 'notElem' is the inverse of 'elem'
notElem :: (Storable a, Eq a) => a -> Vector a -> Bool
notElem :: forall a. (Storable a, Eq a) => a -> Vector a -> Bool
notElem a
c Vector a
ps = Bool -> Bool
not (forall a. (Storable a, Eq a) => a -> Vector a -> Bool
elem a
c Vector a
ps)
{-# INLINE notElem #-}

-- | /O(n)/ 'filter', applied to a predicate and a 'Vector',
-- returns a 'Vector' containing those elements that satisfy the predicate.
filter :: (Storable a) => (a -> Bool) -> Vector a -> Vector a
filter :: forall a. Storable a => (a -> Bool) -> Vector a -> Vector a
filter a -> Bool
p (SV ForeignPtr a
fp Int
s Int
l) =
   let end :: Int
end = Int
sforall a. Num a => a -> a -> a
+Int
l
   in  forall a b. (a, b) -> a
fst forall a b. (a -> b) -> a -> b
$
       forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN Int
l
          (let go :: Int -> Maybe (a, Int)
go = forall a x. (a -> x) -> a -> x
Strict.arguments1 forall a b. (a -> b) -> a -> b
$ \Int
k0 ->
                  do forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Int
k0forall a. Ord a => a -> a -> Bool
<Int
end)
                     let x :: a
x = forall a. Storable a => ForeignPtr a -> Int -> a
foreignPeek ForeignPtr a
fp Int
k0
                         k1 :: Int
k1 = Int -> Int
succ Int
k0
                     if a -> Bool
p a
x
                       then forall a. a -> Maybe a
Just (a
x,Int
k1)
                       else Int -> Maybe (a, Int)
go Int
k1
           in  Int -> Maybe (a, Int)
go)
          Int
s
{-# INLINE filter #-}

-- | /O(n)/ The 'find' function takes a predicate and a 'Vector',
-- and returns the first element in matching the predicate, or 'Nothing'
-- if there is no such element.
--
-- > find f p = case findIndex f p of Just n -> Just (p ! n) ; _ -> Nothing
--
find :: (Storable a) => (a -> Bool) -> Vector a -> Maybe a
find :: forall a. Storable a => (a -> Bool) -> Vector a -> Maybe a
find a -> Bool
f Vector a
p = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (forall a. Storable a => Vector a -> Int -> a
unsafeIndex Vector a
p) (forall a. Storable a => (a -> Bool) -> Vector a -> Maybe Int
findIndex a -> Bool
f Vector a
p)
{-# INLINE find #-}

-- ---------------------------------------------------------------------
-- Searching for substrings

-- | /O(n)/ The 'isPrefixOf' function takes two 'Vector' and returns 'True'
-- iff the first is a prefix of the second.
isPrefixOf :: (Storable a, Eq a) => Vector a -> Vector a -> Bool
isPrefixOf :: forall a. (Storable a, Eq a) => Vector a -> Vector a -> Bool
isPrefixOf x :: Vector a
x@(SV ForeignPtr a
_ Int
_ Int
l1) y :: Vector a
y@(SV ForeignPtr a
_ Int
_ Int
l2) =
    Int
l1 forall a. Ord a => a -> a -> Bool
<= Int
l2 Bool -> Bool -> Bool
&& Vector a
x forall a. Eq a => a -> a -> Bool
== forall a. Storable a => Int -> Vector a -> Vector a
unsafeTake Int
l1 Vector a
y

-- | /O(n)/ The 'isSuffixOf' function takes two 'Vector's and returns 'True'
-- iff the first is a suffix of the second.
--
-- The following holds:
--
-- > isSuffixOf x y == reverse x `isPrefixOf` reverse y
--
isSuffixOf :: (Storable a, Eq a) => Vector a -> Vector a -> Bool
isSuffixOf :: forall a. (Storable a, Eq a) => Vector a -> Vector a -> Bool
isSuffixOf x :: Vector a
x@(SV ForeignPtr a
_ Int
_ Int
l1) y :: Vector a
y@(SV ForeignPtr a
_ Int
_ Int
l2) =
    Int
l1 forall a. Ord a => a -> a -> Bool
<= Int
l2 Bool -> Bool -> Bool
&& Vector a
x forall a. Eq a => a -> a -> Bool
== forall a. Storable a => Int -> Vector a -> Vector a
unsafeDrop (Int
l2 forall a. Num a => a -> a -> a
- Int
l1) Vector a
y

-- ---------------------------------------------------------------------
-- Zipping

-- | /O(n)/ 'zip' takes two 'Vector's and returns a list of
-- corresponding pairs of elements. If one input 'Vector' is short,
-- excess elements of the longer 'Vector' are discarded. This is
-- equivalent to a pair of 'unpack' operations.
zip :: (Storable a, Storable b) => Vector a -> Vector b -> [(a, b)]
zip :: forall a b.
(Storable a, Storable b) =>
Vector a -> Vector b -> [(a, b)]
zip Vector a
ps Vector b
qs =
   forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] forall a. a -> a
id forall a b. (a -> b) -> a -> b
$
      do (a
ph,Vector a
pt) <- forall a. Storable a => Vector a -> Maybe (a, Vector a)
viewL Vector a
ps
         (b
qh,Vector b
qt) <- forall a. Storable a => Vector a -> Maybe (a, Vector a)
viewL Vector b
qs
         forall (m :: * -> *) a. Monad m => a -> m a
return ((a
ph,b
qh) forall a. a -> [a] -> [a]
: forall a b.
(Storable a, Storable b) =>
Vector a -> Vector b -> [(a, b)]
zip Vector a
pt Vector b
qt)

-- | 'zipWith' generalises 'zip' by zipping with the function given as
-- the first argument, instead of a tupling function.  For example,
-- @'zipWith' (+)@ is applied to two 'Vector's to produce the list of
-- corresponding sums.
zipWith :: (Storable a, Storable b, Storable c) =>
   (a -> b -> c) -> Vector a -> Vector b -> Vector c
zipWith :: forall a b c.
(Storable a, Storable b, Storable c) =>
(a -> b -> c) -> Vector a -> Vector b -> Vector c
zipWith a -> b -> c
f Vector a
as Vector b
bs =
   forall a b. Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr Vector a
as forall a b. (a -> b) -> a -> b
$ \Ptr a
pa0 Int
la ->
   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr       Vector b
bs forall a b. (a -> b) -> a -> b
$ \Ptr b
pb0 Int
lb ->
   let len :: Int
len = forall a. Ord a => a -> a -> a
min Int
la Int
lb
   in  forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create Int
len forall a b. (a -> b) -> a -> b
$ \Ptr c
p0 ->
       let go :: Int -> Ptr c -> Ptr a -> Ptr b -> IO ()
go = forall a b c d x. (a -> b -> c -> d -> x) -> a -> b -> c -> d -> x
Strict.arguments4 forall a b. (a -> b) -> a -> b
$ \Int
n Ptr c
p Ptr a
pa Ptr b
pb ->
              forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
nforall a. Ord a => a -> a -> Bool
>Int
0) forall a b. (a -> b) -> a -> b
$
                 forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 a -> b -> c
f (forall a. Storable a => Ptr a -> IO a
St.peek Ptr a
pa) (forall a. Storable a => Ptr a -> IO a
St.peek Ptr b
pb) forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr c
p forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
                 Int -> Ptr c -> Ptr a -> Ptr b -> IO ()
go (Int -> Int
pred Int
n) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr c
p) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
pa) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr b
pb)
       in  Int -> Ptr c -> Ptr a -> Ptr b -> IO ()
go Int
len Ptr c
p0 Ptr a
pa0 Ptr b
pb0


-- zipWith f ps qs = pack $ List.zipWith f (unpack ps) (unpack qs)
{-# INLINE zipWith #-}

-- | Like 'zipWith' but for three input vectors
zipWith3 :: (Storable a, Storable b, Storable c, Storable d) =>
   (a -> b -> c -> d) -> Vector a -> Vector b -> Vector c -> Vector d
zipWith3 :: forall a b c d.
(Storable a, Storable b, Storable c, Storable d) =>
(a -> b -> c -> d) -> Vector a -> Vector b -> Vector c -> Vector d
zipWith3 a -> b -> c -> d
f Vector a
as Vector b
bs Vector c
cs =
   forall a b. Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr Vector a
as forall a b. (a -> b) -> a -> b
$ \Ptr a
pa0 Int
la ->
   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr       Vector b
bs forall a b. (a -> b) -> a -> b
$ \Ptr b
pb0 Int
lb ->
   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr       Vector c
cs forall a b. (a -> b) -> a -> b
$ \Ptr c
pc0 Int
lc ->
   let len :: Int
len = Int
la forall a. Ord a => a -> a -> a
`min` Int
lb forall a. Ord a => a -> a -> a
`min` Int
lc
   in  forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create Int
len forall a b. (a -> b) -> a -> b
$ \Ptr d
p0 ->
       let go :: Int -> Ptr d -> Ptr a -> Ptr b -> Ptr c -> IO ()
go = forall a b c d e x.
(a -> b -> c -> d -> e -> x) -> a -> b -> c -> d -> e -> x
Strict.arguments5 forall a b. (a -> b) -> a -> b
$ \Int
n Ptr d
p Ptr a
pa Ptr b
pb Ptr c
pc ->
              forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
nforall a. Ord a => a -> a -> Bool
>Int
0) forall a b. (a -> b) -> a -> b
$
                 forall (m :: * -> *) a1 a2 a3 r.
Monad m =>
(a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
liftM3 a -> b -> c -> d
f (forall a. Storable a => Ptr a -> IO a
St.peek Ptr a
pa) (forall a. Storable a => Ptr a -> IO a
St.peek Ptr b
pb) (forall a. Storable a => Ptr a -> IO a
St.peek Ptr c
pc) forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr d
p forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
                 Int -> Ptr d -> Ptr a -> Ptr b -> Ptr c -> IO ()
go (Int -> Int
pred Int
n) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr d
p) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
pa) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr b
pb) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr c
pc)
       in  Int -> Ptr d -> Ptr a -> Ptr b -> Ptr c -> IO ()
go Int
len Ptr d
p0 Ptr a
pa0 Ptr b
pb0 Ptr c
pc0
{-# INLINE zipWith3 #-}

-- | Like 'zipWith' but for four input vectors
-- If you need even more input vectors,
-- you might write a function yourselve using unfoldrN and viewL.
zipWith4 :: (Storable a, Storable b, Storable c, Storable d, Storable e) =>
   (a -> b -> c -> d -> e) -> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
zipWith4 :: forall a b c d e.
(Storable a, Storable b, Storable c, Storable d, Storable e) =>
(a -> b -> c -> d -> e)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
zipWith4 a -> b -> c -> d -> e
f Vector a
as Vector b
bs Vector c
cs Vector d
ds =
   forall a b. Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr Vector a
as forall a b. (a -> b) -> a -> b
$ \Ptr a
pa0 Int
la ->
   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr       Vector b
bs forall a b. (a -> b) -> a -> b
$ \Ptr b
pb0 Int
lb ->
   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr       Vector c
cs forall a b. (a -> b) -> a -> b
$ \Ptr c
pc0 Int
lc ->
   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr       Vector d
ds forall a b. (a -> b) -> a -> b
$ \Ptr d
pd0 Int
ld ->
   let len :: Int
len = Int
la forall a. Ord a => a -> a -> a
`min` Int
lb forall a. Ord a => a -> a -> a
`min` Int
lc forall a. Ord a => a -> a -> a
`min` Int
ld
   in  forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create Int
len forall a b. (a -> b) -> a -> b
$ \Ptr e
p0 ->
       let go :: Int -> Ptr e -> Ptr a -> Ptr b -> Ptr c -> Ptr d -> IO ()
go =
              forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \Int
n Ptr e
p ->
              forall a b c d x. (a -> b -> c -> d -> x) -> a -> b -> c -> d -> x
Strict.arguments4 forall a b. (a -> b) -> a -> b
$ \Ptr a
pa Ptr b
pb Ptr c
pc Ptr d
pd ->
              forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
nforall a. Ord a => a -> a -> Bool
>Int
0) forall a b. (a -> b) -> a -> b
$
                 forall (m :: * -> *) a1 a2 a3 a4 r.
Monad m =>
(a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r
liftM4 a -> b -> c -> d -> e
f (forall a. Storable a => Ptr a -> IO a
St.peek Ptr a
pa) (forall a. Storable a => Ptr a -> IO a
St.peek Ptr b
pb) (forall a. Storable a => Ptr a -> IO a
St.peek Ptr c
pc) (forall a. Storable a => Ptr a -> IO a
St.peek Ptr d
pd) forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall a. Storable a => Ptr a -> a -> IO ()
St.poke Ptr e
p forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
                 Int -> Ptr e -> Ptr a -> Ptr b -> Ptr c -> Ptr d -> IO ()
go (Int -> Int
pred Int
n) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr e
p) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr a
pa) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr b
pb) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr c
pc) (forall a. Storable a => Ptr a -> Ptr a
incPtr Ptr d
pd)
       in  Int -> Ptr e -> Ptr a -> Ptr b -> Ptr c -> Ptr d -> IO ()
go Int
len Ptr e
p0 Ptr a
pa0 Ptr b
pb0 Ptr c
pc0 Ptr d
pd0
{-# INLINE zipWith4 #-}

-- | /O(n)/ 'unzip' transforms a list of pairs of elements into a pair of
-- 'Vector's. Note that this performs two 'pack' operations.
unzip :: (Storable a, Storable b) => [(a, b)] -> (Vector a, Vector b)
unzip :: forall a b.
(Storable a, Storable b) =>
[(a, b)] -> (Vector a, Vector b)
unzip [(a, b)]
ls = (forall a. Storable a => [a] -> Vector a
pack (forall a b. (a -> b) -> [a] -> [b]
P.map forall a b. (a, b) -> a
fst [(a, b)]
ls), forall a. Storable a => [a] -> Vector a
pack (forall a b. (a -> b) -> [a] -> [b]
P.map forall a b. (a, b) -> b
snd [(a, b)]
ls))
{-# INLINE unzip #-}

-- ---------------------------------------------------------------------
-- Interleaved 'Vector's

-- | /O(l/n)/ 'sieve' selects every 'n'th element.
sieve :: (Storable a) => Int -> Vector a -> Vector a
sieve :: forall a. Storable a => Int -> Vector a -> Vector a
sieve Int
n Vector a
xs =
   case forall a. Ord a => a -> a -> Ordering
P.compare Int
n Int
1 of
      Ordering
P.LT -> forall a. (?callStack::CallStack) => String -> a
error String
"sieve: non-positive step size"
      Ordering
P.EQ -> Vector a
xs
      Ordering
P.GT -> forall a. Storable a => Int -> Vector a -> Vector a
sieveCore Int
n Vector a
xs

sieveCore :: (Storable a) => Int -> Vector a -> Vector a
sieveCore :: forall a. Storable a => Int -> Vector a -> Vector a
sieveCore Int
n (SV ForeignPtr a
fp Int
s Int
l) =
   let end :: Int
end = Int
sforall a. Num a => a -> a -> a
+Int
l
   in  forall a b. (a, b) -> a
fst forall a b. (a -> b) -> a -> b
$
       forall b a.
Storable b =>
Int -> (a -> Maybe (b, a)) -> a -> (Vector b, Maybe a)
unfoldrN (- forall a. Integral a => a -> a -> a
div (-Int
l) Int
n)
          (forall a x. (a -> x) -> a -> x
Strict.arguments1 forall a b. (a -> b) -> a -> b
$ \Int
k0 ->
              do forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Int
k0forall a. Ord a => a -> a -> Bool
<Int
end)
                 forall a. a -> Maybe a
Just (forall a. Storable a => ForeignPtr a -> Int -> a
foreignPeek ForeignPtr a
fp Int
k0, Int
k0 forall a. Num a => a -> a -> a
+ Int
n))
          Int
s
{-# INLINE sieve #-}

-- | /O(n)/
-- Returns n sieved vectors with successive starting elements.
-- @deinterleave 3 (pack ['a'..'k']) = [pack "adgj", pack "behk", pack "cfi"]@
-- This is the same as 'Data.List.HT.sliceHorizontal'.
deinterleave :: (Storable a) => Int -> Vector a -> [Vector a]
deinterleave :: forall a. Storable a => Int -> Vector a -> [Vector a]
deinterleave Int
n =
   forall a b. (a -> b) -> [a] -> [b]
P.map (forall a. Storable a => Int -> Vector a -> Vector a
sieve Int
n) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Int -> [a] -> [a]
P.take Int
n forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. (a -> a) -> a -> [a]
P.iterate forall a. Storable a => Vector a -> Vector a
laxTail

-- | /O(n)/
-- Almost the inverse of deinterleave.
-- Restriction is that all input vector must have equal length.
-- @interleave [pack "adgj", pack "behk", pack "cfil"] = pack ['a'..'l']@
interleave :: (Storable a) => [Vector a] -> Vector a
interleave :: forall a. Storable a => [Vector a] -> Vector a
interleave [] = forall a. Storable a => Vector a
empty
interleave [Vector a
xs] = Vector a
xs
interleave [Vector a]
vs =
   forall a. IO a -> a
Unsafe.performIO forall a b. (a -> b) -> a -> b
$
   forall {k} (r :: k) (m :: k -> *) a.
ContT r m a -> (a -> m r) -> m r
MC.runContT
      (do
         [(Ptr a, Int)]
pls <- forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (\Vector a
v -> forall {k} (r :: k) (m :: k -> *) a.
((a -> m r) -> m r) -> ContT r m a
MC.ContT (forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr Vector a
v forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c. ((a, b) -> c) -> a -> b -> c
curry)) [Vector a]
vs
         let ([Ptr a]
ps,[Int]
ls) = forall a b. [(a, b)] -> ([a], [b])
P.unzip [(Ptr a, Int)]
pls
         Ptr (Ptr a)
ptrs <- forall {k} (r :: k) (m :: k -> *) a.
((a -> m r) -> m r) -> ContT r m a
MC.ContT (forall a b. Storable a => [a] -> (Ptr a -> IO b) -> IO b
withArray [Ptr a]
ps)
         if forall (t :: * -> *). Foldable t => t Bool -> Bool
and (forall a b. (a -> a -> b) -> [a] -> [b]
ListHT.mapAdjacent forall a. Eq a => a -> a -> Bool
(==) [Int]
ls)
           then forall (m :: * -> *) a. Monad m => a -> m a
return (Ptr (Ptr a)
ptrs, forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
P.sum [Int]
ls)
           else forall a. String -> String -> a
moduleError String
"interleave" String
"all input vectors must have the same length")
      (\(Ptr (Ptr a)
ptrs, Int
totalLength) -> forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create Int
totalLength forall a b. (a -> b) -> a -> b
$ \Ptr a
p ->
         let len :: Int
len = forall (t :: * -> *) a. Foldable t => t a -> Int
P.length [Vector a]
vs
             go :: Int -> IO ()
go = forall a x. (a -> x) -> a -> x
Strict.arguments1 forall a b. (a -> b) -> a -> b
$ \Int
m ->
                forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
m forall a. Ord a => a -> a -> Bool
< Int
totalLength) forall a b. (a -> b) -> a -> b
$ do
                   {-
                   divMod would be more correct,
                   but is slower on the architectures I know
                   -}
                   let (Int
j,Int
k) = forall a. Integral a => a -> a -> (a, a)
P.quotRem Int
m Int
len
                   forall a. Storable a => Ptr a -> Int -> a -> IO ()
pokeElemOff Ptr a
p Int
m forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< forall a b c. (a -> b -> c) -> b -> a -> c
flip forall a. Storable a => Ptr a -> Int -> IO a
peekElemOff Int
j forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< forall a. Storable a => Ptr a -> Int -> IO a
peekElemOff Ptr (Ptr a)
ptrs Int
k
                   Int -> IO ()
go forall a b. (a -> b) -> a -> b
$ Int -> Int
succ Int
m
         in  Int -> IO ()
go Int
0)
{-# INLINE interleave #-}


-- ---------------------------------------------------------------------
-- Special lists

-- | /O(n)/ Return all initial segments of the given 'Vector', shortest first.
inits :: (Storable a) => Vector a -> [Vector a]
inits :: forall a. Storable a => Vector a -> [Vector a]
inits (SV ForeignPtr a
x Int
s Int
l) = forall a b. (a -> b) -> [a] -> [b]
List.map (forall a. ForeignPtr a -> Int -> Int -> Vector a
SV ForeignPtr a
x Int
s) [Int
0..Int
l]

-- | /O(n)/ Return all final segments of the given 'Vector', longest first.
tails :: (Storable a) => Vector a -> [Vector a]
tails :: forall a. Storable a => Vector a -> [Vector a]
tails Vector a
p =
   forall a b.
Storable a =>
b -> (a -> Vector a -> b) -> Vector a -> b
switchL [forall a. Storable a => Vector a
empty] (\ a
_ Vector a
t -> Vector a
p forall a. a -> [a] -> [a]
: forall a. Storable a => Vector a -> [Vector a]
tails Vector a
t) Vector a
p

-- ---------------------------------------------------------------------
-- ** Ordered 'Vector's

-- ---------------------------------------------------------------------
-- Low level constructors

-- | /O(n)/ Make a copy of the 'Vector' with its own storage.
--   This is mainly useful to allow the rest of the data pointed
--   to by the 'Vector' to be garbage collected, for example
--   if a large string has been read in, and only a small part of it
--   is needed in the rest of the program.
copy :: (Storable a) => Vector a -> Vector a
copy :: forall a. Storable a => Vector a -> Vector a
copy Vector a
v =
   forall a b. Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr Vector a
v forall a b. (a -> b) -> a -> b
$ \Ptr a
f Int
l ->
   forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create Int
l forall a b. (a -> b) -> a -> b
$ \Ptr a
p ->
   forall a. Storable a => Ptr a -> Ptr a -> Int -> IO ()
copyArray Ptr a
p Ptr a
f (forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
l)



-- ---------------------------------------------------------------------
-- IO

-- | Write a 'Vector' to a contiguous piece of memory.
poke :: (Storable a) => Ptr a -> Vector a -> IO ()
poke :: forall a. Storable a => Ptr a -> Vector a -> IO ()
poke Ptr a
dst Vector a
v =
   forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr Vector a
v forall a b. (a -> b) -> a -> b
$ \Ptr a
src Int
len -> forall a. Storable a => Ptr a -> Ptr a -> Int -> IO ()
copyArray Ptr a
dst Ptr a
src Int
len

-- | Read a 'Vector' from a contiguous piece of memory.
peek :: (Storable a) => Int -> Ptr a -> IO (Vector a)
peek :: forall a. Storable a => Int -> Ptr a -> IO (Vector a)
peek Int
len Ptr a
src =
   forall a. Storable a => Int -> (Ptr a -> IO ()) -> IO (Vector a)
create Int
len forall a b. (a -> b) -> a -> b
$ \Ptr a
dst -> forall a. Storable a => Ptr a -> Ptr a -> Int -> IO ()
copyArray Ptr a
dst Ptr a
src Int
len

-- | Outputs a 'Vector' to the specified 'Handle'.
hPut :: (Storable a) => Handle -> Vector a -> IO ()
hPut :: forall a. Storable a => Handle -> Vector a -> IO ()
hPut Handle
h Vector a
v =
   forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (forall a. Vector a -> Bool
null Vector a
v)) forall a b. (a -> b) -> a -> b
$
      forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr Vector a
v forall a b. (a -> b) -> a -> b
$ \ Ptr a
ptrS Int
l ->
         let ptrE :: Ptr a
ptrE = forall a. Storable a => Ptr a -> Int -> Ptr a
advancePtr Ptr a
ptrS Int
l
             -- use advancePtr and minusPtr in order to respect alignment
         in  forall a. Handle -> Ptr a -> Int -> IO ()
hPutBuf Handle
h Ptr a
ptrS (forall a b. Ptr a -> Ptr b -> Int
minusPtr Ptr a
ptrE Ptr a
ptrS)

-- | Read a 'Vector' directly from the specified 'Handle'.  This
-- is far more efficient than reading the characters into a list
-- and then using 'pack'.
--
hGet :: (Storable a) => Handle -> Int -> IO (Vector a)
hGet :: forall a. Storable a => Handle -> Int -> IO (Vector a)
hGet Handle
_ Int
0 = forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Storable a => Vector a
empty
hGet Handle
h Int
l =
   forall a. Storable a => Int -> (Ptr a -> IO Int) -> IO (Vector a)
createAndTrim Int
l forall a b. (a -> b) -> a -> b
$ \Ptr a
p ->
      let elemType :: Ptr a -> a
          elemType :: forall a. Ptr a -> a
elemType Ptr a
_ = forall a. (?callStack::CallStack) => a
undefined
          roundUp :: a -> a -> a
roundUp a
m a
n = a
n forall a. Num a => a -> a -> a
+ forall a. Integral a => a -> a -> a
mod (-a
n) a
m
          sizeOfElem :: Int
sizeOfElem =
             forall a. Integral a => a -> a -> a
roundUp
                (forall a. Storable a => a -> Int
alignment (forall a. Ptr a -> a
elemType Ptr a
p))
                (forall a. Storable a => a -> Int
sizeOf (forall a. Ptr a -> a
elemType Ptr a
p))
      in  forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (forall a b c. (a -> b -> c) -> b -> a -> c
flip forall a. Integral a => a -> a -> a
div Int
sizeOfElem) forall a b. (a -> b) -> a -> b
$
          forall a. Handle -> Ptr a -> Int -> IO Int
hGetBuf Handle
h Ptr a
p (Int
l forall a. Num a => a -> a -> a
* Int
sizeOfElem)
{-
   createAndTrim l $ \p ->
      fmap (flip div (incPtr p `minusPtr` p)) $
      hGetBuf h p (advancePtr p l `minusPtr` p)
-}

-- | Read an entire file strictly into a 'Vector'.  This is far more
-- efficient than reading the characters into a 'String' and then using
-- 'pack'.  It also may be more efficient than opening the file and
-- reading it using hGet. Files are read using 'binary mode' on Windows.
--
readFile :: (Storable a) => FilePath -> IO (Vector a)
readFile :: forall a. Storable a => String -> IO (Vector a)
readFile String
f =
   forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket (String -> IOMode -> IO Handle
openBinaryFile String
f IOMode
ReadMode) Handle -> IO ()
hClose
      (\Handle
h -> forall a. Storable a => Handle -> Int -> IO (Vector a)
hGet Handle
h forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (Integral a, Num b) => a -> b
fromIntegral forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Handle -> IO Integer
hFileSize Handle
h)

-- | Write a 'Vector' to a file.
writeFile :: (Storable a) => FilePath -> Vector a -> IO ()
writeFile :: forall a. Storable a => String -> Vector a -> IO ()
writeFile String
f Vector a
txt =
   forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket (String -> IOMode -> IO Handle
openBinaryFile String
f IOMode
WriteMode) Handle -> IO ()
hClose
      (\Handle
h -> forall a. Storable a => Handle -> Vector a -> IO ()
hPut Handle
h Vector a
txt)

-- | Append a 'Vector' to a file.
appendFile :: (Storable a) => FilePath -> Vector a -> IO ()
appendFile :: forall a. Storable a => String -> Vector a -> IO ()
appendFile String
f Vector a
txt =
   forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket (String -> IOMode -> IO Handle
openBinaryFile String
f IOMode
AppendMode) Handle -> IO ()
hClose
      (\Handle
h -> forall a. Storable a => Handle -> Vector a -> IO ()
hPut Handle
h Vector a
txt)


-- ---------------------------------------------------------------------
-- Internal utilities


-- These definitions of succ and pred do not check for overflow
-- and are faster than their counterparts from Enum class.
succ :: Int -> Int
succ :: Int -> Int
succ Int
n = Int
nforall a. Num a => a -> a -> a
+Int
1
{-# INLINE succ #-}

pred :: Int -> Int
pred :: Int -> Int
pred Int
n = Int
nforall a. Num a => a -> a -> a
-Int
1
{-# INLINE pred #-}

unsafeWithStartPtr :: Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr :: forall a b. Storable a => Vector a -> (Ptr a -> Int -> IO b) -> b
unsafeWithStartPtr Vector a
v Ptr a -> Int -> IO b
f =
   forall a. IO a -> a
Unsafe.performIO (forall a b.
Storable a =>
Vector a -> (Ptr a -> Int -> IO b) -> IO b
withStartPtr Vector a
v Ptr a -> Int -> IO b
f)
{-# INLINE unsafeWithStartPtr #-}

foreignPeek :: Storable a => ForeignPtr a -> Int -> a
foreignPeek :: forall a. Storable a => ForeignPtr a -> Int -> a
foreignPeek ForeignPtr a
fp Int
k =
   forall a. IO a -> a
inlinePerformIO forall a b. (a -> b) -> a -> b
$ forall a b. ForeignPtr a -> (Ptr a -> IO b) -> IO b
withForeignPtr ForeignPtr a
fp forall a b. (a -> b) -> a -> b
$ forall a b c. (a -> b -> c) -> b -> a -> c
flip forall a. Storable a => Ptr a -> Int -> IO a
peekElemOff Int
k
{-# INLINE foreignPeek #-}

withNonEmptyVector ::
   String -> (ForeignPtr a -> Int -> Int -> b) -> Vector a -> b
withNonEmptyVector :: forall a b.
String -> (ForeignPtr a -> Int -> Int -> b) -> Vector a -> b
withNonEmptyVector String
fun ForeignPtr a -> Int -> Int -> b
f (SV ForeignPtr a
x Int
s Int
l) =
   if Int
l forall a. Ord a => a -> a -> Bool
<= Int
0
     then forall a. String -> a
errorEmpty String
fun
     else ForeignPtr a -> Int -> Int -> b
f ForeignPtr a
x Int
s Int
l
{-# INLINE withNonEmptyVector #-}

-- Common up near identical calls to `error' to reduce the number
-- constant strings created when compiled:
errorEmpty :: String -> a
errorEmpty :: forall a. String -> a
errorEmpty String
fun = forall a. String -> String -> a
moduleError String
fun String
"empty Vector"
{-# NOINLINE errorEmpty #-}

moduleError :: String -> String -> a
moduleError :: forall a. String -> String -> a
moduleError String
fun String
msg = forall a. (?callStack::CallStack) => String -> a
error (String
"Data.StorableVector." forall a. [a] -> [a] -> [a]
++ String
fun forall a. [a] -> [a] -> [a]
++ Char
':'forall a. a -> [a] -> [a]
:Char
' 'forall a. a -> [a] -> [a]
:String
msg)
{-# NOINLINE moduleError #-}

-- Find from the end of the string using predicate
findFromEndUntil :: (Storable a) => (a -> Bool) -> Vector a -> Int
findFromEndUntil :: forall a. Storable a => (a -> Bool) -> Vector a -> Int
findFromEndUntil = forall a b x. (a -> b -> x) -> a -> b -> x
Strict.arguments2 forall a b. (a -> b) -> a -> b
$ \a -> Bool
f ps :: Vector a
ps@(SV ForeignPtr a
x Int
s Int
l) ->
    if forall a. Vector a -> Bool
null Vector a
ps then Int
0
    else if a -> Bool
f (forall a. Storable a => Vector a -> a
last Vector a
ps) then Int
l
         else forall a. Storable a => (a -> Bool) -> Vector a -> Int
findFromEndUntil a -> Bool
f (forall a. ForeignPtr a -> Int -> Int -> Vector a
SV ForeignPtr a
x Int
s (Int
lforall a. Num a => a -> a -> a
-Int
1))