Debian Codegraph @

Data/ByteString/Lazy/Progress.hs

raw
1 {-# LANGUAGE ScopedTypeVariables #-}
2 -- |This module defines core functions for tracking the consumption of a
3 -- ByteString, as well as several helper functions for making tracking
4 -- ByteStrings easier.
5 module Data.ByteString.Lazy.Progress(
6 trackProgress
7 , trackProgressWithChunkSize
8 --
9 , trackProgressString
10 , trackProgressStringWithChunkSize
11 --
12 , bytesToUnittedStr
13 )
14 where
15
16 import Control.Applicative ((<$>))
17 import qualified Data.ByteString as BSS
18 import Data.ByteString.Lazy(ByteString)
19 import qualified Data.ByteString.Lazy as BS
20 import Data.Maybe (isJust)
21 import Data.Time.Clock (getCurrentTime,diffUTCTime,UTCTime)
22 import Data.Word (Word64)
23 import System.IO.Unsafe (unsafeInterleaveIO)
24
25 -- |Given a function, return a bytestring that will call that function when it
26 -- is partially consumed. The Words provided to the function will be the number
27 -- of bytes that were just consumed and the total bytes consumed thus far.
28 trackProgress :: (Word64 -> Word64 -> IO ()) ->
29 ByteString ->
30 IO ByteString
31 trackProgress tracker inputBS =
32 BS.fromChunks <$> runTrack 0 (BS.toChunks inputBS)
33 where
34 runTrack _ [] = return []
35 runTrack x (fst:rest) = unsafeInterleaveIO $ do
36 let amtRead = fromIntegral $ BSS.length fst
37 tracker amtRead (x + amtRead)
38 (fst :) <$> runTrack (x + amtRead) rest
39
40 -- |Works like 'trackProgress', except uses fixed-size chunks of the given
41 -- size. Thus, for this function, the first number passed to your function
42 -- will always be the given size *except* for the last call to the function,
43 -- which will be less then or equal to the final size.
44 trackProgressWithChunkSize :: Word64 -> (Word64 -> Word64 -> IO ()) ->
45 ByteString ->
46 IO ByteString
47 trackProgressWithChunkSize chunkSize tracker inputBS = runLoop 0 inputBS
48 where
49 runLoop x bstr | BS.null bstr = return BS.empty
50 | otherwise = unsafeInterleaveIO $ do
51 let (first,rest) = BS.splitAt (fromIntegral chunkSize) bstr
52 amtRead = fromIntegral (BS.length first)
53 tracker amtRead (x + amtRead)
54 (first `BS.append`) <$> runLoop (x + amtRead) rest
55
56 -- |Given a format string (described below), track the progress of a function.
57 -- The argument to the callback will be the string expanded with the given
58 -- progress information.
59 --
60 -- Format string items:
61 --
62 -- * %b is the number of bytes read
63 --
64 -- * %B is the number of bytes read, formatted into a human-readable string
65 --
66 -- * %c is the size of the last chunk read
67 --
68 -- * %C is the size of the last chunk read, formatted human-readably
69 --
70 -- * %r is the rate in bytes per second
71 --
72 -- * %R is the rate, formatted human-readably
73 --
74 -- * %% is the character '%'
75 --
76 -- If you provide a total size (the maybe argument, in bytes), then you may
77 -- also use the following items:
78 --
79 -- * %t is the estimated time to completion in seconds
80 --
81 -- * %T is the estimated time to completion, formatted as HH:MM:SS
82 --
83 -- * %p is the percentage complete
84 --
85 trackProgressString :: String -> Maybe Word64 -> (String -> IO ()) ->
86 IO (ByteString -> IO ByteString)
87 trackProgressString formatStr mTotal tracker = do
88 startTime <- getCurrentTime
89 return (trackProgress (handler startTime))
90 where
91 handler startTime chunkSize total = do
92 now <- getCurrentTime
93 tracker (buildString formatStr startTime now mTotal chunkSize total)
94
95 -- |Exactly as 'trackProgressString', but use the given chunkSize instead
96 -- of the default chunk size.
97 trackProgressStringWithChunkSize :: String -- ^the format string
98 -> Word64 -- ^the chunk size
99 -> Maybe Word64 -- ^total size (opt.)
100 -> (String -> IO ()) -- ^the action
101 -> IO (ByteString -> IO ByteString)
102 trackProgressStringWithChunkSize formatStr chunk mTotal tracker = do
103 startTime <- getCurrentTime
104 return (trackProgressWithChunkSize chunk (handler startTime))
105 where
106 handler startTime chunkSize total = do
107 now <- getCurrentTime
108 tracker (buildString formatStr startTime now mTotal chunkSize total)
109
110 -- build a progress string for trackProgressString et al
111 buildString :: String ->
112 UTCTime -> UTCTime -> Maybe Word64 -> Word64 -> Word64 ->
113 String
114 buildString form startTime curTime mTotal chunkSize amtRead = subPercents form
115 where
116 per_b = show amtRead
117 per_B = bytesToUnittedStr amtRead
118 per_c = show chunkSize
119 per_C = bytesToUnittedStr chunkSize
120 diff = max 1 (round $ toRational $ diffUTCTime curTime startTime)
121 rate = amtRead `div` diff
122 per_r = show rate
123 per_R = bytesToUnittedStr rate ++ "ps"
124 total = case mTotal of
125 Just t -> t
126 Nothing -> error "INTERNAL ERROR (needed total w/ Nothing)"
127 tleft = (total - amtRead) `div` rate
128 per_t = show tleft
129 hLeft = tleft `div` (60 * 60)
130 mLeft = (tleft `div` 60) `mod` 60
131 sLeft = tleft `mod` 60
132 per_T = showPadded hLeft ++ ":" ++ showPadded mLeft ++
133 ":" ++ showPadded sLeft
134 perc = 100 * (fromIntegral amtRead / fromIntegral total) :: Double
135 per_p = show (round perc) ++ "%"
136 oktot = isJust mTotal
137 --
138 subPercents [] = []
139 subPercents ('%':rest) = subPercents' rest
140 subPercents (x:rest) = x : subPercents rest
141 --
142 subPercents' [] = []
143 subPercents' ('b':rest) = per_b ++ subPercents rest
144 subPercents' ('B':rest) = per_B ++ subPercents rest
145 subPercents' ('c':rest) = per_c ++ subPercents rest
146 subPercents' ('C':rest) = per_C ++ subPercents rest
147 subPercents' ('r':rest) = per_r ++ subPercents rest
148 subPercents' ('R':rest) = per_R ++ subPercents rest
149 subPercents' ('t':rest) | oktot = per_t ++ subPercents rest
150 subPercents' ('T':rest) | oktot = per_T ++ subPercents rest
151 subPercents' ('p':rest) | oktot = per_p ++ subPercents rest
152 subPercents' ('%':rest) = "%" ++ subPercents rest
153 subPercents' (x:rest) = '%' : ('x' : subPercents rest)
154
155 -- show a number padded to force at least two digits.
156 showPadded :: Show a => a -> String
157 showPadded x = prefix ++ base
158 where
159 base = show x
160 prefix = case base of
161 [] -> "00"
162 [x] -> "0"
163 _ -> ""
164
165 -- |Convert a number of bytes to a string represenation that uses a reasonable
166 -- unit to make the number human-readable.
167 bytesToUnittedStr :: Word64 -> String
168 bytesToUnittedStr x
169 | x < bk_brk = show x ++ "b"
170 | x < km_brk = showHundredthsDiv x k ++ "k"
171 | x < mg_brk = showHundredthsDiv x m ++ "m"
172 | otherwise = showHundredthsDiv x g ++ "g"
173 where
174 bk_brk = 4096
175 km_brk = 768 * k
176 mg_brk = 768 * m
177 --
178 k = 1024
179 m = 1024 * k
180 g = 1024 * m
181
182 -- Divide the first number by the second, and convert to a string showing two
183 -- decimal places.
184 showHundredthsDiv _ 0 = error "Should never happen!"
185 showHundredthsDiv amt size = show ones ++ "." ++ show tenths ++ show hundreths
186 where
187 divRes :: Double = fromIntegral amt / fromIntegral size
188 divRes100 = round (divRes * 100)
189 ones = divRes100 `div` 100
190 tenths = (divRes100 `div` 10) `mod` 10
191 hundreths = divRes100 `mod` 10
192
193