summaryrefslogtreecommitdiff
path: root/src/Logstat/Value.hs
blob: ec505d3e6f95fb10b7d5bdd813b16322e70eae85 (plain)
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 OverloadedStrings,FlexibleContexts #-}
module Logstat.Value where

import Control.Monad.Except
import qualified Data.Attoparsec.ByteString.Char8 as A
import qualified Data.ByteString                  as B
import qualified Data.ByteString.Char8            as B8

import Logstat.Types


asBool :: Val -> Bool
asBool (Val b _) = b /= "" && b /= "0"

asBS :: Val -> B.ByteString
asBS (Val b _) = b

asNum :: MonadError EvalError m => Val -> m Double
asNum (Val b n) = maybe (throwError $ Loc Nothing $ InvalidNumber b) return n

-- Constructors are strict in their arguments
bool :: Bool -> Val
bool True = bs "1"
bool False = bs ""

bs :: B.ByteString -> Val
bs s = s `seq` Val s (parseNum s)

num :: Double -> Val
num n = n `seq` Val (fmtNum n) (Just n)


fmtNum :: Double -> B.ByteString
fmtNum v = let v' = B8.pack (show v) in maybe v' id $ B.stripSuffix ".0" v'

parseNum :: B.ByteString -> Maybe Double
parseNum = either (const Nothing) Just . A.parseOnly (A.double <* A.endOfInput)