{-# LANGUAGE TypeFamilies, TypeOperators #-}

-- |
-- Module      : Data.Double.Conversion.ByteString
-- Copyright   : (c) 2011 MailRank, Inc.
--
-- License     : BSD-style
-- Maintainer  : bos@serpentine.com
-- Stability   : experimental
-- Portability : GHC
--
-- Fast, efficient support for converting between double precision
-- floating point values and text.
--
-- Although about 15 times faster than plain 'show', these functions
-- are /slower/ than their 'Text' counterparts, at roughly half the
-- speed.  (This seems to be due to the cost of allocating
-- 'ByteString' values via @malloc@.)

module Data.Double.Conversion.Internal.ByteString
    ( convert
    ) where

import Control.Monad (when)
import Data.ByteString.Internal (ByteString(..), mallocByteString)
import Data.Double.Conversion.Internal.FFI (ForeignFloating)
import Data.Word (Word8)
import Foreign.C.Types (CDouble, CFloat, CInt)
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Ptr (Ptr)
import System.IO.Unsafe (unsafePerformIO)

convert :: (RealFloat a, RealFloat b , b ~ ForeignFloating a) => String -> CInt -> (b -> Ptr Word8 -> IO CInt)
        -> a -> ByteString
{-# SPECIALIZE convert :: String -> CInt -> (CDouble -> Ptr Word8 -> IO CInt) -> Double -> ByteString #-}
{-# SPECIALIZE convert :: String -> CInt -> (CFloat -> Ptr Word8 -> IO CInt) -> Float -> ByteString #-}
{-# INLINABLE convert #-}
convert :: forall a b.
(RealFloat a, RealFloat b, b ~ ForeignFloating a) =>
String -> CInt -> (b -> Ptr Word8 -> IO CInt) -> a -> ByteString
convert String
func CInt
len b -> Ptr Word8 -> IO CInt
act a
val = forall a. IO a -> a
unsafePerformIO forall a b. (a -> b) -> a -> b
$ do
  ForeignPtr Word8
fp <- forall a. Int -> IO (ForeignPtr a)
mallocByteString (forall a b. (Integral a, Num b) => a -> b
fromIntegral CInt
len)
  CInt
size <- forall a b. ForeignPtr a -> (Ptr a -> IO b) -> IO b
withForeignPtr ForeignPtr Word8
fp forall a b. (a -> b) -> a -> b
$ b -> Ptr Word8 -> IO CInt
act (forall a b. (Real a, Fractional b) => a -> b
realToFrac a
val)
  forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (CInt
size forall a. Eq a => a -> a -> Bool
== -CInt
1) forall b c a. (b -> c) -> (a -> b) -> a -> c
.
    forall (m :: * -> *) a. MonadFail m => String -> m a
fail forall a b. (a -> b) -> a -> b
$ String
"Data.Double.Conversion.ByteString." forall a. [a] -> [a] -> [a]
++ String
func forall a. [a] -> [a] -> [a]
++
           String
": conversion failed (invalid precision requested)"
  forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ ForeignPtr Word8 -> Int -> Int -> ByteString
PS ForeignPtr Word8
fp Int
0 (forall a b. (Integral a, Num b) => a -> b
fromIntegral CInt
size)