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 28 29 30 31 32 33 34 35 36 37
|
{-# LANGUAGE BangPatterns #-}
-- | This module defines a type for mutable, string-valued labels.
-- Labels are variable values and can be used to track e.g. the
-- command line arguments or other free-form values. All operations on
-- labels are thread-safe.
module System.Metrics.Label
(
Label
, new
, read
, set
, modify
) where
import Data.IORef (IORef, atomicModifyIORef', atomicWriteIORef, newIORef, readIORef)
import qualified Data.Text as T
import Prelude hiding (read)
-- | A mutable, text-valued label.
newtype Label = C { unC :: IORef T.Text }
-- | Create a new empty label.
new :: IO Label
new = C `fmap` newIORef T.empty
-- | Get the current value of the label.
read :: Label -> IO T.Text
read = readIORef . unC
-- | Set the label to the given value.
set :: Label -> T.Text -> IO ()
set (C ref) !i = atomicWriteIORef ref i
-- | Set the label to the result of applying the given function to the
-- value.
modify :: (T.Text -> T.Text) -> Label -> IO ()
modify f (C ref) = atomicModifyIORef' ref $ \i -> (f i, ())
|