Skip to content
Browse files

Switch to a salt that changes every time we run

  • Loading branch information...
1 parent c033705 commit 49694d7b95c24b24fc4e1366414a984dde04b2b4 @bos committed
Showing with 28 additions and 1 deletion.
  1. +22 −1 Data/Hashable.hs
  2. +6 −0 hashable.cabal
View
23 Data/Hashable.hs
@@ -1,5 +1,5 @@
{-# LANGUAGE BangPatterns, CPP, ForeignFunctionInterface, MagicHash,
- UnliftedFFITypes #-}
+ ScopedTypeVariables, UnliftedFFITypes #-}
------------------------------------------------------------------------
-- |
@@ -99,6 +99,11 @@ import GHC.Fingerprint.Type(Fingerprint(..))
import Data.Typeable.Internal(TypeRep(..))
#endif
+#ifndef FIXED_SALT
+import Data.Hashable.RandomSource (getRandomBytes_)
+import Foreign.Marshal.Alloc (alloca)
+#endif
+
#include "MachDeps.h"
infixl 0 `combine`, `hashWithSalt`
@@ -109,10 +114,26 @@ infixl 0 `combine`, `hashWithSalt`
-- | A default salt used in the default implementation of 'hashWithSalt'.
-- It is specified by FNV-1 hash as a default salt for hashing string like
-- types.
+--
+-- To reduce the probability of hash collisions, the value of the
+-- default salt will vary from one program invocation to the next
+-- unless this package was compiled with the @fixed-salt@ flag set.
defaultSalt :: Int
+
+#ifdef FIXED_SALT
+
defaultSalt = 2166136261
{-# INLINE defaultSalt #-}
+#else
+
+defaultSalt = unsafePerformIO . alloca $ \(p :: Ptr Int) -> do
+ getRandomBytes_ "defaultSalt" p (sizeOf (undefined :: Int))
+ peek p
+{-# NOINLINE defaultSalt #-}
+
+#endif
+
-- | The class of types that can be converted to a hash value.
--
-- Minimal implementation: 'hash' or 'hashWithSalt'.
View
6 hashable.cabal
@@ -27,6 +27,10 @@ Flag integer-gmp
Description: Are we using integer-gmp to provide fast Integer instances?
Default: True
+Flag fixed-salt
+ Description: Do we use a single fixed salt every time the program runs?
+ Default: False
+
Library
Exposed-modules: Data.Hashable
Data.Hashable.SipHash
@@ -44,6 +48,8 @@ Library
Ghc-options: -Wall
if impl(ghc >= 6.8)
Ghc-options: -fwarn-tabs
+ if flag(fixed-salt)
+ Cpp-options: -DFIXED_SALT
if os(windows)
extra-libraries: advapi32

0 comments on commit 49694d7

Please sign in to comment.
Something went wrong with that request. Please try again.