{-|
Module      : Htcc.Utils.Text
Description : Utilities
Copyright   : (c) roki, 2019
License     : MIT
Maintainer  : falgon53@yahoo.co.jp
Stability   : experimental
Portability : POSIX

Text utilities
-}
{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}
module Htcc.Utils.Text (
    -- * For Data.Text
    tshow,
    spanLenT,
    subTextIndex
) where

import qualified Data.Text                 as T
import qualified Data.Text.Internal.Search as T
import           Htcc.Utils.Tuple          (second3)
import           Prelude                   hiding (toInteger)

{-# INLINE tshow #-}
-- | Convert `Show` class instance to `Data.Text`.
tshow :: Show a => a -> T.Text
tshow :: a -> Text
tshow = String -> Text
T.pack (String -> Text) -> (a -> String) -> a -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> String
forall a. Show a => a -> String
show

-- | `T.Text` version of the `Htcc.Utils.List.spanLen`.
spanLenT :: (Char -> Bool) -> T.Text -> (Int, T.Text, T.Text)
spanLenT :: (Char -> Bool) -> Text -> (Int, Text, Text)
spanLenT = Int -> (Char -> Bool) -> Text -> (Int, Text, Text)
forall a. Enum a => a -> (Char -> Bool) -> Text -> (a, Text, Text)
spanLenT' 0
    where
        spanLenT' :: a -> (Char -> Bool) -> Text -> (a, Text, Text)
spanLenT' !a
n f :: Char -> Bool
f xs :: Text
xs = case Text -> Maybe (Char, Text)
T.uncons Text
xs of
            Just (x :: Char
x, xs' :: Text
xs')
                | Char -> Bool
f Char
x -> (Text -> Text) -> (a, Text, Text) -> (a, Text, Text)
forall b d a c. (b -> d) -> (a, b, c) -> (a, d, c)
second3 (Char -> Text -> Text
T.cons Char
x) ((a, Text, Text) -> (a, Text, Text))
-> (a, Text, Text) -> (a, Text, Text)
forall a b. (a -> b) -> a -> b
$ a -> (Char -> Bool) -> Text -> (a, Text, Text)
spanLenT' (a -> a
forall a. Enum a => a -> a
succ a
n) Char -> Bool
f Text
xs'
                | Bool
otherwise -> (a
n, Text
T.empty, Text
xs)
            Nothing -> (a
n, Text
T.empty, Text
T.empty)

-- | `subTextIndex` searches text for a substring of text and returns its starting position.
-- If nothing is found, `Nothing` is returned.
subTextIndex :: T.Text -> T.Text -> Maybe Int
subTextIndex :: Text -> Text -> Maybe Int
subTextIndex s :: Text
s t :: Text
t = case Text -> Text -> [Int]
T.indices Text
s Text
t of
    (i :: Int
i:_) -> Int -> Maybe Int
forall a. a -> Maybe a
Just Int
i
    _     -> Maybe Int
forall a. Maybe a
Nothing