Browse files

Add module for encoding integers

  • Loading branch information...
1 parent 9098698 commit 643811e760a4c1d9a2ffc28d097cf2f42796f70d @tibbe tibbe committed Mar 29, 2012
Showing with 56 additions and 2 deletions.
  1. +51 −0 Data/Ceason/Encode.hs
  2. +5 −2 ceason.cabal
View
51 Data/Ceason/Encode.hs
@@ -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 #-}
View
7 ceason.cabal
@@ -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
@@ -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,
@@ -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.