Skip to content

Commit

Permalink
Add module for encoding integers
Browse files Browse the repository at this point in the history
  • Loading branch information
tibbe committed Mar 29, 2012
1 parent 9098698 commit 643811e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
51 changes: 51 additions & 0 deletions Data/Ceason/Encode.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{-# LANGUAGE MagicHash #-}
module Data.Ceason.Encode
( decimal
) where

import Blaze.ByteString.Builder
import Blaze.ByteString.Builder.Char8
import qualified Data.ByteString as B
import Data.Int
import Data.Monoid
import Data.Word
import GHC.Exts

decimal :: Integral a => a -> B.ByteString
{-# SPECIALIZE decimal :: Int -> B.ByteString #-}
{-# SPECIALIZE decimal :: Int8 -> B.ByteString #-}
{-# SPECIALIZE decimal :: Int16 -> B.ByteString #-}
{-# SPECIALIZE decimal :: Int32 -> B.ByteString #-}
{-# SPECIALIZE decimal :: Int64 -> B.ByteString #-}
{-# SPECIALIZE decimal :: Word -> B.ByteString #-}
{-# SPECIALIZE decimal :: Word8 -> B.ByteString #-}
{-# SPECIALIZE decimal :: Word16 -> B.ByteString #-}
{-# SPECIALIZE decimal :: Word32 -> B.ByteString #-}
{-# SPECIALIZE decimal :: Word64 -> B.ByteString #-}
decimal = toByteString . decimal_

decimal_ :: Integral a => a -> Builder
{-# SPECIALIZE decimal_ :: Int -> Builder #-}
{-# SPECIALIZE decimal_ :: Int8 -> Builder #-}
{-# SPECIALIZE decimal_ :: Int16 -> Builder #-}
{-# SPECIALIZE decimal_ :: Int32 -> Builder #-}
{-# SPECIALIZE decimal_ :: Int64 -> Builder #-}
{-# SPECIALIZE decimal_ :: Word -> Builder #-}
{-# SPECIALIZE decimal_ :: Word8 -> Builder #-}
{-# SPECIALIZE decimal_ :: Word16 -> Builder #-}
{-# SPECIALIZE decimal_ :: Word32 -> Builder #-}
{-# SPECIALIZE decimal_ :: Word64 -> Builder #-}
decimal_ i
| i < 0 = fromChar '-' <> go (-i)
| otherwise = go i
where
go n | n < 10 = digit n
| otherwise = go (n `quot` 10) <> digit (n `rem` 10)

digit :: Integral a => a -> Builder
digit n = fromChar $! i2d (fromIntegral n)
{-# INLINE digit #-}

i2d :: Int -> Char
i2d (I# i#) = C# (chr# (ord# '0'# +# i#))
{-# INLINE i2d #-}
7 changes: 5 additions & 2 deletions ceason.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ Description:
Homepage: https://github.com/tibbe/sea
License: BSD3
License-file: LICENSE
Copyright: (c) 2012 Johan Tibell
(c) 2011 MailRank, Inc.
Author: Johan Tibell
Maintainer: johan.tibell@gmail.com
Category: Text, Web, CSV
Expand All @@ -18,7 +20,8 @@ Library
Exposed-modules: Data.Ceason
Data.Ceason.Types

Other-modules: Data.Ceason.Parser.Internal
Other-modules: Data.Ceason.Encode
Data.Ceason.Parser.Internal

Build-depends: attoparsec,
base,
Expand All @@ -38,4 +41,4 @@ Test-suite unit-tests
HUnit,
test-framework,
test-framework-hunit
hs-source-dirs: tests
hs-source-dirs: tests

0 comments on commit 643811e

Please sign in to comment.