[Snapshot of ch25 Bryan O'Sullivan **20080617211101] { adddir ./examples/ch27 adddir ./examples/ch27/BloomFilter adddir ./examples/ch27/cbits addfile ./examples/ch27/BloomFilter/Hash.hs addfile ./examples/ch27/BloomFilter/Mutable.hs addfile ./examples/ch27/cbits/lookup3.c addfile ./examples/ch27/cbits/lookup3.h addfile ./examples/ch27/Setup.lhs addfile ./examples/ch27/rwh-bloomfilter.cabal addfile ./examples/ch27/License.txt adddir ./examples/ch27/configs addfile ./examples/ch27/configs/inconsistent.cabal hunk ./en/Makefile 25 -src-dirs := $(wildcard ../examples/app[A-Z]* ../examples/ch[0-9][0-9]*) +src-dirs := $(wildcard ../examples/app[A-Z]* ../examples/ch[0-9][0-9]* \ + ../examples/ch[0-9]*/*) hunk ./en/Makefile 28 -src-examples := $(foreach d,$(src-dirs),$(wildcard $d/*.c $d/*.cabal $d/*.cpp \ - $d/*.ghci $d/*.hs $d/*.java $d/*.js \ - $d/*.lhs $d/*.py)) +src-patterns := *.[ch] *.cabal *.cpp *.ghci *.hs *.java *.js *.lhs *.py +src-examples := $(foreach d,$(src-dirs),$(foreach p,$(src-patterns), \ + $(wildcard $d/$p $d/*/$p))) hunk ./en/Makefile 228 +examples: $(stamp-examples) + hunk ./en/Makefile 235 +cabal-packages: ../examples/ch27/dist/setup-config + +../examples/ch27/dist/setup-config: + cd ../examples/ch27 && \ + runghc Setup configure --user --prefix=$(HOME) && \ + runghc Setup build && \ + runghc Setup install + hunk ./en/Makefile 271 +vpath %.h $(src-dirs) hunk ./en/Makefile 290 + ../tools/bin/snippets $(CURDIR)/x $< > $@ + +x/.stamp-%.h: %.h + @mkdir -p x hunk ./en/book-shortcuts.xml 78 + hunk ./en/ch13-barcode.xml 242 - It is in fact possible to modify arrays efficiently in - Haskell, but this is a subject that we will have to return - to later. + Don't lose hope + + It is in fact possible to + modify an array efficiently in Haskell, but this is a + subject that we will have to return to later. hunk ./en/ch27-advanced-haskell.xml 4 - Advanced Haskell: MPTCs, TH, strong typing, GADTs + Advanced library design: building a Bloom filter hunk ./en/ch27-advanced-haskell.xml 6 - FIXME + + Introducing the Bloom filter + + A Bloom filter is set-like data structure that is highly + efficient in its use of space. It only supports two operations: + insertion and membership querying. Unlike a normal set data + structure, a Bloom filter can give incorrect answers. If we + query it to see whether an element that we have inserted is + present, it will answer affirmatively. If we query for an + element that we have not inserted, it + might incorrectly claim that the element is + present. + + For many applications, a low rate of false positives is + tolerable. For instance, the job of a network traffic shaper is + to throttle bulk transfers (e.g. BitTorrent) so that interactive + sessions (such as ssh sessions or games) see + good response times. A traffic shaper might use a Bloom filter + to determine whether a particular packet is bulk or interactive. + If it misidentifies one in ten thousand bulk packets as + interactive and fails to throttle it, nobody will notice. + + The attraction of a Bloom filter is its space efficiency. If + we want to build a spell checker, and have a dictionary of half + a million words, a set data structure might consume 20 megabytes + of space. A Bloom filter, in contrast, would consume about half + a megabyte, at the cost of missing perhaps 1% of misspelled + words. + + Behind the scenes, a Bloom filter is remarkably simple. It + consists of a bit array and a handful of hash functions. We'll + use k for the number of hash functions. If + we want to insert a value into the Bloom filter, we compute + k hashes of the value, and turn on those + bits in the bit array. If we want to see whether a value is + present, we compute k hashes, and check all + of those bits in the array to see if they are turned on. + + To see how this works, let's say we want to insert the + strings "foo" and "bar" into a Bloom + filter that is 8 bits wide, and we have two hash + functions. + + + + Compute the two hashes of "foo", and get + the values 1 and 6. + + + Set bits 1 and 6 in the bit + array. + + + Compute the two hashes of "bar", and get + the values 6 and 3. + + + Set bits 6 and 3 in the bit + array. + + + + This example should make it clear why we cannot remove an + element from a Bloom filter: both "foo" and + "bar" resulted in bit 6 being set. + + Suppose we now want to query the Bloom filter, to see + whether the values "quux" and "baz" + are present. + + + + Compute the two hashes of "quux", and get + the values 4 and 0. + + + Check bit 4 in the bit array. It is not + set, so "quux" cannot be present. We do not + need to check bit 0. + + + Compute the two hashes of "baz", and get + the values 1 and 3. + + + Check bit 1 in the bit array. It is + set, as is bit 3, so we say that + "baz" is present even though it is not. We + have reported a false positive. + + + + + + Use cases and package layout + + Not all users of Bloom filters have the same needs. In some + cases, it suffices to create a Bloom filter in one pass, and + only query it afterwards. For other applications, we may need + to continue to update the Bloom filter after we create it. To + accommodate these needs, we will design our library with mutable + and immutable APIs. + + We will segregate the mutable and immutable APIs that we + publish by placing them in different modules: + BloomFilter for the immutable code, and + BloomFilter.Mutable for the mutable code. + + In addition, we will create several helper + modules that won't provide parts of the public API, but will keep + the internal code cleaner. + + Finally, we will ask the user of our API to provide a + function that can generate a number of hashes of an element. + This function will have the type a -> [Word32]. + We will use all of the hashes that this function returns, so the + list must not be infinite! + + + + Basic design + + The data structure that we use for our Haskell Bloom filter + is a direct translation of the simple description we gave + earlier: a bit array and a function that computes hashes. + + &Internal.hs:Bloom; + + When we create our Cabal package, we will not be exporting + this BloomFilter.Internal module. It exists purely + to let us control the visibility of names. We will import + BloomFilter.Internal into both the mutable and + immutable modules, but we will re-export from each module only + the type that is relevant to that module's API. + + + Unboxing, lifting, and bottom + + Unlike other Haskell arrays, a UArray + contains unboxed values. + + For a normal Haskell type, a value can be either fully + evaluated, an unevaluated thunk, or the special value + ⊥, pronounced (and sometimes written) + bottom. The value ⊥ is a placeholder + for a computation that does not succeed. Such a computation + could take any of several forms. It could be an infinite + loop; an application of error; or the + special value undefined. + + A type that can contain ⊥ is referred to as + lifted. All normal Haskell types are + lifted. In practice, this means that we can always write + error "eek!" or undefined in place + of a normal expression. + + This ability to store thunks or ⊥ comes with a + performance cost: it adds an extra layer of indirection. To + see why we need this indirection, consider the + Word32 type. A value of this type is a full 32 + bits wide, so on a 32-bit system, there is no way to directly + encode the value ⊥ within 32 bits. The runtime system + has to maintain, and check, some extra data to track whether + the value is ⊥ or not. + + An unboxed value does away with this indirection. In + doing so, it gains performance, but sacrifices the ability to + represent a thunk or ⊥. Since it can be denser than a + normal Haskell array, an array of unboxed values is an + excellent choice for numeric data and bits. + + + Boxing and lifting + + The counterpart of an unboxed type is a + boxed type, which uses indirection. + All lifted types are boxed, but a few low-level boxed types + are not lifted. For instance, &GHC;'s runtime system has a + low-level array type for which it uses boxing (i.e. it + maintains a pointer to the array). If it has a reference to + such an array, it knows that the array must exist, so it + does not need to account for the possibility of ⊥. + This array type is thus boxed, but not lifted. Boxed but + unlifted types only show up at the lowest level of runtime + hacking. We will never encounter them in normal use. + + + &GHC; implements a UArray of + Bool values by packing eight array elements into + each byte, so this type is perfect for our needs. + + + + + The ST monad + + Back in , we + mentioned that modifying an immutable array is prohibitively + expensive, as it requires copying the entire array. Using a + UArray does not change this, so what can we do to + reduce the cost to bearable levels? + + In an imperative language, we would simply modify the + elements of the array in place; this will be our approach in + Haskell, too. + + Haskell provides a special monad, named + ST + The name ST is an acronym of state + threads. + , which lets us work safely with mutable state. + Compared to the State monad, it has some powerful + added capabilities. + + + + We can thaw an immutable array to + give a mutable array; modify the mutable array in place; and + freeze a new immutable array when we + are done. + + + We have the ability to use mutable + references. This lets us implement data + structures that we can modify after construction, as in an + imperative language. This ability is vital for some + imperative data structures and algorithms, for which + similarly efficient purely functional alternatives have not + yet been discovered. + + + + The IO monad also provides these capabilities. + The major difference between the two is that the ST + monad is intentionally designed so that we can + escape from it back into pure Haskell code. + We enter the ST monad via the execution function + runST, in the same way as for most other + Haskell monads (except IO, of course), and we + escape by returning from runST. + + When we apply a monad's execution function, we expect it to + behave repeatably: given the same body and arguments, we must + get the same results every time. This also applies to + runST. To achieve this repeatability, the + ST monad is more restrictive than the + IO monad. We cannot read or write files, create + global variables, or fork threads. Indeed, although we can + create and work with mutable references and arrays, the type + system prevents them from escaping to the caller of + runST. A mutable array must be frozen into + an immutable array before we can return it, and a mutable + reference cannot escape at all. + + + + + Designing an API for qualified import + + The public interfaces that we provide for working with Bloom + filters are worth a little discussion. + + &Mutable.hs:Mutable; + + We export several names that clash with names exported by + the Prelude. This is deliberate: we expect users of our modules + to import them with qualified names. This reduces the burden on + the memory of our users, as they should already be familiar with + the Prelude's elem, + notElem, and length + functions. + + When we use a module written in this style, we might often + import it with a single-letter prefix, for instance as + import qualified BloomFilter.Mutable as M. This + would allow us to write M.length, which + stays compact and readable. + + Alternatively, we could import the module unqualified, and + import the Prelude while hiding the clashing names with + import Prelude hiding (length). This is much less + useful, as it gives a reader skimming the code no local cue that + they are not actually seeing the Prelude's + length. + + Of course, we seem to be violating this precept in our own + module's header: we import the Prelude, and hide some of the + names it exports. There is a practical reason for this. We + define a function named length. If we + export this from our module without first hiding the Prelude's + length, the compiler will complain that it + cannot tell whether to export our version of + length or the Prelude's. + + While we could export the fully qualified name + BloomFilter.Mutable.length to eliminate the + ambiguity, that seems uglier in this case. This decision has no + consequences for someone using our module, just for ourselves as + the authors of what ought to be a black box, so + there is little chance of confusion here. + + + + Creating a mutable Bloom filter + + We put type declaration for our mutable Bloom filter in the + BloomFilter.Internal module, along with the + immutable Bloom type. + + &Internal.hs:MutBloom; + + The STUArray type gives us a mutable unboxed + array that we can work with in the ST monad. To + create an STUArray, we use the + newArray function. The + new function belongs in the + BloomFilter.Mutable function. + + &Mutable.hs:new; + + Most of the methods of STUArray are actually + implementations of the MArray typeclass, which is + defined in the Data.Array.MArray module. + + Our length function is slightly + complicated by two factors. We are relying on our bit array's + record of its own bounds, and an MArray instance's + getBounds function has a monadic type. We + also have to add one to the answer, as the upper bound of the + array is one less than its actual length. + + &Mutable.hs:length; + + To add an element to the Bloom filter, we set all of the + bits indicated by the hash function. We use the + mod function to ensure that all of the + hashes stay within the bounds of our array, and isolate our code + that computes offsets into the bit array in one function. + + &Mutable.hs:insert; + + Testing for membership is no more difficult. If every bit + indicated by the hash function is set, we consider an element to + be present in the Bloom filter. + + &Mutable.hs:elem; + + We need to write a small supporting function: a monadic + version of all, which we will call + allM. + + &Mutable.hs:allM; + + + + The immutable API + + Our interface to the immutable Bloom filter has the same + structure as the mutable API. + + &BloomFilter.hs:module; + + We provide an easy-to-use means to create an immutable Bloom + filter, via a fromList function. This + hides the ST monad from our users, so that they + only see the immutable type. + + &BloomFilter.hs:fromList; + + The key to this function is + runSTUArray. We mentioned earlier that in + order to return an immutable array from the ST + monad, we must freeze a mutable array. The + runSTUArray function combines execution + with freezing. Given an action that returns an + STUArray, it executes the action using + runST; freezes the STUArray + that it returns; and returns that as a + UArray. + + The MArray typeclass provides a + freeze function that we could use instead, + but runSTUArray is both more convenient and + more efficient. The efficiency lies in the fact that + freeze must copy the underlying data from + the STUArray to the new UArray, to + ensure that subsequent modifications of the + STUArray cannot affect the contents of the + UArray. Thanks to the type system, + runSTUArray can guarantee that an + STUArray is no longer accessible when it uses it to + create a UArray. It can thus share the underyling + contents between the two arrays, avoiding the copy. + + + + Creating a friendly interface + + Although our immutable Bloom filter API is straightforward + to use once we have created a Bloom value, the + fromList function leaves some important + decisions unresolved. We still have to choose a function that + can generate many hash values, and determine what the capacity + of a Bloom filter should be. + + &Easy.hs:easyList; + + Here is a possible friendlier way to create a + Bloom filter. It leaves responsibility for hashing values in + the hands of a typeclass, Hashable. It lets us + configure the Bloom filter based on a parameter that is easier + to understand, namely the rate of false positives that we are + willing to tolerate. And it chooses the size of the filter for + us, based on the desired false positive rate and the number of + elements in the input list. + + This function will of course not always be usable, but it + complements the other interfaces we provide. It lets us provide + a range of control over creation, from entirely imperative to + completely declarative. + + + Hashing values + + A Bloom filter depends on fast, high-quality hashes for + good performance and a low false positive rate. It is + surprisingly difficult to write a general purpose hash + function that has both of these properties. + + Luckily for us, a fellow named Bob Jenkins developed some + hash functions that have exactly these properties, and he + placed the code in the public domain at http://burtleburtle.net/bob/hash/doobs.html + Jenkins's hash functions have + much better mixing properties than + some other popular non-cryptographic hash functions that + you might be familiar with, such as FNV and + hashpjw, so we recommend avoiding + them. + . He wrote his hash functions in C, so we can + easily use the FFI to create bindings to them. The specific + source file that we need from that site is named lookup3.c. + + There remains one hitch: we will frequently need seven or + even ten hash functions. We really don't want to scrape + together that many different functions, and fortunately we do + not need to: in most cases, we can get away with just two. We + will see how shortly. The Jenkins hash library includes two + functions, hashword2 and + hashlittle2, that compute two hash + values. Here is a C header file that describes the APIs of + these two functions. + + &lookup3.h:header; + + A salt is a value that perturbs the hash + value that the function computes. If we hash the same value + with two different salts, we will get two different hashes. + Since these functions compute two hashes, they accept two + salts. + + Here are Haskell bindings to these functions. + + &Hash.hs:jenkins; + + For efficiency, we will combine the two 32-bit salts and + hashes into a single 64-bit value. + + &Hash.hs:hashIO; + + Without explicit types around to describe what is + happening, the above code is not completely obvious. The + with function allocates room for the salt + on the C stack, and stores the current salt value in there, so + sp is a Ptr Word64. The + pointers p1 and p2 are + Ptr Word32; p1 points at the + low word of sp, and p2 + at the high word. This is how we chop the single + Word64 salt into two Ptr Word32 + parameters. + + Because all of our data pointers are coming from the + Haskell heap, we know that they will be aligned on an address + that is safe to pass to either hashWord2 + (which only accepts 32-bit-aligned addresses) or + hashLittle2. Since + hashWord32 is the faster of the two + hashing functions, we call it if we our data is a multiple of + 4 bytes in size, otherwise + hashLittle2. + + Since the C hash function will write the computed hashes + into p1 and p2, we only + need to peek the pointer + sp to retrieve the computed hash. + + To hash basic types, we write a little bit of boilerplate + code. + + &Hash.hs:hashStorable; + + We might prefer to be able to make use of the + Storable typeclass to write just one declaration, + as follows: + + &Hash.hs:Storable; + + Unfortunately, Haskell does not permit us to write + instances of this form, as they make the type system + undecidable: they can cause the + compiler's type checker to loop infinitely. We are forced to + use a little boilerplate instead. The restriction on + undecidable types does not, however, pose a problem for a + definition such as this one. + + &Hash.hs:hashList; + + This instance lets us hash values of many list types. + Most importantly, since the Char type is an + instance of Storable, we have gained the ability + to hash values of type String. + + For tuple types, we take advantage of function + composition. + + &Hash.hs:hash2; + + And for ByteString types, we write special + instances. + + &Hash.hs:hashSB; + + + + + Turning two hashes into many + + As we mentioned earlier, we need many more than two hashes + to make effective use of a Bloom filter. We can use a + technique called double hashing to + combine the two values computed by the Jenkins hash functions, + yielding many more hashes. The resulting hashes are of good + enough quality for our needs, and far cheaper than computing + many distinct hashes. + + &Hash.hs:doubleHash; + + + + Implementing the easy creation function + + In the BloomFilter.Easy module, we use our + new doubleHash function to define the + easyList function whose type we defined + earier. + + &Easy.hs:easyList; + + This depends on a suggestSizing + function that estimates the best combination of filter size + and number of hashes to compute, based on our desired false + positive rate and the maximum number of elements that we + expect the filter to contain. + + &Easy.hs:suggestSizing; + + In this function, we attempt to minimise only the size of + the Bloom filter, without regard for the number of hashes. To + see why. Let us + interactively explore the relationship between filter size and + number of hashes. + + Suppose we want + to insert 10 million elements into the Bloom filter with a + false positive rate of 0.1%. + + &sizings.ghci:kbytes; + + We achieve the most compact table (just over 17KB) by + computing 10 hashes. If we do not mind spending an extra 5% on + storage, we can reduce the number of hashes to 7. If we were + really calculating 10 hashes over each value, that might be an + excellent tradeoff, since even cheap hashes are expensive + relative to the cost of a few extra kilobytes of storage. + Since we are using Jenkins's hash functions which compute two + hashes in a single pass, and double hashing the results to + produce additional hashes, our cost of computing extra hashes + is tiny. We thus stand to benefit much less benefit by + reducing the number of hashes. + + If we increase our tolerance for false positives tenfold, + to 1%, the amount of space and the number of hashes we need + drop, though not by easily predictable amounts. + + &sizings.ghci:kbytes2; + + + + + + Creating a Cabal package + + We have created a moderately complicated library, with four + public modules and one internal module. To turn this into a + package that we can easily redistribute, we create a + rwh-bloomfilter.cabal file. + + Cabal allows us to describe several libraries in a single + package. A .cabal file begins with + information that is common to all of the libraries, which is + followed by a distinct section for each library. + + &rwh-bloomfilter.cabal:header; + + As we are bundling some C code with our library, we tell + Cabal about our C source files. + + &rwh-bloomfilter.cabal:extraSourceFiles; + + The extra-source-files directive has no effect + on a build: it directs Cabal to bundle some extra files if we + run runhaskell Setup sdist to create a source + tarball for redistribution. + + + Property names are case insensitive + + When reading a property (the text before a + : character), Cabal ignores + case, so it treats extra-source-files and + Extra-Source-Files as the same. + + + + Dealing with different build setups + + Prior to 2007, the standard Haskell libraries were + organised in a handful of large packages, of which the biggest + was named base. This organisation tied + many unrelated libraries together, so the Haskell community + split the base package up into a number + of more modular libraries. For instance, the array types + migrated from base into a package named + array. + + A Cabal package needs to specify the other packages that + it needs to have present in order to build. This makes it + possible for Cabal's command line interface automatically + download and build a package's dependencies, if necessary. We + would like our code to work with as many versions of &GHC; as + possible, regardless of whether they have the modern layout of + base and numerous other packages. We + thus need to be able to specify that we depend on the + array package if it is present, and + base alone otherwise. + + Cabal provides a generic + configurations feature, which we can use + to selectively enable parts of a .cabal + file. A build configuration is controlled by a Boolean-valued + flag. If it is True, the + text following an if flag directive is used, + otherwise the text following the associated else + is used. + + &rwh-bloomfilter.cabal:splitBase; + + + + The configurations feature was introduced in version + 1.2 of Cabal, so we specify that our package cannot be + built with an older version. + + + The meaning of the split-base flag should + be self-explanatory. + + + The bytestring-in-base flag deals with a + more tortured history. When the + bytestring package was first created, + it was bundled with &GHC; 6.4, and kept separate from the + base package. In &GHC; 6.6, it was + incorporated into the base package, + but it became independent again when the + base package was split before the + release of &GHC; 6.8.1. + + + + These flags are usually invisible to people building a + package, because Cabal handles them automatically. Before we + explain what happens, it will help to see the beginning of the + Library section of our .cabal + file. + + &rwh-bloomfilter.cabal:library; + + Cabal creates a package description with the default + values of the flags (a missing default is assumed to be + True). If that configuration can be built (e.g. + because all of the needed package versions are available), it + will be used. Otherwise, Cabal tries different combinations + of flags until it either finds a configuration that it can + build or exhausts the alternatives. + + For example, if we were to begin with both + split-base and bytestring-in-base + set to True, Cabal would select the following + package dependencies. + + &inconsistent.cabal:bogus; + + The base package cannot + simultaneously be newer than 3.0 and older than + 2.2, so Cabal would reject this configuration as + inconsistent. For a modern version of &GHC;, after a few + attempts it would discover this configuration that will indeed + build. + + &inconsistent.cabal:modern; + + When we run runhaskell Setup configure, + we can manually specify the values of flags, though we will + rarely need to do so in practice. + + hunk ./examples/ch27/BloomFilter/Hash.hs 1 +{-- snippet jenkins --} +{-# LANGUAGE ForeignFunctionInterface #-} +module BloomFilter.Hash where + +import Data.Bits ((.&.), shiftR) +import Foreign.Marshal.Array (withArrayLen) +import Control.Monad (foldM) +import Data.Word (Word32, Word64) +import Foreign.C.Types (CSize) +import Foreign.Marshal.Utils (with) +import Foreign.Ptr (Ptr, castPtr, plusPtr) +import Foreign.Storable (Storable, peek, sizeOf) +import qualified Data.ByteString as Strict +import qualified Data.ByteString.Lazy as Lazy +import System.IO.Unsafe (unsafePerformIO) + +foreign import ccall unsafe "lookup3.h hashword2" hashWord2 + :: Ptr Word32 -> CSize -> Ptr Word32 -> Ptr Word32 -> IO () + +foreign import ccall unsafe "lookup3.h hashlittle2" hashLittle2 + :: Ptr a -> CSize -> Ptr Word32 -> Ptr Word32 -> IO () +{-- /snippet jenkins --} + +class Hashable a where + hashSalt :: Word64 -- ^ salt + -> a -- ^ value to hash + -> Word64 + +hash :: Hashable a => a -> Word64 +hash = hashSalt 0x106fc397cf62f64d3 + +{-- snippet hashIO --} +hashIO :: Ptr a -- value to hash + -> CSize -- number of bytes + -> Word64 -- salt + -> IO Word64 +hashIO ptr bytes salt = + with (fromIntegral salt) $ \sp -> do + let p1 = castPtr sp + p2 = castPtr sp `plusPtr` 4 + go p1 p2 + peek sp + where go p1 p2 + | bytes .&. 3 == 0 = hashWord2 (castPtr ptr) words p1 p2 + | otherwise = hashLittle2 ptr bytes p1 p2 + words = bytes `div` 4 +{-- /snippet hashIO --} + +{-- snippet hashStorable --} +hashStorable :: Storable a => Word64 -> a -> Word64 +hashStorable salt k = unsafePerformIO . with k $ \ptr -> + hashIO ptr (fromIntegral (sizeOf k)) salt + +instance Hashable Char where hashSalt = hashStorable +instance Hashable Int where hashSalt = hashStorable +instance Hashable Double where hashSalt = hashStorable +{-- /snippet hashStorable --} + +{- +{-- snippet Storable --} +instance Storable a => Hashable a where + hashSalt = hashStorable +{-- /snippet Storable --} +-} + +{-- snippet hashList --} +hashList :: (Storable a) => Word64 -> [a] -> IO Word64 +hashList salt xs = + withArrayLen xs $ \len ptr -> + hashIO ptr (fromIntegral (len * sizeOf x)) salt + where x = head xs + +instance (Storable a) => Hashable [a] where + hashSalt salt xs = unsafePerformIO $ hashList salt xs +{-- /snippet hashList --} + +{-- snippet hash2 --} +hash2 k salt = hashSalt salt k + +instance (Hashable a, Hashable b) => Hashable (a,b) where + hashSalt salt (a,b) = hash2 b . hash2 a $ salt + +instance (Hashable a, Hashable b, Hashable c) => Hashable (a,b,c) where + hashSalt salt (a,b,c) = hash2 c . hash2 b . hash2 a $ salt +{-- /snippet hash2 --} + +{-- snippet hashSB --} +hashSB :: Word64 -> Strict.ByteString -> IO Word64 +hashSB salt bs = Strict.useAsCStringLen bs $ \(ptr, len) -> + hashIO ptr (fromIntegral len) salt + +instance Hashable Strict.ByteString where + hashSalt salt bs = unsafePerformIO $ hashSB salt bs + +instance Hashable Lazy.ByteString where + hashSalt salt bs = unsafePerformIO $ + foldM hashSB salt (Lazy.toChunks bs) +{-- /snippet hashSB --} + +{-- snippet doubleHash --} +doubleHash :: Hashable a => Int -> a -> [Word32] +doubleHash numHashes value = [h1 + (h2 * i) | i <- [1..num]] + where h = hashSalt 0x9150a946c4a8966e value + h1 = fromIntegral (h `shiftR` 32) .&. maxBound + h2 = fromIntegral h + num = fromIntegral numHashes +{-- /snippet doubleHash --} hunk ./examples/ch27/BloomFilter/Mutable.hs 1 +{-- snippet Mutable --} +module BloomFilter.Mutable + ( + MutBloom + , elem + , notElem + , insert + , length + , new + ) where + +import Control.Monad (liftM) +import Control.Monad.ST (ST) +import Data.Array.MArray (getBounds, newArray, readArray, writeArray) +import Data.Word (Word32) +import Prelude hiding (elem, length, notElem) + +import BloomFilter.Internal (MutBloom(..)) +{-- /snippet Mutable --} + +{-- snippet new --} +new :: (a -> [Word32]) -> Word32 -> ST s (MutBloom s a) +new hash numBits = MB hash `liftM` newArray (0,numBits-1) False +{-- /snippet new --} + +{-- snippet length --} +length :: MutBloom s a -> ST s Word32 +length filt = (succ . snd) `liftM` getBounds (mutArray filt) +{-- /snippet length --} + +{-- snippet insert --} +insert :: MutBloom s a -> a -> ST s () +insert filt elt = indices filt elt >>= + mapM_ (\bit -> writeArray (mutArray filt) bit True) + +indices :: MutBloom s a -> a -> ST s [Word32] +indices filt elt = do + modulus <- length filt + return $ map (`mod` modulus) (mutHash filt elt) +{-- /snippet insert --} + +{-- snippet elem --} +elem, notElem :: a -> MutBloom s a -> ST s Bool + +elem elt filt = indices filt elt >>= + allM (readArray (mutArray filt)) + +notElem elt filt = not `liftM` elem elt filt +{-- /snippet elem --} + +{-- snippet allM --} +allM :: Monad m => (a -> m Bool) -> [a] -> m Bool +allM p (x:xs) = do + ok <- p x + if ok + then allM p xs + else return False +allM _ [] = return True +{-- /snippet allM --} hunk ./examples/ch27/License.txt 1 +Foo. hunk ./examples/ch27/Setup.lhs 1 +#!/usr/bin/env runhaskell +> import Distribution.Simple +> main = defaultMain hunk ./examples/ch27/cbits/lookup3.c 1 +/* +------------------------------------------------------------------------------- +lookup3.c, by Bob Jenkins, May 2006, Public Domain. + +These are functions for producing 32-bit hashes for hash table lookup. +hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() +are externally useful functions. Routines to test the hash are included +if SELF_TEST is defined. You can use this free for any purpose. It's in +the public domain. It has no warranty. + +You probably want to use hashlittle(). hashlittle() and hashbig() +hash byte arrays. hashlittle() is is faster than hashbig() on +little-endian machines. Intel and AMD are little-endian machines. +On second thought, you probably want hashlittle2(), which is identical to +hashlittle() except it returns two 32-bit hashes for the price of one. +You could implement hashbig2() if you wanted but I haven't bothered here. + +If you want to find a hash of, say, exactly 7 integers, do + a = i1; b = i2; c = i3; + mix(a,b,c); + a += i4; b += i5; c += i6; + mix(a,b,c); + a += i7; + final(a,b,c); +then use c as the hash value. If you have a variable length array of +4-byte integers to hash, use hashword(). If you have a byte array (like +a character string), use hashlittle(). If you have several byte arrays, or +a mix of things, see the comments above hashlittle(). + +Why is this so big? I read 12 bytes at a time into 3 4-byte integers, +then mix those integers. This is fast (you can do a lot more thorough +mixing with 12*3 instructions on 3 integers than you can with 3 instructions +on 1 byte), but shoehorning those bytes into integers efficiently is messy. +------------------------------------------------------------------------------- +*/ +#define SELF_TEST 1 + +#include /* defines printf for tests */ +#include /* defines time_t for timings in the test */ +#include /* defines uint32_t etc */ +#include /* attempt to define endianness */ +#ifdef linux +# include /* attempt to define endianness */ +#endif + +/* + * My best guess at if you are big-endian or little-endian. This may + * need adjustment. + */ +#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \ + __BYTE_ORDER == __LITTLE_ENDIAN) || \ + (defined(i386) || defined(__i386__) || defined(__i486__) || \ + defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL)) +# define HASH_LITTLE_ENDIAN 1 +# define HASH_BIG_ENDIAN 0 +#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \ + __BYTE_ORDER == __BIG_ENDIAN) || \ + (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel)) +# define HASH_LITTLE_ENDIAN 0 +# define HASH_BIG_ENDIAN 1 +#else +# define HASH_LITTLE_ENDIAN 0 +# define HASH_BIG_ENDIAN 0 +#endif + +#define hashsize(n) ((uint32_t)1<<(n)) +#define hashmask(n) (hashsize(n)-1) +#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k)))) + +/* +------------------------------------------------------------------------------- +mix -- mix 3 32-bit values reversibly. + +This is reversible, so any information in (a,b,c) before mix() is +still in (a,b,c) after mix(). + +If four pairs of (a,b,c) inputs are run through mix(), or through +mix() in reverse, there are at least 32 bits of the output that +are sometimes the same for one pair and different for another pair. +This was tested for: +* pairs that differed by one bit, by two bits, in any combination + of top bits of (a,b,c), or in any combination of bottom bits of + (a,b,c). +* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed + the output delta to a Gray code (a^(a>>1)) so a string of 1's (as + is commonly produced by subtraction) look like a single 1-bit + difference. +* the base values were pseudorandom, all zero but one bit set, or + all zero plus a counter that starts at zero. + +Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that +satisfy this are + 4 6 8 16 19 4 + 9 15 3 18 27 15 + 14 9 3 7 17 3 +Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing +for "differ" defined as + with a one-bit base and a two-bit delta. I +used http://burtleburtle.net/bob/hash/avalanche.html to choose +the operations, constants, and arrangements of the variables. + +This does not achieve avalanche. There are input bits of (a,b,c) +that fail to affect some output bits of (a,b,c), especially of a. The +most thoroughly mixed value is c, but it doesn't really even achieve +avalanche in c. + +This allows some parallelism. Read-after-writes are good at doubling +the number of bits affected, so the goal of mixing pulls in the opposite +direction as the goal of parallelism. I did what I could. Rotates +seem to cost as much as shifts on every machine I could lay my hands +on, and rotates are much kinder to the top and bottom bits, so I used +rotates. +------------------------------------------------------------------------------- +*/ +#define mix(a,b,c) \ +{ \ + a -= c; a ^= rot(c, 4); c += b; \ + b -= a; b ^= rot(a, 6); a += c; \ + c -= b; c ^= rot(b, 8); b += a; \ + a -= c; a ^= rot(c,16); c += b; \ + b -= a; b ^= rot(a,19); a += c; \ + c -= b; c ^= rot(b, 4); b += a; \ +} + +/* +------------------------------------------------------------------------------- +final -- final mixing of 3 32-bit values (a,b,c) into c + +Pairs of (a,b,c) values differing in only a few bits will usually +produce values of c that look totally different. This was tested for +* pairs that differed by one bit, by two bits, in any combination + of top bits of (a,b,c), or in any combination of bottom bits of + (a,b,c). +* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed + the output delta to a Gray code (a^(a>>1)) so a string of 1's (as + is commonly produced by subtraction) look like a single 1-bit + difference. +* the base values were pseudorandom, all zero but one bit set, or + all zero plus a counter that starts at zero. + +These constants passed: + 14 11 25 16 4 14 24 + 12 14 25 16 4 14 24 +and these came close: + 4 8 15 26 3 22 24 + 10 8 15 26 3 22 24 + 11 8 15 26 3 22 24 +------------------------------------------------------------------------------- +*/ +#define final(a,b,c) \ +{ \ + c ^= b; c -= rot(b,14); \ + a ^= c; a -= rot(c,11); \ + b ^= a; b -= rot(a,25); \ + c ^= b; c -= rot(b,16); \ + a ^= c; a -= rot(c,4); \ + b ^= a; b -= rot(a,14); \ + c ^= b; c -= rot(b,24); \ +} + +/* +-------------------------------------------------------------------- + This works on all machines. To be useful, it requires + -- that the key be an array of uint32_t's, and + -- that the length be the number of uint32_t's in the key + + The function hashword() is identical to hashlittle() on little-endian + machines, and identical to hashbig() on big-endian machines, + except that the length has to be measured in uint32_ts rather than in + bytes. hashlittle() is more complicated than hashword() only because + hashlittle() has to dance around fitting the key bytes into registers. +-------------------------------------------------------------------- +*/ +uint32_t hashword( +const uint32_t *k, /* the key, an array of uint32_t values */ +size_t length, /* the length of the key, in uint32_ts */ +uint32_t initval) /* the previous hash, or an arbitrary value */ +{ + uint32_t a,b,c; + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + (((uint32_t)length)<<2) + initval; + + /*------------------------------------------------- handle most of the key */ + while (length > 3) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 3; + k += 3; + } + + /*------------------------------------------- handle the last 3 uint32_t's */ + switch(length) /* all the case statements fall through */ + { + case 3 : c+=k[2]; + case 2 : b+=k[1]; + case 1 : a+=k[0]; + final(a,b,c); + case 0: /* case 0: nothing left to add */ + break; + } + /*------------------------------------------------------ report the result */ + return c; +} + + +/* +-------------------------------------------------------------------- +hashword2() -- same as hashword(), but take two seeds and return two +32-bit values. pc and pb must both be nonnull, and *pc and *pb must +both be initialized with seeds. If you pass in (*pb)==0, the output +(*pc) will be the same as the return value from hashword(). +-------------------------------------------------------------------- +*/ +void hashword2 ( +const uint32_t *k, /* the key, an array of uint32_t values */ +size_t length, /* the length of the key, in uint32_ts */ +uint32_t *pc, /* IN: seed OUT: primary hash value */ +uint32_t *pb) /* IN: more seed OUT: secondary hash value */ +{ + uint32_t a,b,c; + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)(length<<2)) + *pc; + c += *pb; + + /*------------------------------------------------- handle most of the key */ + while (length > 3) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 3; + k += 3; + } + + /*------------------------------------------- handle the last 3 uint32_t's */ + switch(length) /* all the case statements fall through */ + { + case 3 : c+=k[2]; + case 2 : b+=k[1]; + case 1 : a+=k[0]; + final(a,b,c); + case 0: /* case 0: nothing left to add */ + break; + } + /*------------------------------------------------------ report the result */ + *pc=c; *pb=b; +} + + +/* +------------------------------------------------------------------------------- +hashlittle() -- hash a variable-length key into a 32-bit value + k : the key (the unaligned variable-length array of bytes) + length : the length of the key, counting by bytes + initval : can be any 4-byte value +Returns a 32-bit value. Every bit of the key affects every bit of +the return value. Two keys differing by one or two bits will have +totally different hash values. + +The best hash table sizes are powers of 2. There is no need to do +mod a prime (mod is sooo slow!). If you need less than 32 bits, +use a bitmask. For example, if you need only 10 bits, do + h = (h & hashmask(10)); +In which case, the hash table should have hashsize(10) elements. + +If you are hashing n strings (uint8_t **)k, do it like this: + for (i=0, h=0; i 12) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * "k[2]&0xffffff" actually reads beyond the end of the string, but + * then masks off the part it's not allowed to read. Because the + * string is aligned, the masked-off tail is in the same word as the + * rest of the string. Every machine with memory protection I've seen + * does it on word boundaries, so is OK with this. But VALGRIND will + * still catch it and complain. The masking trick does make the hash + * noticably faster for short strings (like English words). + */ +#ifndef VALGRIND + + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; + case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; + case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=k[1]&0xffffff; a+=k[0]; break; + case 6 : b+=k[1]&0xffff; a+=k[0]; break; + case 5 : b+=k[1]&0xff; a+=k[0]; break; + case 4 : a+=k[0]; break; + case 3 : a+=k[0]&0xffffff; break; + case 2 : a+=k[0]&0xffff; break; + case 1 : a+=k[0]&0xff; break; + case 0 : return c; /* zero length strings require no mixing */ + } + +#else /* make valgrind happy */ + + k8 = (const uint8_t *)k; + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ + case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ + case 9 : c+=k8[8]; /* fall through */ + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ + case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ + case 5 : b+=k8[4]; /* fall through */ + case 4 : a+=k[0]; break; + case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ + case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ + case 1 : a+=k8[0]; break; + case 0 : return c; + } + +#endif /* !valgrind */ + + } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { + const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ + const uint8_t *k8; + + /*--------------- all but last block: aligned reads and different mixing */ + while (length > 12) + { + a += k[0] + (((uint32_t)k[1])<<16); + b += k[2] + (((uint32_t)k[3])<<16); + c += k[4] + (((uint32_t)k[5])<<16); + mix(a,b,c); + length -= 12; + k += 6; + } + + /*----------------------------- handle the last (probably partial) block */ + k8 = (const uint8_t *)k; + switch(length) + { + case 12: c+=k[4]+(((uint32_t)k[5])<<16); + b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ + case 10: c+=k[4]; + b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 9 : c+=k8[8]; /* fall through */ + case 8 : b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ + case 6 : b+=k[2]; + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 5 : b+=k8[4]; /* fall through */ + case 4 : a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ + case 2 : a+=k[0]; + break; + case 1 : a+=k8[0]; + break; + case 0 : return c; /* zero length requires no mixing */ + } + + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) + { + a += k[0]; + a += ((uint32_t)k[1])<<8; + a += ((uint32_t)k[2])<<16; + a += ((uint32_t)k[3])<<24; + b += k[4]; + b += ((uint32_t)k[5])<<8; + b += ((uint32_t)k[6])<<16; + b += ((uint32_t)k[7])<<24; + c += k[8]; + c += ((uint32_t)k[9])<<8; + c += ((uint32_t)k[10])<<16; + c += ((uint32_t)k[11])<<24; + mix(a,b,c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch(length) /* all the case statements fall through */ + { + case 12: c+=((uint32_t)k[11])<<24; + case 11: c+=((uint32_t)k[10])<<16; + case 10: c+=((uint32_t)k[9])<<8; + case 9 : c+=k[8]; + case 8 : b+=((uint32_t)k[7])<<24; + case 7 : b+=((uint32_t)k[6])<<16; + case 6 : b+=((uint32_t)k[5])<<8; + case 5 : b+=k[4]; + case 4 : a+=((uint32_t)k[3])<<24; + case 3 : a+=((uint32_t)k[2])<<16; + case 2 : a+=((uint32_t)k[1])<<8; + case 1 : a+=k[0]; + break; + case 0 : return c; + } + } + + final(a,b,c); + return c; +} + + +/* + * hashlittle2: return 2 32-bit hash values + * + * This is identical to hashlittle(), except it returns two 32-bit hash + * values instead of just one. This is good enough for hash table + * lookup with 2^^64 buckets, or if you want a second hash if you're not + * happy with the first, or if you want a probably-unique 64-bit ID for + * the key. *pc is better mixed than *pb, so use *pc first. If you want + * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)". + */ +void hashlittle2( + const void *key, /* the key to hash */ + size_t length, /* length of the key */ + uint32_t *pc, /* IN: primary initval, OUT: primary hash */ + uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */ +{ + uint32_t a,b,c; /* internal state */ + union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc; + c += *pb; + + u.ptr = key; + if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { + const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ + const uint8_t *k8; + + /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ + while (length > 12) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * "k[2]&0xffffff" actually reads beyond the end of the string, but + * then masks off the part it's not allowed to read. Because the + * string is aligned, the masked-off tail is in the same word as the + * rest of the string. Every machine with memory protection I've seen + * does it on word boundaries, so is OK with this. But VALGRIND will + * still catch it and complain. The masking trick does make the hash + * noticably faster for short strings (like English words). + */ +#ifndef VALGRIND + + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; + case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; + case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=k[1]&0xffffff; a+=k[0]; break; + case 6 : b+=k[1]&0xffff; a+=k[0]; break; + case 5 : b+=k[1]&0xff; a+=k[0]; break; + case 4 : a+=k[0]; break; + case 3 : a+=k[0]&0xffffff; break; + case 2 : a+=k[0]&0xffff; break; + case 1 : a+=k[0]&0xff; break; + case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ + } + +#else /* make valgrind happy */ + + k8 = (const uint8_t *)k; + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ + case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ + case 9 : c+=k8[8]; /* fall through */ + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ + case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ + case 5 : b+=k8[4]; /* fall through */ + case 4 : a+=k[0]; break; + case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ + case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ + case 1 : a+=k8[0]; break; + case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ + } + +#endif /* !valgrind */ + + } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { + const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ + const uint8_t *k8; + + /*--------------- all but last block: aligned reads and different mixing */ + while (length > 12) + { + a += k[0] + (((uint32_t)k[1])<<16); + b += k[2] + (((uint32_t)k[3])<<16); + c += k[4] + (((uint32_t)k[5])<<16); + mix(a,b,c); + length -= 12; + k += 6; + } + + /*----------------------------- handle the last (probably partial) block */ + k8 = (const uint8_t *)k; + switch(length) + { + case 12: c+=k[4]+(((uint32_t)k[5])<<16); + b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ + case 10: c+=k[4]; + b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 9 : c+=k8[8]; /* fall through */ + case 8 : b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ + case 6 : b+=k[2]; + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 5 : b+=k8[4]; /* fall through */ + case 4 : a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ + case 2 : a+=k[0]; + break; + case 1 : a+=k8[0]; + break; + case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ + } + + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) + { + a += k[0]; + a += ((uint32_t)k[1])<<8; + a += ((uint32_t)k[2])<<16; + a += ((uint32_t)k[3])<<24; + b += k[4]; + b += ((uint32_t)k[5])<<8; + b += ((uint32_t)k[6])<<16; + b += ((uint32_t)k[7])<<24; + c += k[8]; + c += ((uint32_t)k[9])<<8; + c += ((uint32_t)k[10])<<16; + c += ((uint32_t)k[11])<<24; + mix(a,b,c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch(length) /* all the case statements fall through */ + { + case 12: c+=((uint32_t)k[11])<<24; + case 11: c+=((uint32_t)k[10])<<16; + case 10: c+=((uint32_t)k[9])<<8; + case 9 : c+=k[8]; + case 8 : b+=((uint32_t)k[7])<<24; + case 7 : b+=((uint32_t)k[6])<<16; + case 6 : b+=((uint32_t)k[5])<<8; + case 5 : b+=k[4]; + case 4 : a+=((uint32_t)k[3])<<24; + case 3 : a+=((uint32_t)k[2])<<16; + case 2 : a+=((uint32_t)k[1])<<8; + case 1 : a+=k[0]; + break; + case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ + } + } + + final(a,b,c); + *pc=c; *pb=b; +} + + + +/* + * hashbig(): + * This is the same as hashword() on big-endian machines. It is different + * from hashlittle() on all machines. hashbig() takes advantage of + * big-endian byte ordering. + */ +uint32_t hashbig( const void *key, size_t length, uint32_t initval) +{ + uint32_t a,b,c; + union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */ + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; + + u.ptr = key; + if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) { + const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ + const uint8_t *k8; + + /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ + while (length > 12) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * "k[2]<<8" actually reads beyond the end of the string, but + * then shifts out the part it's not allowed to read. Because the + * string is aligned, the illegal read is in the same word as the + * rest of the string. Every machine with memory protection I've seen + * does it on word boundaries, so is OK with this. But VALGRIND will + * still catch it and complain. The masking trick does make the hash + * noticably faster for short strings (like English words). + */ +#ifndef VALGRIND + + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break; + case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break; + case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break; + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=k[1]&0xffffff00; a+=k[0]; break; + case 6 : b+=k[1]&0xffff0000; a+=k[0]; break; + case 5 : b+=k[1]&0xff000000; a+=k[0]; break; + case 4 : a+=k[0]; break; + case 3 : a+=k[0]&0xffffff00; break; + case 2 : a+=k[0]&0xffff0000; break; + case 1 : a+=k[0]&0xff000000; break; + case 0 : return c; /* zero length strings require no mixing */ + } + +#else /* make valgrind happy */ + + k8 = (const uint8_t *)k; + switch(length) /* all the case statements fall through */ + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=((uint32_t)k8[10])<<8; /* fall through */ + case 10: c+=((uint32_t)k8[9])<<16; /* fall through */ + case 9 : c+=((uint32_t)k8[8])<<24; /* fall through */ + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=((uint32_t)k8[6])<<8; /* fall through */ + case 6 : b+=((uint32_t)k8[5])<<16; /* fall through */ + case 5 : b+=((uint32_t)k8[4])<<24; /* fall through */ + case 4 : a+=k[0]; break; + case 3 : a+=((uint32_t)k8[2])<<8; /* fall through */ + case 2 : a+=((uint32_t)k8[1])<<16; /* fall through */ + case 1 : a+=((uint32_t)k8[0])<<24; break; + case 0 : return c; + } + +#endif /* !VALGRIND */ + + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) + { + a += ((uint32_t)k[0])<<24; + a += ((uint32_t)k[1])<<16; + a += ((uint32_t)k[2])<<8; + a += ((uint32_t)k[3]); + b += ((uint32_t)k[4])<<24; + b += ((uint32_t)k[5])<<16; + b += ((uint32_t)k[6])<<8; + b += ((uint32_t)k[7]); + c += ((uint32_t)k[8])<<24; + c += ((uint32_t)k[9])<<16; + c += ((uint32_t)k[10])<<8; + c += ((uint32_t)k[11]); + mix(a,b,c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch(length) /* all the case statements fall through */ + { + case 12: c+=k[11]; + case 11: c+=((uint32_t)k[10])<<8; + case 10: c+=((uint32_t)k[9])<<16; + case 9 : c+=((uint32_t)k[8])<<24; + case 8 : b+=k[7]; + case 7 : b+=((uint32_t)k[6])<<8; + case 6 : b+=((uint32_t)k[5])<<16; + case 5 : b+=((uint32_t)k[4])<<24; + case 4 : a+=k[3]; + case 3 : a+=((uint32_t)k[2])<<8; + case 2 : a+=((uint32_t)k[1])<<16; + case 1 : a+=((uint32_t)k[0])<<24; + break; + case 0 : return c; + } + } + + final(a,b,c); + return c; +} + + +#ifdef SELF_TEST + +/* used for timings */ +void driver1() +{ + uint8_t buf[256]; + uint32_t i; + uint32_t h=0; + time_t a,z; + + time(&a); + for (i=0; i<256; ++i) buf[i] = 'x'; + for (i=0; i<1; ++i) + { + h = hashlittle(&buf[0],1,h); + } + time(&z); + if (z-a > 0) printf("time %d %.8x\n", z-a, h); +} + +/* check that every input bit changes every output bit half the time */ +#define HASHSTATE 1 +#define HASHLEN 1 +#define MAXPAIR 60 +#define MAXLEN 70 +void driver2() +{ + uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1]; + uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z; + uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE]; + uint32_t x[HASHSTATE],y[HASHSTATE]; + uint32_t hlen; + + printf("No more than %d trials should ever be needed \n",MAXPAIR/2); + for (hlen=0; hlen < MAXLEN; ++hlen) + { + z=0; + for (i=0; i>(8-j)); + c[0] = hashlittle(a, hlen, m); + b[i] ^= ((k+1)<>(8-j)); + d[0] = hashlittle(b, hlen, m); + /* check every bit is 1, 0, set, and not set at least once */ + for (l=0; lz) z=k; + if (k==MAXPAIR) + { + printf("Some bit didn't change: "); + printf("%.8x %.8x %.8x %.8x %.8x %.8x ", + e[0],f[0],g[0],h[0],x[0],y[0]); + printf("i %d j %d m %d len %d\n", i, j, m, hlen); + } + if (z==MAXPAIR) goto done; + } + } + } + done: + if (z < MAXPAIR) + { + printf("Mix success %2d bytes %2d initvals ",i,m); + printf("required %d trials\n", z/2); + } + } + printf("\n"); +} + +/* Check for reading beyond the end of the buffer and alignment problems */ +void driver3() +{ + uint8_t buf[MAXLEN+20], *b; + uint32_t len; + uint8_t q[] = "This is the time for all good men to come to the aid of their country..."; + uint32_t h; + uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country..."; + uint32_t i; + uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country..."; + uint32_t j; + uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country..."; + uint32_t ref,x,y; + uint8_t *p; + + printf("Endianness. These lines should all be the same (for values filled in):\n"); + printf("%.8x %.8x %.8x\n", + hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13), + hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13), + hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13)); + p = q; + printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", + hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), + hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), + hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), + hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), + hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), + hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); + p = &qq[1]; + printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", + hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), + hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), + hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), + hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), + hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), + hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); + p = &qqq[2]; + printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", + hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), + hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), + hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), + hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), + hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), + hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); + p = &qqqq[3]; + printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", + hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), + hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), + hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), + hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), + hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), + hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); + printf("\n"); + + /* check that hashlittle2 and hashlittle produce the same results */ + i=47; j=0; + hashlittle2(q, sizeof(q), &i, &j); + if (hashlittle(q, sizeof(q), 47) != i) + printf("hashlittle2 and hashlittle mismatch\n"); + + /* check that hashword2 and hashword produce the same results */ + len = 0xdeadbeef; + i=47, j=0; + hashword2(&len, 1, &i, &j); + if (hashword(&len, 1, 47) != i) + printf("hashword2 and hashword mismatch %x %x\n", + i, hashword(&len, 1, 47)); + + /* check hashlittle doesn't read before or after the ends of the string */ + for (h=0, b=buf+1; h<8; ++h, ++b) + { + for (i=0; i +#include + +/* only accepts uint32_t aligned arrays of uint32_t */ +void hashword2(const uint32_t *key, /* array of uint32_t */ + size_t length, /* number of uint32_t values */ + uint32_t *pc, /* in: seed1, out: hash1 */ + uint32_t *pb); /* in: seed2, out: hash2 */ + +/* handles arbitrarily aligned arrays of bytes */ +void hashlittle2(const void *key, /* array of bytes */ + size_t length, /* number of bytes */ + uint32_t *pc, /* in: seed1, out: hash1 */ + uint32_t *pb); /* in: seed2, out: hash2 */ +/** /snippet header */ hunk ./examples/ch27/configs/inconsistent.cabal 1 +-- snippet bogus +Build-Depends: base >= 2.0 && < 2.2 +Build-Depends: base >= 3.0, array +-- /snippet bogus + +-- snippet modern +-- in base 1.0 and 3.0, bytestring is a separate package +Build-Depends: base < 2.0 || >= 3, bytestring >= 0.9 +Build-Depends: base >= 3.0, array +-- /snippet modern hunk ./examples/ch27/rwh-bloomfilter.cabal 1 +-- snippet header +Name: rwh-bloomfilter +Version: 0.1 +License: BSD3 +License-File: License.txt +Category: Data +Stability: experimental +Build-Type: Simple +-- /snippet header + +-- snippet extraSourceFiles +Extra-Source-Files: cbits/lookup3.c cbits/lookup3.h +-- /snippet extraSourceFiles + +-- snippet splitBase +Cabal-Version: >= 1.2 + +Flag split-base + Description: Has the base package been split up? + Default: True + +Flag bytestring-in-base + Description: Is ByteString in the base or bytestring package? + Default: False +-- /snippet splitBase + +-- snippet library +Library + if flag(bytestring-in-base) + -- bytestring was in base-2.0 and 2.1.1 + Build-Depends: base >= 2.0 && < 2.2 + else + -- in base 1.0 and 3.0, bytestring is a separate package + Build-Depends: base < 2.0 || >= 3, bytestring >= 0.9 + + if flag(split-base) + Build-Depends: base >= 3.0, array + else + Build-Depends: base < 3.0 +-- /snippet library + + Exposed-Modules: BloomFilter + BloomFilter.Easy + BloomFilter.Hash + BloomFilter.Mutable + Other-Modules: BloomFilter.Internal + C-Sources: cbits/lookup3.c + GHC-Options: -O2 -Wall -fliberate-case-threshold=1000 + CC-Options: -O3 hunk ./tools/Snip.hs 39 + "h" -> (startC, endC) }