File: HashTablesSpec.hs

package info (click to toggle)
haskell-vector-hashtables 0.1.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 184 kB
  • sloc: haskell: 1,476; makefile: 3
file content (443 lines) | stat: -rw-r--r-- 15,479 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE DerivingStrategies         #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs               #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE RankNTypes                 #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE StandaloneDeriving         #-}
{-# LANGUAGE TypeApplications           #-}
{-# LANGUAGE TypeFamilies               #-}
module Data.Vector.HashTablesSpec where

import           Control.Monad.Primitive
import           Data.Hashable                   (Hashable (hashWithSalt))
import qualified Data.List                       as L
import           Data.Primitive.MutVar
import           Data.Proxy                      (Proxy (..))
import qualified Data.Set                        as Set
import           Data.Vector.Generic             (Mutable, Vector)
import qualified Data.Vector.Generic             as VI
import           Data.Vector.Generic.Mutable     (MVector)
import qualified Data.Vector.Mutable             as M
import qualified Data.Vector.Storable.Mutable    as SM
import qualified Data.Vector.Unboxed             as U
import qualified Data.Vector.Unboxed.Mutable     as UM
import           GHC.Generics                    (Generic)
import           Test.Hspec.QuickCheck           (modifyMaxSuccess)
import           Test.QuickCheck                 (Arbitrary (..), Gen,
                                                  NonNegative (..),
                                                  Positive (..), Property,
                                                  choose, elements, forAll,
                                                  generate, property, shuffle,
                                                  vector)

import           Test.Hspec                      (Spec, describe, errorCall, it,
                                                  shouldBe, shouldThrow)

import qualified Data.Vector.Hashtables.Internal as VH

newtype AlwaysCollide = AC Int
    deriving newtype (Arbitrary, SM.Storable, Num, Eq, Ord, Show)
    deriving stock Generic

instance Hashable AlwaysCollide where
    hashWithSalt _ _ = 1

listN :: Int -> Gen [(Int, Int)]
listN n = do
  keys <- vector n
  vals <- vector n
  let keys' = Set.toList (Set.fromList keys)
  return (zip keys' vals)

shuffledListN :: Int -> Gen ([(Int, Int)], [(Int, Int)])
shuffledListN n = do
  testData <- listN n
  shuffledTestData <- shuffle testData
  return (testData, shuffledTestData)

listsForRemoveN :: Int -> Gen ([(Int, Int)], [Int])
listsForRemoveN n = do
  testData <- listN n
  dropCount <- min (n - 1) <$> choose (1, n)
  let deleteData = fst <$> take dropCount testData
  return (testData, deleteData)

twoListsN :: Int -> Gen ([(Int, Int)], [(Int, Int)])
twoListsN n = do
  list1 <- listN n
  list2 <- listN n
  return (list1, list2)

spec :: Spec
spec = mutableSpec
  *> storableMutableSpec
  *> storableKeysSpec
  *> unboxedKeysSpec

class HashTableTest ks vs where

  specDescription :: Proxy ks -> Proxy vs -> String

  testInit :: Proxy ks -> Proxy vs -> Int -> IO (VH.Dictionary (PrimState IO) ks Int vs Int)

  testInsert :: (VH.Dictionary (PrimState IO) ks Int vs Int) -> Int -> Int -> IO ()

  testAt :: (VH.Dictionary (PrimState IO) ks Int vs Int) -> Int -> IO Int

  testAt' :: (VH.Dictionary (PrimState IO) ks Int vs Int) -> Int -> IO (Maybe Int)

  testDelete :: (VH.Dictionary (PrimState IO) ks Int vs Int) -> Int -> IO ()

  testInitCollide
    :: Proxy ks
    -> Proxy vs
    -> Int
    -> IO (VH.Dictionary (PrimState IO) ks AlwaysCollide vs Int)

  testInsertCollide
    :: (VH.Dictionary (PrimState IO) ks AlwaysCollide vs Int) -> AlwaysCollide -> Int -> IO ()

  testAtCollide
    :: (VH.Dictionary (PrimState IO) ks AlwaysCollide vs Int) -> AlwaysCollide -> IO Int

  testFromList
    :: Proxy ks -> Proxy vs -> [(Int, Int)] -> IO (VH.Dictionary (PrimState IO) ks Int vs Int)

  testToList :: VH.Dictionary (PrimState IO) ks Int vs Int -> IO [(Int, Int)]

  testLength :: VH.Dictionary (PrimState IO) ks Int vs Int -> IO Int

  testNull :: VH.Dictionary (PrimState IO) ks Int vs Int -> IO Bool

  testMember :: VH.Dictionary (PrimState IO) ks Int vs Int -> Int -> IO Bool

  testAlter :: VH.Dictionary (PrimState IO) ks Int vs Int -> (Maybe Int -> Maybe Int) -> Int -> IO ()

  testUpsert :: VH.Dictionary (PrimState IO) ks Int vs Int -> (Maybe Int -> Int) -> Int -> IO ()

  testUnion
    :: VH.Dictionary (PrimState IO) ks Int vs Int
    -> VH.Dictionary (PrimState IO) ks Int vs Int
    -> IO (VH.Dictionary (PrimState IO) ks Int vs Int)

  testDifference
    :: VH.Dictionary (PrimState IO) ks Int vs Int
    -> VH.Dictionary (PrimState IO) ks Int vs Int
    -> IO (VH.Dictionary (PrimState IO) ks Int vs Int)

  testIntersection
    :: VH.Dictionary (PrimState IO) ks Int vs Int
    -> VH.Dictionary (PrimState IO) ks Int vs Int
    -> IO (VH.Dictionary (PrimState IO) ks Int vs Int)

mkSpec
  :: forall ks vs. (HashTableTest ks vs)
  => Proxy ks -> Proxy vs -> Spec
mkSpec ksp vsp = describe (specDescription ksp vsp) $
    modifyMaxSuccess (const 1000) $ do
      it "lookup for inserted value at specific index returns value" $
        property prop_insertLookup

      it "lookup for inserted value at specific index returns nothing" $
        property prop_insertLookupNothing

      it "lookup for inserted value at specific index throws error" $
        property prop_insertLookupError

      it "lookup for updated value at specific index returns updated value" $
        property prop_insertUpdateLookup

      it "lookup for deleted value at specific index returns nothing" $
        property prop_insertDeleteLookupNothing

      it "lookup for deleted value at specific index throws error" $
        property prop_insertDeleteLookupError

      it "table size increases when multiple elements added" $
        property prop_insertMultipleElements

      it "lookup for inserted value with hash collision returns value" $
        property prop_insertLookupHashCollisions

      it "fromList . toList === id" $ property prop_fromListToList

      it "deleted entries are not present in key-value list after deleting from hashtable" $
        property prop_insertDeleteKeysSize

      it "new table is null" $ property prop_newIsNull

      it "non-empty table is not null" $ property prop_fromListIsNotNull

      it "inserted key is table member" $ property prop_isMember

      it "deleted key is not a member" $ property prop_isNotMember

      it "when altering is nothing - key deleted from table" $ property prop_alterDelete

      it "when altering is just a result - key updated with result" $ property prop_alterUpdate

      it "when upserting a new key - key is set to value" $ property prop_upsertInsert

      it "when upserting an existing key - key updated with result" $ property prop_upsertUpdate

      it "intersection + symmetric difference of two tables is equal to union of two tables" $ property prop_union

  where
    prop_insertLookup
      :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_insertLookup (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht x y
      v <- testAt ht x
      v `shouldBe` y

    prop_insertLookupNothing :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_insertLookupNothing (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht (x + 1) y
      v <- testAt' ht x
      v `shouldBe` Nothing

    prop_insertLookupError :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_insertLookupError (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht (x + 1) y
      testAt ht x `shouldThrow` errorCall "KeyNotFoundException!"

    prop_insertUpdateLookup :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_insertUpdateLookup (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht x y
      testInsert ht x (y + 1)
      v <- testAt ht x
      v `shouldBe` (y + 1)

    prop_insertDeleteLookupNothing :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_insertDeleteLookupNothing (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht x y
      testDelete ht x
      v <- testAt' ht x
      v `shouldBe` Nothing

    prop_insertDeleteLookupError :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_insertDeleteLookupError (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht 0 1
      testDelete ht 0
      testAt ht 0 `shouldThrow` errorCall "KeyNotFoundException!"

    prop_insertMultipleElements
      :: HashTableTest ks vs
      => (NonNegative Int) -> Property
    prop_insertMultipleElements (NonNegative n) = forAll (listN n) $ \xs -> do
      ht <- testInit (Proxy @ks) (Proxy @vs) 2
      mapM_ (uncurry (testInsert ht)) xs
      htl <- testLength ht
      htl `shouldBe` (length . Set.toList . Set.fromList) (fst <$> xs)

    prop_insertLookupHashCollisions
      :: HashTableTest ks vs => (AlwaysCollide, Int) -> (AlwaysCollide, Int) -> IO ()
    prop_insertLookupHashCollisions (x1, y1) (x2, y2) = do
      ht <- testInitCollide (Proxy @ks) (Proxy @vs) 10
      let x2' = if x1 /= x2 then x2 else x2 + 1
      testInsertCollide ht x1 y1
      testInsertCollide ht x2' y2
      v <- testAtCollide ht x1
      v `shouldBe` y1

    prop_fromListToList :: NonNegative Int -> Property
    prop_fromListToList (NonNegative n) = forAll (shuffledListN n) $ \(xs, ys) -> do
      ht <- testFromList (Proxy @ks) (Proxy @vs) xs
      xs' <- testToList ht
      L.sort xs' `shouldBe` L.sort ys

    prop_insertDeleteKeysSize :: NonNegative Int -> Property
    prop_insertDeleteKeysSize (NonNegative n) = forAll (listsForRemoveN n) go
      where
        go (insertData, deleteData) = do
          ht <- testInit (Proxy @ks) (Proxy @vs) 2
          mapM_ (uncurry (testInsert ht)) insertData
          mapM_ (testDelete ht) deleteData
          kvs <- testToList ht
          L.length insertData - L.length deleteData `shouldBe` L.length kvs

    prop_newIsNull :: IO ()
    prop_newIsNull = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 2
      result <- testNull ht
      result `shouldBe` True

    prop_fromListIsNotNull :: Positive Int -> Property
    prop_fromListIsNotNull (Positive n) = forAll (listN n) $ \xs -> do
      ht <- testFromList (Proxy @ks) (Proxy @vs) xs
      result <- testNull ht
      result `shouldBe` False

    prop_isMember :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_isMember (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht x y
      v <- testMember ht x
      v `shouldBe` True

    prop_isNotMember :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_isNotMember (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht x y
      testDelete ht x
      v <- testMember ht x
      v `shouldBe` False

    prop_alterDelete :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_alterDelete (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht x y
      testAlter ht (const Nothing) x
      v <- testMember ht x
      v `shouldBe` False

    prop_alterUpdate :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_alterUpdate (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht x y
      testAlter ht (fmap negate) x
      v <- testAt ht x
      v `shouldBe` (negate y)

    prop_upsertInsert :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_upsertInsert (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testUpsert ht (maybe 0 negate) x
      v <- testAt ht x
      v `shouldBe` 0

    prop_upsertUpdate :: HashTableTest ks vs => (Int, Int) -> IO ()
    prop_upsertUpdate (x, y) = do
      ht <- testInit (Proxy @ks) (Proxy @vs) 10
      testInsert ht x y
      testUpsert ht (maybe 0 negate) x
      v <- testAt ht x
      v `shouldBe` (negate y)

    prop_union :: Positive Int -> Property
    prop_union (Positive n) = forAll (twoListsN n) $ \(xs, ys) -> do
      ht1 <- testFromList (Proxy @ks) (Proxy @vs) xs
      ht2 <- testFromList (Proxy @ks) (Proxy @vs) ys
      u1  <- testUnion ht1 ht2
      d1  <- testDifference ht1 ht2
      d2  <- testDifference ht2 ht1
      i   <- testIntersection ht1 ht2

      res <- do
        u2  <- testUnion d1 d2
        testUnion i u2

      resultList <- testToList res
      unionList  <- testToList u1

      Set.fromList resultList `shouldBe` Set.fromList unionList


instance HashTableTest M.MVector M.MVector where
  specDescription _ _ = "Data.Vector.HashTables.Mutable keys and values"
  testInit _ _ n = VH.initialize n
  testInitCollide _ _ n = VH.initialize n
  testInsert = VH.insert
  testAt = VH.at
  testAt' = VH.at'
  testDelete = VH.delete
  testInsertCollide = VH.insert
  testAtCollide = VH.at
  testLength = VH.length
  testFromList _ _ = VH.fromList
  testToList = VH.toList
  testNull = VH.null
  testMember = VH.member
  testAlter = VH.alter
  testUpsert = VH.upsert
  testUnion = VH.union
  testDifference = VH.difference
  testIntersection = VH.intersection

mutableSpec :: Spec
mutableSpec = mkSpec (Proxy :: Proxy M.MVector) (Proxy :: Proxy M.MVector)


instance HashTableTest SM.MVector SM.MVector where
  specDescription _ _ = "Data.Vector.HashTables.Storable.Mutable keys and values"
  testInit _ _ n = VH.initialize n
  testInitCollide _ _ n = VH.initialize n
  testInsert = VH.insert
  testAt = VH.at
  testAt' = VH.at'
  testDelete = VH.delete
  testInsertCollide = VH.insert
  testAtCollide = VH.at
  testLength = VH.length
  testFromList _ _ = VH.fromList
  testToList = VH.toList
  testNull = VH.null
  testMember = VH.member
  testAlter = VH.alter
  testUpsert = VH.upsert
  testUnion = VH.union
  testDifference = VH.difference
  testIntersection = VH.intersection

storableMutableSpec :: Spec
storableMutableSpec = mkSpec (Proxy @SM.MVector) (Proxy @SM.MVector)


instance HashTableTest SM.MVector M.MVector where
  specDescription _ _ = "Data.Vector.HashTables.Mutable keys and Data.Vector.HashTables.Storable.Mutable values"
  testInit _ _ n = VH.initialize n
  testInitCollide _ _ n = VH.initialize n
  testInsert = VH.insert
  testAt = VH.at
  testAt' = VH.at'
  testDelete = VH.delete
  testInsertCollide = VH.insert
  testAtCollide = VH.at
  testLength = VH.length
  testFromList _ _ = VH.fromList
  testToList = VH.toList
  testNull = VH.null
  testMember = VH.member
  testAlter = VH.alter
  testUpsert = VH.upsert
  testUnion = VH.union
  testDifference = VH.difference
  testIntersection = VH.intersection

storableKeysSpec :: Spec
storableKeysSpec = mkSpec (Proxy @SM.MVector) (Proxy @M.MVector)


instance HashTableTest M.MVector UM.MVector where
  specDescription _ _ = "Data.Vector.HashTables.Mutable keys and Data.Vector.HashTables.Unboxed.Mutable values"
  testInit _ _ n = VH.initialize n
  testInitCollide _ _ n = VH.initialize n
  testInsert = VH.insert
  testAt = VH.at
  testAt' = VH.at'
  testDelete = VH.delete
  testInsertCollide = VH.insert
  testAtCollide = VH.at
  testLength = VH.length
  testFromList _ _ = VH.fromList
  testToList = VH.toList
  testNull = VH.null
  testMember = VH.member
  testAlter = VH.alter
  testUpsert = VH.upsert
  testUnion = VH.union
  testDifference = VH.difference
  testIntersection = VH.intersection

unboxedKeysSpec :: Spec
unboxedKeysSpec = mkSpec (Proxy @M.MVector) (Proxy @UM.MVector)