module Floskell.Buffer
( Buffer
, empty
, newline
, write
, line
, column
, toLazyByteString
) where
import qualified Data.ByteString as BS
import Data.ByteString.Builder ( Builder )
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Lazy as BL
data Buffer =
Buffer { bufferData :: !Builder
, bufferDataNoSpace :: !Builder
, bufferLine :: !Int
, bufferColumn :: !Int
}
empty :: Buffer
empty = Buffer { bufferData = mempty
, bufferDataNoSpace = mempty
, bufferLine = 0
, bufferColumn = 0
}
write :: BS.ByteString -> Buffer -> Buffer
write str buf =
buf { bufferData = newBufferData
, bufferDataNoSpace =
if BS.all (== 32) str then bufferData buf else newBufferData
, bufferColumn = bufferColumn buf + BS.length str
}
where
newBufferData = bufferData buf `mappend` BB.byteString str
newline :: Buffer -> Buffer
newline buf = buf { bufferData = newBufferData
, bufferDataNoSpace = newBufferData
, bufferLine = bufferLine buf + 1
, bufferColumn = 0
}
where
newBufferData = bufferDataNoSpace buf `mappend` BB.char7 '\n'
line :: Buffer -> Int
line = bufferLine
column :: Buffer -> Int
column = bufferColumn
toLazyByteString :: Buffer -> BL.ByteString
toLazyByteString = BB.toLazyByteString . bufferData