summaryrefslogtreecommitdiff
path: root/lib/Graphics/Fountainhead/Compression.hs
blob: c1a05fcd8cc2b4189fccd21b9ecf9016d7ba6ad1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
-- | Font compression and decompression.
module Graphics.Fountainhead.Compression
    ( compress
    , hDecompress
    ) where

import qualified Data.ByteString.Lazy as ByteString.Lazy
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Codec.Compression.Zlib as Zlib
import System.IO (Handle, SeekMode(..), hFileSize, hSeek)

-- | Reads the font from a file handle decompressing it if needed.
hDecompress :: Handle -> IO ByteString
hDecompress fontHandle = do
    firstBytes <- ByteString.unpack <$> ByteString.hGet fontHandle 2
    hSeek fontHandle AbsoluteSeek 0
    fileSize <- fromIntegral <$> hFileSize fontHandle
    case firstBytes of
        0x78 : [secondByte]
            | secondByte `elem` [0x01, 0x9c, 0x5e, 0xda] ->
                ByteString.Lazy.toStrict . Zlib.decompress
                    <$> ByteString.Lazy.hGet fontHandle fileSize
        _ -> ByteString.hGetContents fontHandle

compress :: ByteString -> ByteString
compress = ByteString.Lazy.toStrict . Zlib.compress . ByteString.Lazy.fromStrict