|
| 1 | +{-# LANGUAGE ScopedTypeVariables #-} |
| 2 | + |
| 3 | +module Tests.Vector.UnitTests (tests) where |
| 4 | + |
| 5 | +import Control.Applicative as Applicative |
| 6 | +import qualified Data.Vector.Storable as Storable |
| 7 | +import Foreign.Ptr |
| 8 | +import Foreign.Storable |
| 9 | +import Text.Printf |
| 10 | + |
| 11 | +import Test.Framework |
| 12 | +import Test.Framework.Providers.HUnit (testCase) |
| 13 | +import Test.HUnit (Assertion, assertBool) |
| 14 | + |
| 15 | +newtype Aligned a = Aligned { getAligned :: a } |
| 16 | + |
| 17 | +instance (Storable a) => Storable (Aligned a) where |
| 18 | + sizeOf _ = sizeOf (undefined :: a) |
| 19 | + alignment _ = 128 |
| 20 | + peek ptr = Aligned Applicative.<$> peek (castPtr ptr) |
| 21 | + poke ptr = poke (castPtr ptr) . getAligned |
| 22 | + |
| 23 | +checkAddressAlignment :: forall a. (Storable a) => Storable.Vector a -> Assertion |
| 24 | +checkAddressAlignment xs = Storable.unsafeWith xs $ \ptr -> do |
| 25 | + let ptr' = ptrToWordPtr ptr |
| 26 | + msg = printf "Expected pointer with alignment %d but got 0x%08x" (toInteger align) (toInteger ptr') |
| 27 | + align :: WordPtr |
| 28 | + align = fromIntegral $ alignment dummy |
| 29 | + assertBool msg $ (ptr' `mod` align) == 0 |
| 30 | + where |
| 31 | + dummy :: a |
| 32 | + dummy = undefined |
| 33 | + |
| 34 | +tests :: [Test] |
| 35 | +tests = |
| 36 | + [ testGroup "Data.Vector.Storable.Vector Alignment" |
| 37 | + [ testCase "Aligned Double" $ |
| 38 | + checkAddressAlignment alignedDoubleVec |
| 39 | + , testCase "Aligned Int" $ |
| 40 | + checkAddressAlignment alignedIntVec |
| 41 | + ] |
| 42 | + ] |
| 43 | + |
| 44 | +alignedDoubleVec :: Storable.Vector (Aligned Double) |
| 45 | +alignedDoubleVec = Storable.fromList $ map Aligned [1, 2, 3, 4, 5] |
| 46 | + |
| 47 | +alignedIntVec :: Storable.Vector (Aligned Int) |
| 48 | +alignedIntVec = Storable.fromList $ map Aligned [1, 2, 3, 4, 5] |
0 commit comments