criterion / Criterion / IO.hs

The default branch has multiple heads

{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module      : Criterion.IO
-- Copyright   : (c) 2009, 2010 Bryan O'Sullivan
-- License     : BSD-style
-- Maintainer  :
-- Stability   : experimental
-- Portability : GHC
-- Input and output actions.

module Criterion.IO
    , hGetResults
    , hPutResults
    , readResults
    , writeResults
    ) where

import Criterion.Types (Result(..))
import Data.Binary (Binary(..), encode)
import Data.Binary.Get (runGetOrFail)
import Data.Binary.Put (putByteString, putWord16be, runPut)
import Data.Version (Version(..))
import Paths_criterion (version)
import System.IO (Handle, IOMode(..), withFile)
import qualified Data.ByteString.Lazy as L

header :: L.ByteString
header = runPut $ do
  putByteString "criterio"
  mapM_ (putWord16be . fromIntegral) (versionBranch version)

hGetResults :: Handle -> IO (Either String [Result])
hGetResults handle = do
  bs <- L.hGet handle (fromIntegral (L.length header))
  if bs == header
    then Right `fmap` readAll handle
    else return $ Left "unexpected header"

hPutResults :: Handle -> [Result] -> IO ()
hPutResults handle rs = do
  L.hPut handle header
  mapM_ (L.hPut handle . encode) rs

readResults :: FilePath -> IO (Either String [Result])
readResults path = withFile path ReadMode hGetResults

writeResults :: FilePath -> [Result] -> IO ()
writeResults path rs = withFile path WriteMode (flip hPutResults rs)

readAll :: Binary a => Handle -> IO [a]
readAll handle = do
  let go bs
         | L.null bs = return []
         | otherwise = case runGetOrFail get bs of
                         Left (_, _, err) -> fail err
                         Right (bs', _, a) -> (a:) `fmap` go bs'
  go =<< L.hGetContents handle
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.