{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Text.RE.ZeInternals.Types.CaptureID where
import qualified Data.HashMap.Strict as HMS
import Data.Hashable
import Data.Ix
import qualified Data.Text as T
data CaptureID
= IsCaptureOrdinal CaptureOrdinal
| IsCaptureName CaptureName
deriving (Show,Ord,Eq)
type CaptureNames = HMS.HashMap CaptureName CaptureOrdinal
noCaptureNames :: CaptureNames
noCaptureNames = HMS.empty
newtype CaptureName = CaptureName { getCaptureName :: T.Text }
deriving (Show,Ord,Eq)
instance Hashable CaptureName where
hashWithSalt i = hashWithSalt i . getCaptureName
newtype CaptureOrdinal = CaptureOrdinal { getCaptureOrdinal :: Int }
deriving (Show,Ord,Eq,Enum,Ix,Num)
findCaptureID :: CaptureID -> CaptureNames -> Either String CaptureOrdinal
findCaptureID (IsCaptureOrdinal o) _ = Right o
findCaptureID (IsCaptureName n) hms =
maybe oops Right $ HMS.lookup n hms
where
oops = Left $ unlines $
("lookupCaptureID: " ++ T.unpack t ++ " not found in:") :
[ " "++T.unpack (getCaptureName nm) | nm <- HMS.keys hms ]
t = getCaptureName n