1 /** @file
2 
3   @section license License
4 
5   Licensed to the Apache Software Foundation (ASF) under one
6   or more contributor license agreements.  See the NOTICE file
7   distributed with this work for additional information
8   regarding copyright ownership.  The ASF licenses this file
9   to you under the Apache License, Version 2.0 (the
10   "License"); you may not use this file except in compliance
11   with the License.  You may obtain a copy of the License at
12 
13       http://www.apache.org/licenses/LICENSE-2.0
14 
15   Unless required by applicable law or agreed to in writing, software
16   distributed under the License is distributed on an "AS IS" BASIS,
17   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   See the License for the specific language governing permissions and
19   limitations under the License.
20  */
21 
22 /*
23   http://www.isthe.com/chongo/tech/comp/fnv/
24 
25   Currently implemented FNV-1a 32bit and FNV-1a 64bit
26  */
27 
28 #pragma once
29 
30 #include "tscore/Hash.h"
31 #include <cstdint>
32 
33 struct ATSHash32FNV1a : ATSHash32 {
34   ATSHash32FNV1a();
35 
36   template <typename Transform> void update(const void *data, size_t len, Transform xfrm);
37   void
updateATSHash32FNV1a38   update(const void *data, size_t len) override
39   {
40     update(data, len, ATSHash::nullxfrm());
41   }
42 
43   void final() override;
44   uint32_t get() const override;
45   void clear() override;
46 
47 private:
48   uint32_t hval;
49 };
50 
51 template <typename Transform>
52 void
update(const void * data,size_t len,Transform xfrm)53 ATSHash32FNV1a::update(const void *data, size_t len, Transform xfrm)
54 {
55   uint8_t *bp = (uint8_t *)data;
56   uint8_t *be = bp + len;
57 
58   for (; bp < be; ++bp) {
59     hval ^= (uint32_t)xfrm(*bp);
60     hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
61   }
62 }
63 
64 struct ATSHash64FNV1a : ATSHash64 {
65   ATSHash64FNV1a();
66 
67   template <typename Transform> void update(const void *data, size_t len, Transform xfrm);
68   void
updateATSHash64FNV1a69   update(const void *data, size_t len) override
70   {
71     update(data, len, ATSHash::nullxfrm());
72   }
73 
74   void final() override;
75   uint64_t get() const override;
76   void clear() override;
77 
78 private:
79   uint64_t hval;
80 };
81 
82 template <typename Transform>
83 void
update(const void * data,size_t len,Transform xfrm)84 ATSHash64FNV1a::update(const void *data, size_t len, Transform xfrm)
85 {
86   uint8_t *bp = (uint8_t *)data;
87   uint8_t *be = bp + len;
88 
89   for (; bp < be; ++bp) {
90     hval ^= (uint64_t)xfrm(*bp);
91     hval += (hval << 1) + (hval << 4) + (hval << 5) + (hval << 7) + (hval << 8) + (hval << 40);
92   }
93 }
94