Skip to content

Commit ed08885

Browse files
specialized maxEncodeLength to Float and Double
also helps prevent future overflow implementation errors for example 128 bit floats
1 parent d8b0506 commit ed08885

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

Data/ByteString/Builder/RealFloat.hs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,7 @@ formatFloating :: forall a mw ew ei.
267267
, R.ExponentBits a
268268
, R.MantissaBits a
269269
, R.CastToWord a
270+
, R.MaxEncodedLength a
270271
-- mantissa
271272
, mw ~ R.MantissaWord a
272273
, R.Mantissa mw

Data/ByteString/Builder/RealFloat/Internal.hs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ module Data.ByteString.Builder.RealFloat.Internal
4444
, trimTrailing
4545
, trimNoTrailing
4646
, closestCorrectlyRounded
47+
, MaxEncodedLength(..)
4748
, toCharsScientific
4849
, asciiRaw
4950
-- hand-rolled division and remainder for f2s and d2s
@@ -228,9 +229,9 @@ instance DecimalLength Word64 where decimalLength = decimalLength17
228229
--
229230
-- floats: 1 (sign) + 9 (mantissa) + 1 (.) + 1 (e) + 3 (exponent) = 15
230231
-- doubles: 1 (sign) + 17 (mantissa) + 1 (.) + 1 (e) + 4 (exponent) = 24
231-
--
232-
maxEncodedLength :: Int
233-
maxEncodedLength = 32
232+
class MaxEncodedLength a where maxEncodedLength :: Int
233+
instance MaxEncodedLength Float where maxEncodedLength = 15
234+
instance MaxEncodedLength Double where maxEncodedLength = 24
234235

235236
-- | Char7 encode a 'String'.
236237
{-# INLINE string7 #-}
@@ -893,13 +894,14 @@ writeSign ptr False s = (# ptr, s #)
893894
{-# SPECIALIZE toCharsScientific :: Proxy Float -> Word8# -> Bool -> Word32 -> Int32 -> BoundedPrim () #-}
894895
{-# SPECIALIZE toCharsScientific :: Proxy Double -> Word8# -> Bool -> Word64 -> Int32 -> BoundedPrim () #-}
895896
toCharsScientific :: forall a mw ei.
896-
( Mantissa mw
897+
( MaxEncodedLength a
898+
, Mantissa mw
897899
, DecimalLength mw
898900
, Integral ei
899901
, ToInt ei
900902
, FromInt ei
901903
) => Proxy a -> Word8# -> Bool -> mw -> ei -> BoundedPrim ()
902-
toCharsScientific _ eE !sign !mantissa !expo = boundedPrim maxEncodedLength $ \_ !(Ptr p0)-> do
904+
toCharsScientific _ eE !sign !mantissa !expo = boundedPrim (maxEncodedLength @a) $ \_ !(Ptr p0)-> do
903905
let !olength@(I# ol) = decimalLength mantissa
904906
!expo' = expo + fromInt olength - 1
905907
IO $ \s1 ->

0 commit comments

Comments
 (0)