File: Label.hs

package info (click to toggle)
haskell-ekg-core 0.1.1.7-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 140 kB
  • sloc: haskell: 585; ansic: 62; makefile: 2
file content (37 lines) | stat: -rw-r--r-- 1,059 bytes parent folder | download | duplicates (2)
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, ())