-----------------------------------------------------------------------------
-- |
-- Copyright   :  (C) 2011-2019 Edward Kmett
-- License     :  BSD-style (see the file LICENSE)
--
-- Maintainer  :  Edward Kmett <ekmett@gmail.com>
-- Stability   :  experimental
-- Portability :  non-portable
--
----------------------------------------------------------------------------
module Text.Trifecta.Util.Combinators
  ( argmin
  , argmax
  -- * ByteString conversions
  , fromLazy
  , toLazy
  , takeLine
  , (<$!>)
  ) where

import Data.ByteString      as Strict
import Data.ByteString.Lazy as Lazy

argmin :: Ord b => (a -> b) -> a -> a -> a
argmin :: forall b a. Ord b => (a -> b) -> a -> a -> a
argmin a -> b
f a
a a
b
  | a -> b
f a
a forall a. Ord a => a -> a -> Bool
<= a -> b
f a
b = a
a
  | Bool
otherwise = a
b
{-# INLINE argmin #-}

argmax :: Ord b => (a -> b) -> a -> a -> a
argmax :: forall b a. Ord b => (a -> b) -> a -> a -> a
argmax a -> b
f a
a a
b
  | a -> b
f a
a forall a. Ord a => a -> a -> Bool
> a -> b
f a
b = a
a
  | Bool
otherwise = a
b
{-# INLINE argmax #-}

fromLazy :: Lazy.ByteString -> Strict.ByteString
fromLazy :: ByteString -> ByteString
fromLazy = [ByteString] -> ByteString
Strict.concat forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> [ByteString]
Lazy.toChunks

toLazy :: Strict.ByteString -> Lazy.ByteString
toLazy :: ByteString -> ByteString
toLazy = [ByteString] -> ByteString
Lazy.fromChunks forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (m :: * -> *) a. Monad m => a -> m a
return

takeLine :: Lazy.ByteString -> Lazy.ByteString
takeLine :: ByteString -> ByteString
takeLine ByteString
s = case Word8 -> ByteString -> Maybe Int64
Lazy.elemIndex Word8
10 ByteString
s of
  Just Int64
i -> Int64 -> ByteString -> ByteString
Lazy.take (Int64
i forall a. Num a => a -> a -> a
+ Int64
1) ByteString
s
  Maybe Int64
Nothing -> ByteString
s

infixl 4 <$!>
(<$!>) :: Monad m => (a -> b) -> m a -> m b
a -> b
f <$!> :: forall (m :: * -> *) a b. Monad m => (a -> b) -> m a -> m b
<$!> m a
m = do
  a
a <- m a
m
  forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$! a -> b
f a
a