Skip to content

Commit ab7dad0

Browse files
authored
Merge pull request #4 from well-typed/edsko/niBracket
Add `niBracket`
2 parents f78acc4 + aa1aaae commit ab7dad0

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

niio.cabal

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,18 @@ common lang
2121
ghc-options: -Wall
2222
build-depends: base >= 4.14 && < 4.21
2323

24+
default-extensions:
25+
DeriveFunctor
26+
DerivingStrategies
27+
StandaloneDeriving
28+
2429
library
2530
import: lang
2631
exposed-modules: System.IO.NonInterleaved
2732
hs-source-dirs: src
2833

2934
build-depends:
30-
temporary >= 1.3 && < 1.4
35+
, exceptions >= 0.9 && < 0.11
36+
, temporary >= 1.2.1 && < 1.4
37+
3138

src/System/IO/NonInterleaved.hs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
{-# OPTIONS_GHC -Wno-orphans #-}
2+
13
module System.IO.NonInterleaved (
24
-- * Output functions
35
niPutStr
@@ -9,9 +11,13 @@ module System.IO.NonInterleaved (
911
, niTraceShowId
1012
, niTraceM
1113
, niTraceShowM
14+
-- * Derived functionality
15+
, niBracket
16+
, niBracketLn
1217
) where
1318

1419
import Control.Concurrent
20+
import Control.Monad.Catch (ExitCase(..), generalBracket)
1521
import System.IO
1622
import System.IO.Temp (getCanonicalTemporaryDirectory)
1723
import System.IO.Unsafe
@@ -73,6 +79,32 @@ niTraceM str = niTrace str $ pure ()
7379
niTraceShowM :: (Applicative m, Show a) => a -> m ()
7480
niTraceShowM = niTraceM . show
7581

82+
{-------------------------------------------------------------------------------
83+
Derived functionality
84+
-------------------------------------------------------------------------------}
85+
86+
-- | Print a message before and after an action
87+
--
88+
-- NOTE: We provide an (orphan) 'Functor' instance for 'ExitCase', which can
89+
-- be useful in cases where @a@ is not showable.
90+
niBracket ::
91+
String -- ^ Message to print prior to the action
92+
-> (ExitCase a -> String) -- ^ Message to print after
93+
-> IO a -> IO a
94+
niBracket before after act = fmap (\(a, ()) -> a) $
95+
generalBracket
96+
(niPutStr before)
97+
(\() -> niPutStr . after)
98+
(\() -> act)
99+
100+
-- | Like 'niBracket', but adding linebreaks.
101+
--
102+
-- 'niBracketLn' is to 'niBracket' as 'niPutStrLn' is to 'niPutStr'.
103+
niBracketLn :: String -> (ExitCase a -> String) -> IO a -> IO a
104+
niBracketLn before after = niBracket (before ++ "\n") ((++ "\n") . after)
105+
106+
deriving stock instance Functor ExitCase
107+
76108
{-------------------------------------------------------------------------------
77109
Internal
78110
-------------------------------------------------------------------------------}

0 commit comments

Comments
 (0)