| 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 |
"context" |
| 19 |
"hash/fnv" |
| 20 |
|
| 21 |
"github.com/gohugoio/hugo/common/hashing" |
| 22 |
"github.com/gohugoio/hugo/deps" |
| 23 |
"github.com/gohugoio/hugo/tpl/internal" |
| 24 |
"github.com/spf13/cast" |
| 25 |
) |
| 26 |
|
| 27 |
// New returns a new instance of the hash-namespaced template functions. |
| 28 |
func New() *Namespace { |
| 29 |
return &Namespace{} |
| 30 |
} |
| 31 |
|
| 32 |
// Namespace provides template functions for the "hash" namespace. |
| 33 |
type Namespace struct{} |
| 34 |
|
| 35 |
// FNV32a hashes v using fnv32a algorithm. |
| 36 |
func (ns *Namespace) FNV32a(v any) (int, error) { |
| 37 |
conv, err := cast.ToStringE(v) |
| 38 |
if err != nil { |
| 39 |
return 0, err |
| 40 |
} |
| 41 |
algorithm := fnv.New32a() |
| 42 |
algorithm.Write([]byte(conv)) |
| 43 |
return int(algorithm.Sum32()), nil |
| 44 |
} |
| 45 |
|
| 46 |
// XxHash returns the xxHash of the input string. |
| 47 |
func (ns *Namespace) XxHash(v any) (string, error) { |
| 48 |
conv, err := cast.ToStringE(v) |
| 49 |
if err != nil { |
| 50 |
return "", err |
| 51 |
} |
| 52 |
|
| 53 |
return hashing.XxHashFromStringHexEncoded(conv), nil |
| 54 |
} |
| 55 |
|
| 56 |
const name = "hash" |
| 57 |
|
| 58 |
func init() { |
| 59 |
f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { |
| 60 |
ctx := New() |
| 61 |
|
| 62 |
ns := &internal.TemplateFuncsNamespace{ |
| 63 |
Name: name, |
| 64 |
Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, |
| 65 |
} |
| 66 |
|
| 67 |
ns.AddMethodMapping(ctx.FNV32a, |
| 68 |
nil, |
| 69 |
[][2]string{ |
| 70 |
{`{{ hash.FNV32a "Hugo Rocks!!" }}`, `1515779328`}, |
| 71 |
}, |
| 72 |
) |
| 73 |
|
| 74 |
ns.AddMethodMapping(ctx.XxHash, |
| 75 |
[]string{"xxhash"}, |
| 76 |
[][2]string{ |
| 77 |
{`{{ hash.XxHash "The quick brown fox jumps over the lazy dog" }}`, `0b242d361fda71bc`}, |
| 78 |
}, |
| 79 |
) |
| 80 |
|
| 81 |
return ns |
| 82 |
} |
| 83 |
|
| 84 |
internal.AddTemplateFuncsNamespace(f) |
| 85 |
} |