{-# LANGUAGE OverloadedStrings #-}
module Regex.KDE
 (Regex(..), compileRegex, matchRegex, testRegex, isWordChar)
  where

import Regex.KDE.Regex
import Regex.KDE.Compile
import Regex.KDE.Match
import qualified Data.ByteString.UTF8 as U
import qualified Data.IntMap.Strict as M
import qualified Data.ByteString as B
import Data.List (sortOn)

testRegex :: Bool -> String -> String -> Maybe (String, [(Int, String)])
testRegex :: Bool -> String -> String -> Maybe (String, [(Key, String)])
testRegex Bool
caseSensitive String
re String
s =
  let bs :: ByteString
bs = String -> ByteString
U.fromString String
s
      toSlice :: (Key, Key) -> String
toSlice (Key
off,Key
len) = ByteString -> String
U.toString (ByteString -> String) -> ByteString -> String
forall a b. (a -> b) -> a -> b
$ Key -> ByteString -> ByteString
B.take Key
len (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ Key -> ByteString -> ByteString
B.drop Key
off ByteString
bs
   in case Bool -> ByteString -> Either String Regex
compileRegex Bool
caseSensitive (String -> ByteString
U.fromString String
re) of
        Right Regex
r ->
          case Regex -> ByteString -> Maybe (ByteString, IntMap (Key, Key))
matchRegex Regex
r ByteString
bs of
            Maybe (ByteString, IntMap (Key, Key))
Nothing -> Maybe (String, [(Key, String)])
forall a. Maybe a
Nothing
            Just (ByteString
m,IntMap (Key, Key)
cs) -> (String, [(Key, String)]) -> Maybe (String, [(Key, String)])
forall a. a -> Maybe a
Just (ByteString -> String
U.toString ByteString
m, ((Key, String) -> Key) -> [(Key, String)] -> [(Key, String)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Key, String) -> Key
forall a b. (a, b) -> a
fst
                                  (IntMap String -> [(Key, String)]
forall a. IntMap a -> [(Key, a)]
M.toList (((Key, Key) -> String) -> IntMap (Key, Key) -> IntMap String
forall a b. (a -> b) -> IntMap a -> IntMap b
M.map (Key, Key) -> String
toSlice IntMap (Key, Key)
cs)))
        Left String
e  -> String -> Maybe (String, [(Key, String)])
forall a. HasCallStack => String -> a
error String
e