• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 // Copyright 2008-2009 Daniel James.
3 // Distributed under the Boost Software License, Version 1.0. (See accompanying
4 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5 
6 // This code is also released into the public domain.
7 
8 // Algorithm from: http://www.isthe.com/chongo/tech/comp/fnv/
9 
10 #include <string>
11 
12 namespace hash
13 {
14     template <std::size_t FnvPrime, std::size_t OffsetBasis>
15     struct basic_fnv_1
16     {
operator ()hash::basic_fnv_117         std::size_t operator()(std::string const& text) const
18         {
19             std::size_t hash = OffsetBasis;
20             for(std::string::const_iterator it = text.begin(), end = text.end();
21                     it != end; ++it)
22             {
23                 hash *= FnvPrime;
24                 hash ^= *it;
25             }
26 
27             return hash;
28         }
29     };
30 
31     template <std::size_t FnvPrime, std::size_t OffsetBasis>
32     struct basic_fnv_1a
33     {
operator ()hash::basic_fnv_1a34         std::size_t operator()(std::string const& text) const
35         {
36             std::size_t hash = OffsetBasis;
37             for(std::string::const_iterator it = text.begin(), end = text.end();
38                     it != end; ++it)
39             {
40                 hash ^= *it;
41                 hash *= FnvPrime;
42             }
43 
44             return hash;
45         }
46     };
47 
48     // For 32 bit machines:
49     const std::size_t fnv_prime = 16777619u;
50     const std::size_t fnv_offset_basis = 2166136261u;
51 
52     // For 64 bit machines:
53     // const std::size_t fnv_prime = 1099511628211u;
54     // const std::size_t fnv_offset_basis = 14695981039346656037u;
55 
56     // For 128 bit machines:
57     // const std::size_t fnv_prime = 309485009821345068724781401u;
58     // const std::size_t fnv_offset_basis =
59     //     275519064689413815358837431229664493455u;
60 
61     // For 256 bit machines:
62     // const std::size_t fnv_prime =
63     //     374144419156711147060143317175368453031918731002211u;
64     // const std::size_t fnv_offset_basis =
65     //     100029257958052580907070968620625704837092796014241193945225284501741471925557u;
66 
67     typedef basic_fnv_1<fnv_prime, fnv_offset_basis> fnv_1;
68     typedef basic_fnv_1a<fnv_prime, fnv_offset_basis> fnv_1a;
69 }
70