| 1 |
// Copyright 2024 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
// Package hash provides non-cryptographic hash functions for template use. |
| 15 |
package hash |
| 16 |
|
| 17 |
import ( |
| 18 |
"crypto/md5" |
| 19 |
"encoding/hex" |
| 20 |
"fmt" |
| 21 |
"strings" |
| 22 |
"testing" |
| 23 |
|
| 24 |
qt "github.com/frankban/quicktest" |
| 25 |
"github.com/spf13/cast" |
| 26 |
) |
| 27 |
|
| 28 |
func TestXxHash(t *testing.T) { |
| 29 |
t.Parallel() |
| 30 |
c := qt.New(t) |
| 31 |
|
| 32 |
ns := New() |
| 33 |
|
| 34 |
h, err := ns.XxHash("The quick brown fox jumps over the lazy dog") |
| 35 |
c.Assert(err, qt.IsNil) |
| 36 |
// Facit: https://asecuritysite.com/encryption/xxhash?val=The%20quick%20brown%20fox%20jumps%20over%20the%20lazy%20dog |
| 37 |
c.Assert(h, qt.Equals, "0b242d361fda71bc") |
| 38 |
} |
| 39 |
|
| 40 |
func BenchmarkXxHash(b *testing.B) { |
| 41 |
const inputSmall = "The quick brown fox jumps over the lazy dog" |
| 42 |
inputLarge := strings.Repeat(inputSmall, 100) |
| 43 |
|
| 44 |
runBench := func(name, input string, b *testing.B, fn func(v any)) { |
| 45 |
b.Run(fmt.Sprintf("%s_%d", name, len(input)), func(b *testing.B) { |
| 46 |
for b.Loop() { |
| 47 |
fn(input) |
| 48 |
} |
| 49 |
}) |
| 50 |
} |
| 51 |
|
| 52 |
ns := New() |
| 53 |
fnXxHash := func(v any) { |
| 54 |
_, err := ns.XxHash(v) |
| 55 |
if err != nil { |
| 56 |
panic(err) |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
fnFNv32a := func(v any) { |
| 61 |
_, err := ns.FNV32a(v) |
| 62 |
if err != nil { |
| 63 |
panic(err) |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
// Copied from the crypto tpl/crypto package, |
| 68 |
// just to have something to compare the above with. |
| 69 |
fnMD5 := func(v any) { |
| 70 |
conv, err := cast.ToStringE(v) |
| 71 |
if err != nil { |
| 72 |
panic(err) |
| 73 |
} |
| 74 |
|
| 75 |
hash := md5.Sum([]byte(conv)) |
| 76 |
_ = hex.EncodeToString(hash[:]) |
| 77 |
} |
| 78 |
|
| 79 |
for _, input := range []string{inputSmall, inputLarge} { |
| 80 |
runBench("xxHash", input, b, fnXxHash) |
| 81 |
runBench("mdb5", input, b, fnMD5) |
| 82 |
runBench("fnv32a", input, b, fnFNv32a) |
| 83 |
} |
| 84 |
} |