Data.Hashable

hashable-1.2.5.0: A class for types that can be converted to a hash value

Copyright | (c) Milan Straka 2010 (c) Johan Tibell 2011 (c) Bryan O'Sullivan 2011, 2012
License | BSD-style
Maintainer | johan.tibell@gmail.com
Stability | provisional
Portability | portable
Safe Haskell | Trustworthy
Language | Haskell98

Data.Hashable

Contents

- Hashing and security
- Computing hash values
- Creating new instances
  - Generic instances
    - Understanding a compiler error
  - Writing instances by hand
    - Hashing contructors with multiple fields
    - Hashing types with multiple constructors
- Caching hashes

Description

This module defines a class, `Hashable`, for types that can be converted to a hash value. This class exists for the benefit of hashing-based data structures. The module provides instances for most standard types. Efficient instances for other types can be generated automatically and effortlessly using the generics support in GHC 7.2 and above.

The easiest way to get started is to use the `hash` function. Here is an example session with `ghci`.

    ghci> import Data.Hashable
    ghci> hash "foo"
    60853164

Synopsis

- class Hashable a where
- hashUsing :: Hashable b => (a -> b) -> Int -> a -> Int
- hashPtr :: Ptr a -> Int -> IO Int
- hashPtrWithSalt :: Ptr a -> Int -> Int -> IO Int
- hashByteArray :: ByteArray# -> Int -> Int -> Int
- hashByteArrayWithSalt :: ByteArray# -> Int -> Int -> Int -> Int
- data Hashed a
- hashed :: Hashable a => a -> Hashed a
- unhashed :: Hashed a -> a
- mapHashed :: Hashable b => (a -> b) -> Hashed a -> Hashed b
- traverseHashed :: (Hashable b, Functor f) => (a -> f b) -> Hashed a -> f (Hashed b)

# Hashing and security

Applications that use hash-based data structures to store input from untrusted users can be susceptible to "hash DoS", a class of denial-of-service attack that uses deliberately chosen colliding inputs to force an application into unexpectedly behaving with quadratic time complexity.

At this time, the string hashing functions used in this library are susceptible to such attacks and users are recommended to either use a `Map` to store keys derived from untrusted input or to use a hash function (e.g. SipHash) that's resistant to such attacks. A future version of this library might ship with such hash functions.

# Computing hash values

class Hashable a where #

The class of types that can be converted to a hash value.

Minimal implementation: `hashWithSalt`.

Methods

hashWithSalt :: Int -> a -> Int infixl 0 #

Return a hash value for the argument, using the given salt.

The general contract of `hashWithSalt` is:

- If two values are equal according to the `==` method, then applying the `hashWithSalt` method on each of the two values must produce the same integer result if the same salt is used in each case.
- It is not required that if two values are unequal according to the `==` method, then applying the `hashWithSalt` method on each of the two values must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal values may improve the performance of hashing-based data structures.
- This method can be used to compute different hash values for the same input by providing a different salt in each application of the method. This implies that any instance that defines `hashWithSalt` must make use of the salt in its implementation.

hash :: a -> Int #

Like `hashWithSalt`, but no salt is used. The default implementation uses `hashWithSalt` with some default salt. Instances might want to implement this method to provide a more efficient implementation than the default implementation.

hashWithSalt :: (Generic a, GHashable Zero (Rep a)) => Int -> a -> Int infixl 0 #

Return a hash value for the argument, using the given salt.

The general contract of `hashWithSalt` is:

- If two values are equal according to the `==` method, then applying the `hashWithSalt` method on each of the two values must produce the same integer result if the same salt is used in each case.
- It is not required that if two values are unequal according to the `==` method, then applying the `hashWithSalt` method on each of the two values must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal values may improve the performance of hashing-based data structures.
- This method can be used to compute different hash values for the same input by providing a different salt in each application of the method. This implies that any instance that defines `hashWithSalt` must make use of the salt in its implementation.

Instances

Hashable Bool # |
Methods hashWithSalt :: Int -> Bool -> Int # hash :: Bool -> Int #
Hashable Char # |
Methods hashWithSalt :: Int -> Char -> Int # hash :: Char -> Int #
Hashable Double # |
Methods hashWithSalt :: Int -> Double -> Int # hash :: Double -> Int #
Hashable Float # |
Methods hashWithSalt :: Int -> Float -> Int # hash :: Float -> Int #
Hashable Int # |
Methods hashWithSalt :: Int -> Int -> Int # hash :: Int -> Int #
Hashable Int8 # |
Methods hashWithSalt :: Int -> Int8 -> Int # hash :: Int8 -> Int #
Hashable Int16 # |
Methods hashWithSalt :: Int -> Int16 -> Int # hash :: Int16 -> Int #
Hashable Int32 # |
Methods hashWithSalt :: Int -> Int32 -> Int # hash :: Int32 -> Int #
Hashable Int64 # |
Methods hashWithSalt :: Int -> Int64 -> Int # hash :: Int64 -> Int #
Hashable Integer # |
Methods hashWithSalt :: Int -> Integer -> Int # hash :: Integer -> Int #
Hashable Ordering # |
Methods hashWithSalt :: Int -> Ordering -> Int # hash :: Ordering -> Int #
Hashable Word # |
Methods hashWithSalt :: Int -> Word -> Int # hash :: Word -> Int #
Hashable Word8 # |
Methods hashWithSalt :: Int -> Word8 -> Int # hash :: Word8 -> Int #
Hashable Word16 # |
Methods hashWithSalt :: Int -> Word16 -> Int # hash :: Word16 -> Int #
Hashable Word32 # |
Methods hashWithSalt :: Int -> Word32 -> Int # hash :: Word32 -> Int #
Hashable Word64 # |
Methods hashWithSalt :: Int -> Word64 -> Int # hash :: Word64 -> Int #
Hashable TypeRep # |
Methods hashWithSalt :: Int -> TypeRep -> Int # hash :: TypeRep -> Int #
Hashable () # |
Methods hashWithSalt :: Int -> () -> Int # hash :: () -> Int #
Hashable BigNat # |
Methods hashWithSalt :: Int -> BigNat -> Int # hash :: BigNat -> Int #
Hashable Natural # |
Methods hashWithSalt :: Int -> Natural -> Int # hash :: Natural -> Int #
Hashable Void # |
Methods hashWithSalt :: Int -> Void -> Int # hash :: Void -> Int #
Hashable Version # |
Methods hashWithSalt :: Int -> Version -> Int # hash :: Version -> Int #
Hashable Unique # |
Methods hashWithSalt :: Int -> Unique -> Int # hash :: Unique -> Int #
Hashable ThreadId # |
Methods hashWithSalt :: Int -> ThreadId -> Int # hash :: ThreadId -> Int #
Hashable WordPtr # |
Methods hashWithSalt :: Int -> WordPtr -> Int # hash :: WordPtr -> Int #
Hashable IntPtr # |
Methods hashWithSalt :: Int -> IntPtr -> Int # hash :: IntPtr -> Int #
Hashable ShortByteString # |
Methods hashWithSalt :: Int -> ShortByteString -> Int # hash :: ShortByteString -> Int #
Hashable ByteString # |
Methods hashWithSalt :: Int -> ByteString -> Int # hash :: ByteString -> Int #
Hashable ByteString # |
Methods hashWithSalt :: Int -> ByteString -> Int # hash :: ByteString -> Int #
Hashable Text # |
Methods hashWithSalt :: Int -> Text -> Int # hash :: Text -> Int #
Hashable Text # |
Methods hashWithSalt :: Int -> Text -> Int # hash :: Text -> Int #
Hashable a => Hashable [a] # |
Methods hashWithSalt :: Int -> [a] -> Int # hash :: [a] -> Int #
Hashable a => Hashable (Maybe a) # |
Methods hashWithSalt :: Int -> Maybe a -> Int # hash :: Maybe a -> Int #
Hashable a => Hashable (Ratio a) # |
Methods hashWithSalt :: Int -> Ratio a -> Int # hash :: Ratio a -> Int #
Hashable (Ptr a) # |
Methods hashWithSalt :: Int -> Ptr a -> Int # hash :: Ptr a -> Int #
Hashable (FunPtr a) # |
Methods hashWithSalt :: Int -> FunPtr a -> Int # hash :: FunPtr a -> Int #
Hashable a => Hashable (Identity a) # |
Methods hashWithSalt :: Int -> Identity a -> Int # hash :: Identity a -> Int #
Hashable a => Hashable (Min a) # |
Methods hashWithSalt :: Int -> Min a -> Int # hash :: Min a -> Int #
Hashable a => Hashable (Max a) # |
Methods hashWithSalt :: Int -> Max a -> Int # hash :: Max a -> Int #
Hashable a => Hashable (First a) # |
Methods hashWithSalt :: Int -> First a -> Int # hash :: First a -> Int #
Hashable a => Hashable (Last a) # |
Methods hashWithSalt :: Int -> Last a -> Int # hash :: Last a -> Int #
Hashable a => Hashable (WrappedMonoid a) # |
Methods hashWithSalt :: Int -> WrappedMonoid a -> Int # hash :: WrappedMonoid a -> Int #
Hashable a => Hashable (Option a) # |
Methods hashWithSalt :: Int -> Option a -> Int # hash :: Option a -> Int #
Hashable a => Hashable (NonEmpty a) # |
Methods hashWithSalt :: Int -> NonEmpty a -> Int # hash :: NonEmpty a -> Int #
Hashable (Fixed a) # |
Methods hashWithSalt :: Int -> Fixed a -> Int # hash :: Fixed a -> Int #
Hashable (StableName a) # |
Methods hashWithSalt :: Int -> StableName a -> Int # hash :: StableName a -> Int #
Hashable (Hashed a) # |
Methods hashWithSalt :: Int -> Hashed a -> Int # hash :: Hashed a -> Int #
(Hashable a, Hashable b) => Hashable (Either a b) # |
Methods hashWithSalt :: Int -> Either a b -> Int # hash :: Either a b -> Int #
(Hashable a1, Hashable a2) => Hashable (a1, a2) # |
Methods hashWithSalt :: Int -> (a1, a2) -> Int # hash :: (a1, a2) -> Int #
(Hashable a, Hashable b) => Hashable (Arg a b) # |
Methods hashWithSalt :: Int -> Arg a b -> Int # hash :: Arg a b -> Int #
Hashable (Proxy * a) # |
Methods hashWithSalt :: Int -> Proxy * a -> Int # hash :: Proxy * a -> Int #
(Hashable a1, Hashable a2, Hashable a3) => Hashable (a1, a2, a3) # |
Methods hashWithSalt :: Int -> (a1, a2, a3) -> Int # hash :: (a1, a2, a3) -> Int #
Hashable a => Hashable (Const * a b) # |
Methods hashWithSalt :: Int -> Const * a b -> Int # hash :: Const * a b -> Int #
(Hashable a1, Hashable a2, Hashable a3, Hashable a4) => Hashable (a1, a2, a3, a4) # |
Methods hashWithSalt :: Int -> (a1, a2, a3, a4) -> Int # hash :: (a1, a2, a3, a4) -> Int #
(Hashable1 f, Hashable1 g, Hashable a) => Hashable (Sum * f g a) # |
Methods hashWithSalt :: Int -> Sum * f g a -> Int # hash :: Sum * f g a -> Int #
(Hashable1 f, Hashable1 g, Hashable a) => Hashable (Product * f g a) # |
Methods hashWithSalt :: Int -> Product * f g a -> Int # hash :: Product * f g a -> Int #
(Hashable a1, Hashable a2, Hashable a3, Hashable a4, Hashable a5) => Hashable (a1, a2, a3, a4, a5) # |
Methods hashWithSalt :: Int -> (a1, a2, a3, a4, a5) -> Int # hash :: (a1, a2, a3, a4, a5) -> Int #
(Hashable1 f, Hashable1 g, Hashable a) => Hashable (Compose * * f g a) # | In general, `hash (Compose x) ≠ hash x`. However, `hashWithSalt` satisfies its variant of this equivalence.
Methods hashWithSalt :: Int -> Compose * * f g a -> Int # hash :: Compose * * f g a -> Int #
(Hashable a1, Hashable a2, Hashable a3, Hashable a4, Hashable a5, Hashable a6) => Hashable (a1, a2, a3, a4, a5, a6) # |
Methods hashWithSalt :: Int -> (a1, a2, a3, a4, a5, a6) -> Int # hash :: (a1, a2, a3, a4, a5, a6) -> Int #
(Hashable a1, Hashable a2, Hashable a3, Hashable a4, Hashable a5, Hashable a6, Hashable a7) => Hashable (a1, a2, a3, a4, a5, a6, a7) # |
Methods hashWithSalt :: Int -> (a1, a2, a3, a4, a5, a6, a7) -> Int # hash :: (a1, a2, a3, a4, a5, a6, a7) -> Int #

# Creating new instances

There are two ways to create new instances: by deriving instances automatically using GHC's generic programming support or by writing instances manually.

## Generic instances

Beginning with GHC 7.2, the recommended way to make instances of `Hashable` for most types is to use the compiler's support for automatically generating default instances.

    {-# LANGUAGE DeriveGeneric #-}

    import GHC.Generics (Generic)
    import Data.Hashable

    data Foo a = Foo a String
                 deriving (Eq, Generic)

    instance Hashable a => Hashable (Foo a)

    data Colour = Red | Green | Blue
                  deriving Generic

    instance Hashable Colour

If you omit a body for the instance declaration, GHC will generate a default instance that correctly and efficiently hashes every constructor and parameter.

### Understanding a compiler error

Suppose you intend to use the generic machinery to automatically generate a `Hashable` instance.

    data Oops = Oops
         -- forgot to add "deriving Generic" here!

    instance Hashable Oops

And imagine that, as in the example above, you forget to add a "`deriving `Generic``" clause to your data type. At compile time, you will get an error message from GHC that begins roughly as follows:

    No instance for (GHashable (Rep Oops))

This error can be confusing, as `GHashable` is not exported (it is an internal typeclass used by this library's generics machinery). The correct fix is simply to add the missing "`deriving `Generic``".

## Writing instances by hand

To maintain high quality hashes, new `Hashable` instances should be built using existing `Hashable` instances, combinators, and hash functions.

The functions below can be used when creating new instances of `Hashable`. For example, for many string-like types the `hashWithSalt` method can be defined in terms of either `hashPtrWithSalt` or `hashByteArrayWithSalt`. Here's how you could implement an instance for the `ByteString` data type, from the `bytestring` package:

    import qualified Data.ByteString as B
    import qualified Data.ByteString.Internal as B
    import qualified Data.ByteString.Unsafe as B
    import Data.Hashable
    import Foreign.Ptr (castPtr)

    instance Hashable B.ByteString where
        hashWithSalt salt bs = B.inlinePerformIO $
                               B.unsafeUseAsCStringLen bs $ \(p, len) ->
                               hashPtrWithSalt p (fromIntegral len) salt

### Hashing contructors with multiple fields

Hash constructors with multiple fields by chaining `hashWithSalt`:

    data Date = Date Int Int Int

    instance Hashable Date where
        hashWithSalt s (Date yr mo dy) =
            s `hashWithSalt`
            yr `hashWithSalt`
            mo `hashWithSalt` dy

If you need to chain hashes together, use `hashWithSalt` and follow this recipe:

    combineTwo h1 h2 = h1 `hashWithSalt` h2

### Hashing types with multiple constructors

For a type with several value constructors, there are a few possible approaches to writing a `Hashable` instance.

If the type is an instance of `Enum`, the easiest path is to convert it to an `Int`, and use the existing `Hashable` instance for `Int`.

    data Color = Red | Green | Blue
                 deriving Enum

    instance Hashable Color where
        hashWithSalt = hashUsing fromEnum

If the type's constructors accept parameters, it is important to distinguish the constructors. To distinguish the constructors, add a different integer to the hash computation of each constructor:

    data Time = Days Int
              | Weeks Int
              | Months Int

    instance Hashable Time where
        hashWithSalt s (Days n)   = s `hashWithSalt`
                                    (0::Int) `hashWithSalt` n
        hashWithSalt s (Weeks n)  = s `hashWithSalt`
                                    (1::Int) `hashWithSalt` n
        hashWithSalt s (Months n) = s `hashWithSalt`
                                    (2::Int) `hashWithSalt` n

hashUsing #

Arguments

:: Hashable b |
=> (a -> b) | Transformation function.
-> Int | Salt.
-> a | Value to transform.
-> Int |

Transform a value into a `Hashable` value, then hash the transformed value using the given salt.

This is a useful shorthand in cases where a type can easily be mapped to another type that is already an instance of `Hashable`. Example:

    data Foo = Foo | Bar
             deriving (Enum)

    instance Hashable Foo where
        hashWithSalt = hashUsing fromEnum

hashPtr #

Arguments

:: Ptr a | pointer to the data to hash
-> Int | length, in bytes
-> IO Int | hash value

Compute a hash value for the content of this pointer.

hashPtrWithSalt #

Arguments

:: Ptr a | pointer to the data to hash
-> Int | length, in bytes
-> Int | salt
-> IO Int | hash value

Compute a hash value for the content of this pointer, using an initial salt.

This function can for example be used to hash non-contiguous segments of memory as if they were one contiguous segment, by using the output of one hash as the salt for the next.

hashByteArray #

Arguments

:: ByteArray# | data to hash
-> Int | offset, in bytes
-> Int | length, in bytes
-> Int | hash value

Compute a hash value for the content of this `ByteArray#`, beginning at the specified offset, using specified number of bytes.

hashByteArrayWithSalt #

Arguments

:: ByteArray# | data to hash
-> Int | offset, in bytes
-> Int | length, in bytes
-> Int | salt
-> Int | hash value

Compute a hash value for the content of this `ByteArray#`, using an initial salt.

This function can for example be used to hash non-contiguous segments of memory as if they were one contiguous segment, by using the output of one hash as the salt for the next.

# Caching hashes

data Hashed a #

A hashable value along with the result of the `hash` function.

Instances

Foldable Hashed # |
Methods fold :: Monoid m => Hashed m -> m # foldMap :: Monoid m => (a -> m) -> Hashed a -> m # foldr :: (a -> b -> b) -> b -> Hashed a -> b # foldr' :: (a -> b -> b) -> b -> Hashed a -> b # foldl :: (b -> a -> b) -> b -> Hashed a -> b # foldl' :: (b -> a -> b) -> b -> Hashed a -> b # foldr1 :: (a -> a -> a) -> Hashed a -> a # foldl1 :: (a -> a -> a) -> Hashed a -> a # toList :: Hashed a -> [a] # null :: Hashed a -> Bool # length :: Hashed a -> Int # elem :: Eq a => a -> Hashed a -> Bool # maximum :: Ord a => Hashed a -> a # minimum :: Ord a => Hashed a -> a # sum :: Num a => Hashed a -> a # product :: Num a => Hashed a -> a #
Eq1 Hashed # |
Methods liftEq :: (a -> b -> Bool) -> Hashed a -> Hashed b -> Bool #
Ord1 Hashed # |
Methods liftCompare :: (a -> b -> Ordering) -> Hashed a -> Hashed b -> Ordering #
Show1 Hashed # |
Methods liftShowsPrec :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> Int -> Hashed a -> ShowS # liftShowList :: (Int -> a -> ShowS) -> ([a] -> ShowS) -> [Hashed a] -> ShowS #
Hashable1 Hashed # |
Methods liftHashWithSalt :: (Int -> a -> Int) -> Int -> Hashed a -> Int #
Eq a => Eq (Hashed a) # | Uses precomputed hash to detect inequality faster
Methods (==) :: Hashed a -> Hashed a -> Bool # (/=) :: Hashed a -> Hashed a -> Bool #
Ord a => Ord (Hashed a) # |
Methods compare :: Hashed a -> Hashed a -> Ordering # (<) :: Hashed a -> Hashed a -> Bool # (<=) :: Hashed a -> Hashed a -> Bool # (>) :: Hashed a -> Hashed a -> Bool # (>=) :: Hashed a -> Hashed a -> Bool # max :: Hashed a -> Hashed a -> Hashed a # min :: Hashed a -> Hashed a -> Hashed a #
Show a => Show (Hashed a) # |
Methods showsPrec :: Int -> Hashed a -> ShowS # show :: Hashed a -> String # showList :: [Hashed a] -> ShowS #
(IsString a, Hashable a) => IsString (Hashed a) # |
Methods fromString :: String -> Hashed a #
Hashable (Hashed a) # |
Methods hashWithSalt :: Int -> Hashed a -> Int # hash :: Hashed a -> Int #

hashed :: Hashable a => a -> Hashed a #

Wrap a hashable value, caching the `hash` function result.

unhashed :: Hashed a -> a #

Unwrap hashed value.

mapHashed :: Hashable b => (a -> b) -> Hashed a -> Hashed b #

`Hashed` cannot be `Functor`

traverseHashed :: (Hashable b, Functor f) => (a -> f b) -> Hashed a -> f (Hashed b) #

`Hashed` cannot be `Traversable`