{-# Language TypeFamilies #-}
module Data.Source.ByteString.Lazy.Char8.Offset where
import Data.Char
import Data.Source.Class
import qualified Data.ByteString.Lazy as B

data Src
 = Src
 { loc :: Int
 , str :: B.ByteString
 } deriving (Eq,Ord,Show,Read)

mkSrc :: B.ByteString -> Src
mkSrc = Src 0

instance Source Src where
 type Location  Src = Int
 type Element   Src = Char
 type Token     Src = B.ByteString
 type Error     Src = ()
 offset = loc
 uncons (Src loc bs) 
        = Right $ B.uncons bs >>= \(w,t) ->
           let ch = chr $ fromIntegral w
           in return (ch, Src (loc+1) t)
 view   (Src loc bs) _ eh nh 
        = case B.uncons bs of
           Nothing      -> eh
           Just (w,t)  ->       let ch = chr $ fromIntegral w
                                in nh ch $ Src (loc+1) t
 location (Src ofs _) 
        = ofs
 token (Src lloc lbs) (Src rloc _)
        = B.take (fromIntegral $ rloc - lloc) lbs

