|
| 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 hashing |
| 15 | + |
| 16 | +import ( |
| 17 | + "strings" |
| 18 | + "testing" |
| 19 | + |
| 20 | + "github.com/cespare/xxhash/v2" |
| 21 | + qt "github.com/frankban/quicktest" |
| 22 | +) |
| 23 | + |
| 24 | +func TestXxHashFromReader(t *testing.T) { |
| 25 | + c := qt.New(t) |
| 26 | + s := "Hello World" |
| 27 | + r := strings.NewReader(s) |
| 28 | + got, size, err := XXHashFromReader(r) |
| 29 | + c.Assert(err, qt.IsNil) |
| 30 | + c.Assert(size, qt.Equals, int64(len(s))) |
| 31 | + c.Assert(got, qt.Equals, uint64(7148569436472236994)) |
| 32 | +} |
| 33 | + |
| 34 | +func TestXxHashFromString(t *testing.T) { |
| 35 | + c := qt.New(t) |
| 36 | + s := "Hello World" |
| 37 | + got, err := XXHashFromString(s) |
| 38 | + c.Assert(err, qt.IsNil) |
| 39 | + c.Assert(got, qt.Equals, uint64(7148569436472236994)) |
| 40 | +} |
| 41 | + |
| 42 | +func TestXxHashFromStringHexEncoded(t *testing.T) { |
| 43 | + c := qt.New(t) |
| 44 | + s := "The quick brown fox jumps over the lazy dog" |
| 45 | + got := XxHashFromStringHexEncoded(s) |
| 46 | + // Facit: https://asecuritysite.com/encryption/xxhash?val=The%20quick%20brown%20fox%20jumps%20over%20the%20lazy%20dog |
| 47 | + c.Assert(got, qt.Equals, "0b242d361fda71bc") |
| 48 | +} |
| 49 | + |
| 50 | +func BenchmarkXXHashFromReader(b *testing.B) { |
| 51 | + r := strings.NewReader("Hello World") |
| 52 | + b.ResetTimer() |
| 53 | + for i := 0; i < b.N; i++ { |
| 54 | + XXHashFromReader(r) |
| 55 | + r.Seek(0, 0) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +func BenchmarkXXHashFromString(b *testing.B) { |
| 60 | + s := "Hello World" |
| 61 | + b.ResetTimer() |
| 62 | + for i := 0; i < b.N; i++ { |
| 63 | + XXHashFromString(s) |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +func BenchmarkXXHashFromStringHexEncoded(b *testing.B) { |
| 68 | + s := "The quick brown fox jumps over the lazy dog" |
| 69 | + b.ResetTimer() |
| 70 | + for i := 0; i < b.N; i++ { |
| 71 | + XxHashFromStringHexEncoded(s) |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +func xxHashFromString(f string) uint64 { |
| 76 | + h := xxhash.New() |
| 77 | + h.WriteString(f) |
| 78 | + return h.Sum64() |
| 79 | +} |
0 commit comments