| 1 |
// Copyright 2021 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 navigation |
| 15 |
|
| 16 |
import ( |
| 17 |
"slices" |
| 18 |
"sync" |
| 19 |
) |
| 20 |
|
| 21 |
type menuCacheEntry struct { |
| 22 |
in []Menu |
| 23 |
out Menu |
| 24 |
} |
| 25 |
|
| 26 |
func (entry menuCacheEntry) matches(menuList []Menu) bool { |
| 27 |
if len(entry.in) != len(menuList) { |
| 28 |
return false |
| 29 |
} |
| 30 |
for i, m := range menuList { |
| 31 |
if !slices.Equal(m, entry.in[i]) { |
| 32 |
return false |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
return true |
| 37 |
} |
| 38 |
|
| 39 |
// newMenuCache creates a new menuCache instance. |
| 40 |
func newMenuCache() *menuCache { |
| 41 |
return &menuCache{m: make(map[string][]menuCacheEntry)} |
| 42 |
} |
| 43 |
|
| 44 |
type menuCache struct { |
| 45 |
sync.RWMutex |
| 46 |
m map[string][]menuCacheEntry |
| 47 |
} |
| 48 |
|
| 49 |
// get retrieves a menu from the cache based on the provided key and menuLists. |
| 50 |
// If the menu is not found, it applies the provided function and caches the result. |
| 51 |
func (c *menuCache) get(key string, apply func(m Menu), menuLists ...Menu) (Menu, bool) { |
| 52 |
return c.getP(key, func(m *Menu) { |
| 53 |
if apply != nil { |
| 54 |
apply(*m) |
| 55 |
} |
| 56 |
}, menuLists...) |
| 57 |
} |
| 58 |
|
| 59 |
// getP is similar to get but also returns a boolean indicating whether the menu was found in the cache. |
| 60 |
func (c *menuCache) getP(key string, apply func(m *Menu), menuLists ...Menu) (Menu, bool) { |
| 61 |
c.Lock() |
| 62 |
defer c.Unlock() |
| 63 |
|
| 64 |
if cached, ok := c.m[key]; ok { |
| 65 |
for _, entry := range cached { |
| 66 |
if entry.matches(menuLists) { |
| 67 |
return entry.out, true |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
m := menuLists[0] |
| 73 |
menuCopy := slices.Clone(m) |
| 74 |
|
| 75 |
if apply != nil { |
| 76 |
apply(&menuCopy) |
| 77 |
} |
| 78 |
|
| 79 |
entry := menuCacheEntry{in: menuLists, out: menuCopy} |
| 80 |
if v, ok := c.m[key]; ok { |
| 81 |
c.m[key] = append(v, entry) |
| 82 |
} else { |
| 83 |
c.m[key] = []menuCacheEntry{entry} |
| 84 |
} |
| 85 |
|
| 86 |
return menuCopy, false |
| 87 |
} |