Skip to content

Commit 627d48b

Browse files
committed
Use O(n) ghc-bignum Addr primitives for big Integer and Natural
Previously, putBigInteger/getBigInteger and putBigNatural/getBigNatural used O(n^2) byte-by-byte shiftR/shiftL via unroll/roll and an intermediate [Word8] list, taking 95.9 ms and 4.0 GB of allocation to decode a single 64 KB Integer. On GHC >= 9.0 (base >= 4.15, ghc-bignum), use integerSizeInBase#/ integerToAddr/integerFromAddr and naturalSizeInBase#/naturalToAddr/ naturalFromAddr with little-endian flag 0# (matching the exact little-endian wire format of unroll/roll), keeping unroll/roll as the portable fallback for older GHC / MicroHs. Safety of unsafe operations (documented inline in Class.hs): - BI.unsafeCreate: an = abs n (or n for Natural) is strictly positive on the big-int path, and len = integerSizeInBase# 256## an (or naturalSizeInBase# 256## n) is the exact byte count written by integerToAddr / naturalToAddr into the freshly allocated len-byte buffer. - unsafeDupablePerformIO + BU.unsafeUseAsCString: bs is an immutable ByteString of exact length n > 0 (guaranteed by getByteString n), kept alive across the call by unsafeUseAsCString's withForeignPtr; integerFromAddr / naturalFromAddr only performs a pure, idempotent read of those n bytes (does not mutate or require a NUL terminator). Also document the unsafeChr safety proof inline above getChr. Object size (GHC 9.10.3 -O2): - Get Main.o: 589,536 B -> 589,472 B ( -64 B, -0.0%) - Put Main.o: 303,736 B -> 304,200 B ( +464 B, +0.2%) - Data/Binary/Class.o: 758,680 B -> 755,856 B (-2,824 B, -0.4%) - Wasm.o / Pcap.o / Bencode.o: unchanged (0.0%) Benchmarks (GHC 9.10.3, +RTS -T): - Get Integer/decode (64 KB): 95.9 ms (4.0 GB alloc, 2.2 GB peak) -> 4.36 us (65 KB alloc, 20 MB peak) (~22,000x faster, ~61,500x less alloc) - Put [big Integer] (10k): 1.30 ms (12 MB) -> 1.23 ms (6.1 MB) (-49% alloc) - Get [small Integer] (10k): 122 us (1.3 MB) -> 113 us (1.3 MB) - Get [small Natural] (10k): 130 us (1.4 MB) -> 131 us (1.4 MB) Add QuickCheck properties prop_big_integer_wire_format and prop_big_natural_wire_format verifying bit-for-bit wire-format equivalence with unroll and roundtrip decoding (240/240 QC properties passing). Assisted-By: Antigravity (Gemini 4)
1 parent f6f1e0c commit 627d48b

2 files changed

Lines changed: 123 additions & 0 deletions

File tree

‎src/Data/Binary/Class.hs‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@
1515
{-# LANGUAGE MultiWayIf #-}
1616
#endif
1717

18+
#if defined(__GLASGOW_HASKELL__) && MIN_VERSION_base(4,15,0)
19+
{-# LANGUAGE MagicHash #-}
20+
#define HAS_GHC_BIGNUM
21+
#endif
22+
1823
#if MIN_VERSION_base(4,16,0)
1924
#define HAS_TYPELITS_CHAR
2025
#endif
@@ -100,7 +105,16 @@ import qualified Data.ByteString.Lazy as L
100105
import qualified Data.ByteString.Builder.Prim as Prim
101106
#endif
102107

108+
#ifdef HAS_GHC_BIGNUM
109+
import qualified Data.ByteString.Internal as BI
110+
import qualified Data.ByteString.Unsafe as BU
111+
import GHC.Exts (Ptr(..), Word(..))
112+
import GHC.Num.Integer (integerFromAddr, integerSizeInBase#, integerToAddr)
113+
import GHC.Num.Natural (naturalFromAddr, naturalSizeInBase#, naturalToAddr)
114+
import System.IO.Unsafe (unsafeDupablePerformIO)
115+
#else
103116
import Data.List (unfoldr)
117+
#endif
104118
import qualified Data.List as List
105119

106120
-- And needed for the instances:
@@ -426,15 +440,57 @@ instance Binary Integer where
426440
_ -> fail ("Data.Binary.get @Integer: invalid tag " ++ show tag)
427441

428442
putBigInteger :: Integer -> Put
443+
#ifdef HAS_GHC_BIGNUM
444+
putBigInteger n =
445+
putWord8 1
446+
<> putWord8 sign
447+
<> put len
448+
-- Safety of unsafeCreate: an = abs n is strictly positive (n is outside
449+
-- Int32), and len = integerSizeInBase# 256## an is the exact byte count
450+
-- that integerToAddr writes into the freshly allocated len-byte buffer.
451+
<> putByteString (BI.unsafeCreate len $ \(Ptr addr#) ->
452+
void (integerToAddr an addr# 0#))
453+
where
454+
an = abs n
455+
sign = if n < 0 then 255 else 1 :: Word8
456+
len = fromIntegral (W# (integerSizeInBase# 256## an)) :: Int
457+
#else
429458
putBigInteger n =
430459
putWord8 1
431460
<> put sign
432461
<> put (unroll (abs n)) -- unroll the bytes
433462
where
434463
sign = fromIntegral (signum n) :: Word8
464+
#endif
435465
{-# NOINLINE putBigInteger #-}
436466

437467
getBigInteger :: Get Integer
468+
#ifdef HAS_GHC_BIGNUM
469+
getBigInteger = do
470+
sign <- getWord8
471+
n <- get :: Get Int
472+
if n < 0
473+
then fail "Data.Binary.get @Integer: negative length"
474+
else do
475+
bs <- getByteString n
476+
-- Safety of unsafeDupablePerformIO + unsafeUseAsCString:
477+
-- 1. bs is an immutable ByteString of exact length n > 0 (guaranteed by
478+
-- getByteString n), and integerFromAddr only reads those n bytes
479+
-- (does not mutate or rely on a NUL terminator).
480+
-- 2. unsafeUseAsCString wraps withForeignPtr, keeping bs alive for the
481+
-- duration of integerFromAddr.
482+
-- 3. The read is pure and idempotent, so duplication is safe.
483+
let v = if n == 0
484+
then 0
485+
else unsafeDupablePerformIO $
486+
BU.unsafeUseAsCString bs $ \(Ptr addr#) ->
487+
case fromIntegral n of
488+
W# w# -> integerFromAddr w# addr# 0#
489+
case sign of
490+
1 -> return $! v
491+
255 -> return $! - v
492+
_ -> fail ("Data.Binary.get @Integer: invalid sign " ++ show sign)
493+
#else
438494
getBigInteger = do
439495
sign <- get :: Get Word8
440496
bytes <- get
@@ -443,6 +499,7 @@ getBigInteger = do
443499
1 -> return $! v
444500
255 -> return $! - v
445501
_ -> fail ("Data.Binary.get @Integer: invalid sign " ++ show sign)
502+
#endif
446503
{-# NOINLINE getBigInteger #-}
447504

448505
-- | @since 0.8.0.0
@@ -455,6 +512,7 @@ instance forall a. Fixed.HasResolution a => Binary (Fixed.Fixed a) where
455512
get = (\x -> fromInteger x / fromInteger (Fixed.resolution (undefined :: Maybe a))) `liftM` get
456513
#endif
457514

515+
#ifndef HAS_GHC_BIGNUM
458516
--
459517
-- Fold and unfold an Integer to and from a list of its bytes
460518
--
@@ -468,6 +526,7 @@ roll :: (Integral a, Bits a) => [Word8] -> a
468526
roll = foldl' unstep 0 . reverse
469527
where
470528
unstep a b = a `shiftL` 8 .|. fromIntegral b
529+
#endif
471530

472531
#ifdef HAS_NATURAL
473532
-- Fixed-size type for a subset of Natural
@@ -497,15 +556,47 @@ instance Binary Natural where
497556
_ -> fail ("Data.Binary.get @Natural: invalid tag " ++ show tag)
498557

499558
putBigNatural :: Natural -> Put
559+
#ifdef HAS_GHC_BIGNUM
560+
putBigNatural n =
561+
putWord8 1
562+
<> put len
563+
-- Safety of unsafeCreate: n > maxBound @Word64 so n > 0, and
564+
-- len = naturalSizeInBase# 256## n is the exact byte count that
565+
-- naturalToAddr writes into the freshly allocated len-byte buffer.
566+
<> putByteString (BI.unsafeCreate len $ \(Ptr addr#) ->
567+
void (naturalToAddr n addr# 0#))
568+
where
569+
len = fromIntegral (W# (naturalSizeInBase# 256## n)) :: Int
570+
#else
500571
putBigNatural n =
501572
putWord8 1
502573
<> put (unroll (abs n)) -- unroll the bytes
574+
#endif
503575
{-# NOINLINE putBigNatural #-}
504576

505577
getBigNatural :: Get Natural
578+
#ifdef HAS_GHC_BIGNUM
579+
getBigNatural = do
580+
n <- get :: Get Int
581+
if n < 0
582+
then fail "Data.Binary.get @Natural: negative length"
583+
else if n == 0
584+
then return 0
585+
else do
586+
bs <- getByteString n
587+
-- Safety of unsafeDupablePerformIO + unsafeUseAsCString:
588+
-- bs is an immutable ByteString of exact length n > 0, kept alive by
589+
-- unsafeUseAsCString's withForeignPtr, and naturalFromAddr performs
590+
-- a pure, idempotent read of exactly those n bytes (no NUL needed).
591+
return $! unsafeDupablePerformIO $
592+
BU.unsafeUseAsCString bs $ \(Ptr addr#) ->
593+
case fromIntegral n of
594+
W# w# -> naturalFromAddr w# addr# 0#
595+
#else
506596
getBigNatural = do
507597
bytes <- get
508598
return $! roll bytes
599+
#endif
509600
{-# NOINLINE getBigNatural #-}
510601
#endif
511602

@@ -634,6 +725,13 @@ getCharMultiByte w =
634725
else invalid -- no continuation byte
635726
{-# NOINLINE getCharMultiByte #-}
636727

728+
-- Safety of unsafeChr: getChr is private to this module and only called from
729+
-- the four WTF-8 branches of Binary Char's get, which statically guarantee
730+
-- 0 <= i <= 0x10ffff:
731+
-- 1-byte (w < 0x80): 0x00000 .. 0x00007f
732+
-- 2-byte (0xc2 <= w <= 0xdf): 0x00080 .. 0x0007ff
733+
-- 3-byte (0xe0 <= w <= 0xef, not < 0x800): 0x00800 .. 0x00ffff
734+
-- 4-byte (0xf0 <= w <= 0xf4, w==0xf4 => x<=0x8f): 0x10000 .. 0x10ffff
637735
getChr :: Int -> Get Char
638736
#ifdef __GLASGOW_HASKELL__
639737
getChr i = pure $! unsafeChr i

‎tests/QC.hs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1006,6 +1006,27 @@ prop_double_wire_format d =
10061006
, encodeFloat (2^(52 :: Int)) 0
10071007
] :: [Double])
10081008

1009+
prop_big_integer_wire_format :: [Word8] -> Bool -> Bool
1010+
prop_big_integer_wire_format ws neg =
1011+
let mag = foldr (\b acc -> acc * 256 + fromIntegral b) (0 :: Integer) ws
1012+
big = (mag + 1) * (2 ^ (32 :: Int)) + 1
1013+
n = if neg then -big else big
1014+
refUnroll 0 = []
1015+
refUnroll i = (fromIntegral (i `mod` 256) :: Word8) : refUnroll (i `div` 256)
1016+
refEnc = runPut (putWord8 1 <> put (fromIntegral (signum n) :: Word8) <> put (refUnroll (abs n)))
1017+
in encode n == refEnc && decode (encode n) == n
1018+
1019+
#ifdef HAS_NATURAL
1020+
prop_big_natural_wire_format :: [Word8] -> Bool
1021+
prop_big_natural_wire_format ws =
1022+
let mag = foldr (\b acc -> acc * 256 + fromIntegral b) (0 :: Natural) ws
1023+
n = (mag + 1) * (2 ^ (64 :: Int)) + 1
1024+
refUnroll 0 = []
1025+
refUnroll i = (fromIntegral (i `mod` 256) :: Word8) : refUnroll (i `div` 256)
1026+
refEnc = runPut (putWord8 1 <> put (refUnroll n))
1027+
in encode n == refEnc && decode (encode n) == n
1028+
#endif
1029+
10091030
genTree :: Gen (Tree.Tree Int8)
10101031
genTree = sized go
10111032
where
@@ -1346,6 +1367,10 @@ tests =
13461367
, testProperty "IntMap negative length" (p prop_intmap_negative_length)
13471368
, testProperty "Float wire format matches decodeFloat" (p prop_float_wire_format)
13481369
, testProperty "Double wire format matches decodeFloat" (p prop_double_wire_format)
1370+
, testProperty "Big Integer wire format and roundtrip" (p prop_big_integer_wire_format)
1371+
#ifdef HAS_NATURAL
1372+
, testProperty "Big Natural wire format and roundtrip" (p prop_big_natural_wire_format)
1373+
#endif
13491374
, -- Arbitrary test input
13501375
let testInput :: [Int] ; testInput = [0 .. 10]
13511376
in testProperty "look-ahead independent of chunking" (p (prop_lookAheadIndepOfChunking testInput))

0 commit comments

Comments
 (0)