-----------------------------------------------------------------------------
-- |
-- 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 :: (a -> b) -> a -> a -> a
argmin a -> b
f a
a a
b
  | a -> b
f a
a b -> b -> Bool
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 :: (a -> b) -> a -> a -> a
argmax a -> b
f a
a a
b
  | a -> b
f a
a b -> b -> Bool
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 ([ByteString] -> ByteString)
-> (ByteString -> [ByteString]) -> ByteString -> ByteString
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 ([ByteString] -> ByteString)
-> (ByteString -> [ByteString]) -> ByteString -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> [ByteString]
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 Int64 -> Int64 -> Int64
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 <$!> :: (a -> b) -> m a -> m b
<$!> m a
m = do
  a
a <- m a
m
  b -> m b
forall (m :: * -> *) a. Monad m => a -> m a
return (b -> m b) -> b -> m b
forall a b. (a -> b) -> a -> b
$! a -> b
f a
a