on master help sign in
Implement roundUpToPower2

Fix for 64 bits word Fix review comments Fix review cooment

commit03efde25ceb71849e52f7a791a9e138b75d27208 authorRanjeet Kumar Ranjan <ranjeetr@composewell.com> dateMon 27 Dec 2021, 20:56 (5 years ago) parent77998d1
1 file changed+17−4
src/Streamly/Internal/Data/Array/Foreign/Mut/Type.hs+17−4
src/Streamly/Internal/Data/Array/Foreign/Mut/Type.hs+17−4
@@ -195,6 +195,7 @@ module Streamly.Internal.Data.Array.Foreign.Mut.Type
195195 -- , appendSliceFrom
196196
197197 -- * Utilities
198+ , roundUpToPower2
198199 , memcpy
199200 , memcmp
200201 , c_memchr
@@ -202,6 +203,7 @@ module Streamly.Internal.Data.Array.Foreign.Mut.Type
202203where
203204
204205#include "inline.hs"
206+#include "MachDeps.h"
205207
206208#ifdef USE_C_MALLOC
207209#define USE_FOREIGN_PTR
@@ -211,7 +213,7 @@ import Control.Exception (assert)
211213import Control.DeepSeq (NFData(..))
212214import Control.Monad (when, void)
213215import Control.Monad.IO.Class (MonadIO(..))
214−import Data.Bits ((.&.))
216+import Data.Bits (shiftR, (.|.), (.&.))
215217#if __GLASGOW_HASKELL__ < 808
216218import Data.Semigroup (Semigroup(..))
217219#endif
@@ -687,10 +689,21 @@ roundUpLargeArray size =
687689 ((size + blockSize - 1) .&. negate blockSize)
688690 else size
689691
690−{-
691692roundUpToPower2 :: Int -> Int
692−roundUpToPower2 = undefined
693−-}
693+roundUpToPower2 x =
694+#if WORD_SIZE_IN_BITS == 64
695+ 1 + z6
696+#else
697+ 1 + z5
698+#endif
699+ where
700+ z = x - 1
701+ z1 = z .|. z `shiftR` 1
702+ z2 = z1 .|. z1 `shiftR` 2
703+ z3 = z2 .|. z2 `shiftR` 4
704+ z4 = z3 .|. z3 `shiftR` 8
705+ z5 = z4 .|. z4 `shiftR` 16
706+ z6 = z5 .|. z5 `shiftR` 32
694707
695708-- | @allocBytesToBytes elem allocatedBytes@ returns the array size in bytes
696709-- such that the real allocation is less than or equal to @allocatedBytes@,