| 1 |
// Copyright 2019 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 collections provides template functions for manipulating collections |
| 15 |
// such as arrays, maps, and slices. |
| 16 |
package collections |
| 17 |
|
| 18 |
import ( |
| 19 |
"context" |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"math/rand/v2" |
| 23 |
"reflect" |
| 24 |
"strings" |
| 25 |
"time" |
| 26 |
|
| 27 |
"github.com/gohugoio/hugo/common/collections" |
| 28 |
"github.com/gohugoio/hugo/common/hmaps" |
| 29 |
"github.com/gohugoio/hugo/common/hreflect" |
| 30 |
"github.com/gohugoio/hugo/common/hstore" |
| 31 |
"github.com/gohugoio/hugo/common/types" |
| 32 |
"github.com/gohugoio/hugo/deps" |
| 33 |
"github.com/gohugoio/hugo/langs" |
| 34 |
"github.com/gohugoio/hugo/tpl/compare" |
| 35 |
"github.com/spf13/cast" |
| 36 |
) |
| 37 |
|
| 38 |
// New returns a new instance of the collections-namespaced template functions. |
| 39 |
func New(deps *deps.Deps) *Namespace { |
| 40 |
language := deps.Conf.Language().(*langs.Language) |
| 41 |
if language == nil { |
| 42 |
panic("language must be set") |
| 43 |
} |
| 44 |
loc := langs.GetLocation(language) |
| 45 |
|
| 46 |
dCache := hmaps.NewCacheWithOptions[dKey, []int](hmaps.CacheOptions{Size: 100}) |
| 47 |
|
| 48 |
return &Namespace{ |
| 49 |
loc: loc, |
| 50 |
sortComp: compare.New(loc, true), |
| 51 |
dCache: dCache, |
| 52 |
deps: deps, |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
// Namespace provides template functions for the "collections" namespace. |
| 57 |
type Namespace struct { |
| 58 |
loc *time.Location |
| 59 |
sortComp *compare.Namespace |
| 60 |
dCache *hmaps.Cache[dKey, []int] |
| 61 |
deps *deps.Deps |
| 62 |
} |
| 63 |
|
| 64 |
// After returns all the items after the first n items in list l. |
| 65 |
func (ns *Namespace) After(n any, l any) (any, error) { |
| 66 |
if n == nil || l == nil { |
| 67 |
return nil, errors.New("both limit and seq must be provided") |
| 68 |
} |
| 69 |
|
| 70 |
nv, err := cast.ToIntE(n) |
| 71 |
if err != nil { |
| 72 |
return nil, err |
| 73 |
} |
| 74 |
|
| 75 |
if nv < 0 { |
| 76 |
return nil, errors.New("sequence bounds out of range [" + cast.ToString(nv) + ":]") |
| 77 |
} |
| 78 |
|
| 79 |
lv := reflect.ValueOf(l) |
| 80 |
lv, isNil := hreflect.Indirect(lv) |
| 81 |
if isNil { |
| 82 |
return nil, errors.New("can't iterate over a nil value") |
| 83 |
} |
| 84 |
|
| 85 |
switch lv.Kind() { |
| 86 |
case reflect.Array, reflect.Slice, reflect.String: |
| 87 |
// okay |
| 88 |
default: |
| 89 |
return nil, errors.New("can't iterate over " + reflect.ValueOf(l).Type().String()) |
| 90 |
} |
| 91 |
|
| 92 |
if nv >= lv.Len() { |
| 93 |
return lv.Slice(0, 0).Interface(), nil |
| 94 |
} |
| 95 |
|
| 96 |
return lv.Slice(nv, lv.Len()).Interface(), nil |
| 97 |
} |
| 98 |
|
| 99 |
// Delimit takes a given list l and returns a string delimited by sep. |
| 100 |
// If last is passed to the function, it will be used as the final delimiter. |
| 101 |
func (ns *Namespace) Delimit(ctx context.Context, l, sep any, last ...any) (string, error) { |
| 102 |
d, err := cast.ToStringE(sep) |
| 103 |
if err != nil { |
| 104 |
return "", err |
| 105 |
} |
| 106 |
|
| 107 |
var dLast *string |
| 108 |
if len(last) > 0 { |
| 109 |
l := last[0] |
| 110 |
dStr, err := cast.ToStringE(l) |
| 111 |
if err != nil { |
| 112 |
dLast = nil |
| 113 |
} else { |
| 114 |
dLast = &dStr |
| 115 |
} |
| 116 |
} |
| 117 |
|
| 118 |
lv := reflect.ValueOf(l) |
| 119 |
lv, isNil := hreflect.Indirect(lv) |
| 120 |
if isNil { |
| 121 |
return "", errors.New("can't iterate over a nil value") |
| 122 |
} |
| 123 |
|
| 124 |
var str strings.Builder |
| 125 |
switch lv.Kind() { |
| 126 |
case reflect.Map: |
| 127 |
sortSeq, err := ns.Sort(ctx, l) |
| 128 |
if err != nil { |
| 129 |
return "", err |
| 130 |
} |
| 131 |
lv = reflect.ValueOf(sortSeq) |
| 132 |
fallthrough |
| 133 |
case reflect.Array, reflect.Slice, reflect.String: |
| 134 |
for i := range lv.Len() { |
| 135 |
val := lv.Index(i).Interface() |
| 136 |
valStr, err := cast.ToStringE(val) |
| 137 |
if err != nil { |
| 138 |
continue |
| 139 |
} |
| 140 |
switch { |
| 141 |
case i == lv.Len()-2 && dLast != nil: |
| 142 |
str.WriteString(valStr + *dLast) |
| 143 |
case i == lv.Len()-1: |
| 144 |
str.WriteString(valStr) |
| 145 |
default: |
| 146 |
str.WriteString(valStr + d) |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
default: |
| 151 |
return "", fmt.Errorf("can't iterate over %T", l) |
| 152 |
} |
| 153 |
|
| 154 |
return str.String(), nil |
| 155 |
} |
| 156 |
|
| 157 |
// Dictionary creates a new map from the given parameters by |
| 158 |
// treating values as key-value pairs. The number of values must be even. |
| 159 |
// The keys can be string slices, which will create the needed nested structure. |
| 160 |
func (ns *Namespace) Dictionary(values ...any) (map[string]any, error) { |
| 161 |
if len(values)%2 != 0 { |
| 162 |
return nil, errors.New("invalid dictionary call") |
| 163 |
} |
| 164 |
|
| 165 |
root := make(map[string]any) |
| 166 |
|
| 167 |
for i := 0; i < len(values); i += 2 { |
| 168 |
dict := root |
| 169 |
var key string |
| 170 |
switch v := values[i].(type) { |
| 171 |
case string: |
| 172 |
key = v |
| 173 |
case []string: |
| 174 |
for i := range len(v) - 1 { |
| 175 |
key = v[i] |
| 176 |
var m map[string]any |
| 177 |
v, found := dict[key] |
| 178 |
if found { |
| 179 |
m = v.(map[string]any) |
| 180 |
} else { |
| 181 |
m = make(map[string]any) |
| 182 |
dict[key] = m |
| 183 |
} |
| 184 |
dict = m |
| 185 |
} |
| 186 |
key = v[len(v)-1] |
| 187 |
default: |
| 188 |
return nil, errors.New("invalid dictionary key") |
| 189 |
} |
| 190 |
dict[key] = values[i+1] |
| 191 |
} |
| 192 |
|
| 193 |
return root, nil |
| 194 |
} |
| 195 |
|
| 196 |
// First returns the first limit items in list l. |
| 197 |
func (ns *Namespace) First(limit any, l any) (any, error) { |
| 198 |
if limit == nil || l == nil { |
| 199 |
return nil, errors.New("both limit and seq must be provided") |
| 200 |
} |
| 201 |
|
| 202 |
limitv, err := cast.ToIntE(limit) |
| 203 |
if err != nil { |
| 204 |
return nil, err |
| 205 |
} |
| 206 |
|
| 207 |
if limitv < 0 { |
| 208 |
return nil, errors.New("sequence length must be non-negative") |
| 209 |
} |
| 210 |
|
| 211 |
lv := reflect.ValueOf(l) |
| 212 |
lv, isNil := hreflect.Indirect(lv) |
| 213 |
if isNil { |
| 214 |
return nil, errors.New("can't iterate over a nil value") |
| 215 |
} |
| 216 |
|
| 217 |
switch lv.Kind() { |
| 218 |
case reflect.Array, reflect.Slice, reflect.String: |
| 219 |
// okay |
| 220 |
default: |
| 221 |
return nil, errors.New("can't iterate over " + reflect.ValueOf(l).Type().String()) |
| 222 |
} |
| 223 |
|
| 224 |
if limitv > lv.Len() { |
| 225 |
limitv = lv.Len() |
| 226 |
} |
| 227 |
|
| 228 |
return lv.Slice(0, limitv).Interface(), nil |
| 229 |
} |
| 230 |
|
| 231 |
// In returns whether v is in the list l. l may be an array or slice. |
| 232 |
func (ns *Namespace) In(l any, v any) (bool, error) { |
| 233 |
if l == nil || v == nil { |
| 234 |
return false, nil |
| 235 |
} |
| 236 |
|
| 237 |
lv := reflect.ValueOf(l) |
| 238 |
vv := reflect.ValueOf(v) |
| 239 |
|
| 240 |
vvk := normalize(vv) |
| 241 |
|
| 242 |
switch lv.Kind() { |
| 243 |
case reflect.Array, reflect.Slice: |
| 244 |
for i := range lv.Len() { |
| 245 |
lvv, isNil := hreflect.Indirect(lv.Index(i)) |
| 246 |
if isNil { |
| 247 |
continue |
| 248 |
} |
| 249 |
|
| 250 |
lvvk := normalize(lvv) |
| 251 |
|
| 252 |
if lvvk == vvk { |
| 253 |
return true, nil |
| 254 |
} |
| 255 |
} |
| 256 |
} |
| 257 |
ss, err := cast.ToStringE(l) |
| 258 |
if err != nil { |
| 259 |
return false, nil |
| 260 |
} |
| 261 |
|
| 262 |
su, err := cast.ToStringE(v) |
| 263 |
if err != nil { |
| 264 |
return false, nil |
| 265 |
} |
| 266 |
return strings.Contains(ss, su), nil |
| 267 |
} |
| 268 |
|
| 269 |
// Intersect returns the common elements in the given sets, l1 and l2. l1 and |
| 270 |
// l2 must be of the same type and may be either arrays or slices. |
| 271 |
func (ns *Namespace) Intersect(l1, l2 any) (any, error) { |
| 272 |
if l1 == nil || l2 == nil { |
| 273 |
return make([]any, 0), nil |
| 274 |
} |
| 275 |
|
| 276 |
var ins *intersector |
| 277 |
|
| 278 |
l1v := reflect.ValueOf(l1) |
| 279 |
l2v := reflect.ValueOf(l2) |
| 280 |
|
| 281 |
switch l1v.Kind() { |
| 282 |
case reflect.Array, reflect.Slice: |
| 283 |
ins = &intersector{r: reflect.MakeSlice(l1v.Type(), 0, 0), seen: make(map[any]bool)} |
| 284 |
switch l2v.Kind() { |
| 285 |
case reflect.Array, reflect.Slice: |
| 286 |
for i := range l1v.Len() { |
| 287 |
l1vv := l1v.Index(i) |
| 288 |
if !l1vv.Type().Comparable() { |
| 289 |
return make([]any, 0), errors.New("intersect does not support slices or arrays of uncomparable types") |
| 290 |
} |
| 291 |
|
| 292 |
for j := range l2v.Len() { |
| 293 |
l2vv := l2v.Index(j) |
| 294 |
if !l2vv.Type().Comparable() { |
| 295 |
return make([]any, 0), errors.New("intersect does not support slices or arrays of uncomparable types") |
| 296 |
} |
| 297 |
|
| 298 |
ins.handleValuePair(l1vv, l2vv) |
| 299 |
} |
| 300 |
} |
| 301 |
return ins.r.Interface(), nil |
| 302 |
default: |
| 303 |
return nil, errors.New("can't iterate over " + reflect.ValueOf(l2).Type().String()) |
| 304 |
} |
| 305 |
default: |
| 306 |
return nil, errors.New("can't iterate over " + reflect.ValueOf(l1).Type().String()) |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
// Group groups a set of items by the given key. |
| 311 |
// This is currently only supported for Pages. |
| 312 |
func (ns *Namespace) Group(key any, items any) (any, error) { |
| 313 |
if key == nil { |
| 314 |
return nil, errors.New("nil is not a valid key to group by") |
| 315 |
} |
| 316 |
|
| 317 |
if g, ok := items.(collections.Grouper); ok { |
| 318 |
return g.Group(key, items) |
| 319 |
} |
| 320 |
|
| 321 |
in := newSliceElement(items) |
| 322 |
|
| 323 |
if g, ok := in.(collections.Grouper); ok { |
| 324 |
return g.Group(key, items) |
| 325 |
} |
| 326 |
|
| 327 |
return nil, fmt.Errorf("grouping not supported for type %T %T", items, in) |
| 328 |
} |
| 329 |
|
| 330 |
// IsSet returns whether a given array, channel, slice, or map in c has the given key |
| 331 |
// defined. |
| 332 |
func (ns *Namespace) IsSet(c any, key any) (bool, error) { |
| 333 |
av := reflect.ValueOf(c) |
| 334 |
kv := reflect.ValueOf(key) |
| 335 |
|
| 336 |
switch av.Kind() { |
| 337 |
case reflect.Array, reflect.Chan, reflect.Slice: |
| 338 |
k, err := cast.ToIntE(key) |
| 339 |
if err != nil { |
| 340 |
return false, fmt.Errorf("isset unable to use key of type %T as index", key) |
| 341 |
} |
| 342 |
if av.Len() > k { |
| 343 |
return true, nil |
| 344 |
} |
| 345 |
case reflect.Map: |
| 346 |
if kv.Type() == av.Type().Key() { |
| 347 |
return av.MapIndex(kv).IsValid(), nil |
| 348 |
} |
| 349 |
default: |
| 350 |
ns.deps.Log.Warnf("calling IsSet with unsupported type %q (%T) for key %v will always return false.\n", av.Kind(), c, key) |
| 351 |
} |
| 352 |
|
| 353 |
return false, nil |
| 354 |
} |
| 355 |
|
| 356 |
// Last returns the last limit items in the list l. |
| 357 |
func (ns *Namespace) Last(limit any, l any) (any, error) { |
| 358 |
if limit == nil || l == nil { |
| 359 |
return nil, errors.New("both limit and seq must be provided") |
| 360 |
} |
| 361 |
|
| 362 |
limitv, err := cast.ToIntE(limit) |
| 363 |
if err != nil { |
| 364 |
return nil, err |
| 365 |
} |
| 366 |
|
| 367 |
if limitv < 0 { |
| 368 |
return nil, errors.New("sequence length must be non-negative") |
| 369 |
} |
| 370 |
|
| 371 |
seqv := reflect.ValueOf(l) |
| 372 |
seqv, isNil := hreflect.Indirect(seqv) |
| 373 |
if isNil { |
| 374 |
return nil, errors.New("can't iterate over a nil value") |
| 375 |
} |
| 376 |
|
| 377 |
switch seqv.Kind() { |
| 378 |
case reflect.Array, reflect.Slice, reflect.String: |
| 379 |
// okay |
| 380 |
default: |
| 381 |
return nil, errors.New("can't iterate over " + reflect.ValueOf(l).Type().String()) |
| 382 |
} |
| 383 |
|
| 384 |
if limitv > seqv.Len() { |
| 385 |
limitv = seqv.Len() |
| 386 |
} |
| 387 |
|
| 388 |
return seqv.Slice(seqv.Len()-limitv, seqv.Len()).Interface(), nil |
| 389 |
} |
| 390 |
|
| 391 |
// Reverse creates a copy of the list l and reverses it. |
| 392 |
func (ns *Namespace) Reverse(l any) (any, error) { |
| 393 |
if l == nil { |
| 394 |
return nil, nil |
| 395 |
} |
| 396 |
v := reflect.ValueOf(l) |
| 397 |
|
| 398 |
switch v.Kind() { |
| 399 |
case reflect.Slice: |
| 400 |
default: |
| 401 |
return nil, errors.New("argument must be a slice") |
| 402 |
} |
| 403 |
|
| 404 |
sliceCopy := reflect.MakeSlice(v.Type(), v.Len(), v.Len()) |
| 405 |
|
| 406 |
for i := v.Len() - 1; i >= 0; i-- { |
| 407 |
element := sliceCopy.Index(i) |
| 408 |
element.Set(v.Index(v.Len() - 1 - i)) |
| 409 |
} |
| 410 |
|
| 411 |
return sliceCopy.Interface(), nil |
| 412 |
} |
| 413 |
|
| 414 |
// Sanity check for slices created by Seq and D. |
| 415 |
const maxSeqSize = 1000000 |
| 416 |
|
| 417 |
var errSeqSizeExceedsLimit = errors.New("size of result exceeds limit") |
| 418 |
|
| 419 |
// Seq creates a sequence of integers from args. It's named and used as GNU's seq. |
| 420 |
// |
| 421 |
// Examples: |
| 422 |
// |
| 423 |
// 3 => 1, 2, 3 |
| 424 |
// 1 2 4 => 1, 3 |
| 425 |
// -3 => -1, -2, -3 |
| 426 |
// 1 4 => 1, 2, 3, 4 |
| 427 |
// 1 -2 => 1, 0, -1, -2 |
| 428 |
func (ns *Namespace) Seq(args ...any) ([]int, error) { |
| 429 |
if len(args) < 1 || len(args) > 3 { |
| 430 |
return nil, errors.New("invalid number of arguments to Seq") |
| 431 |
} |
| 432 |
|
| 433 |
intArgs := cast.ToIntSlice(args) |
| 434 |
if len(intArgs) < 1 || len(intArgs) > 3 { |
| 435 |
return nil, errors.New("invalid arguments to Seq") |
| 436 |
} |
| 437 |
|
| 438 |
inc := 1 |
| 439 |
var last int |
| 440 |
first := intArgs[0] |
| 441 |
|
| 442 |
if len(intArgs) == 1 { |
| 443 |
last = first |
| 444 |
if last == 0 { |
| 445 |
return []int{}, nil |
| 446 |
} else if last > 0 { |
| 447 |
first = 1 |
| 448 |
} else { |
| 449 |
first = -1 |
| 450 |
inc = -1 |
| 451 |
} |
| 452 |
} else if len(intArgs) == 2 { |
| 453 |
last = intArgs[1] |
| 454 |
if last < first { |
| 455 |
inc = -1 |
| 456 |
} |
| 457 |
} else { |
| 458 |
inc = intArgs[1] |
| 459 |
last = intArgs[2] |
| 460 |
if inc == 0 { |
| 461 |
return nil, errors.New("'increment' must not be 0") |
| 462 |
} |
| 463 |
if first < last && inc < 0 { |
| 464 |
return nil, errors.New("'increment' must be > 0") |
| 465 |
} |
| 466 |
if first > last && inc > 0 { |
| 467 |
return nil, errors.New("'increment' must be < 0") |
| 468 |
} |
| 469 |
} |
| 470 |
|
| 471 |
// sanity check |
| 472 |
if last < -maxSeqSize { |
| 473 |
return nil, errSeqSizeExceedsLimit |
| 474 |
} |
| 475 |
size := ((last - first) / inc) + 1 |
| 476 |
|
| 477 |
// sanity check |
| 478 |
if size <= 0 || size > maxSeqSize { |
| 479 |
return nil, errSeqSizeExceedsLimit |
| 480 |
} |
| 481 |
|
| 482 |
seq := make([]int, size) |
| 483 |
val := first |
| 484 |
for i := 0; ; i++ { |
| 485 |
seq[i] = val |
| 486 |
val += inc |
| 487 |
if (inc < 0 && val < last) || (inc > 0 && val > last) { |
| 488 |
break |
| 489 |
} |
| 490 |
} |
| 491 |
|
| 492 |
return seq, nil |
| 493 |
} |
| 494 |
|
| 495 |
// Shuffle returns list l in a randomized order. |
| 496 |
func (ns *Namespace) Shuffle(l any) (any, error) { |
| 497 |
if l == nil { |
| 498 |
return nil, errors.New("both count and seq must be provided") |
| 499 |
} |
| 500 |
|
| 501 |
lv := reflect.ValueOf(l) |
| 502 |
lv, isNil := hreflect.Indirect(lv) |
| 503 |
if isNil { |
| 504 |
return nil, errors.New("can't iterate over a nil value") |
| 505 |
} |
| 506 |
|
| 507 |
switch lv.Kind() { |
| 508 |
case reflect.Array, reflect.Slice, reflect.String: |
| 509 |
// okay |
| 510 |
default: |
| 511 |
return nil, errors.New("can't iterate over " + reflect.ValueOf(l).Type().String()) |
| 512 |
} |
| 513 |
|
| 514 |
shuffled := reflect.MakeSlice(reflect.TypeOf(l), lv.Len(), lv.Len()) |
| 515 |
|
| 516 |
randomIndices := rand.Perm(lv.Len()) |
| 517 |
|
| 518 |
for index, value := range randomIndices { |
| 519 |
shuffled.Index(value).Set(lv.Index(index)) |
| 520 |
} |
| 521 |
|
| 522 |
return shuffled.Interface(), nil |
| 523 |
} |
| 524 |
|
| 525 |
// Slice returns a slice of all passed arguments. |
| 526 |
func (ns *Namespace) Slice(args ...any) any { |
| 527 |
if len(args) == 0 { |
| 528 |
return args |
| 529 |
} |
| 530 |
|
| 531 |
return collections.Slice(args...) |
| 532 |
} |
| 533 |
|
| 534 |
type dKey struct { |
| 535 |
seed uint64 |
| 536 |
n int |
| 537 |
hi int |
| 538 |
} |
| 539 |
|
| 540 |
// D returns a sorted slice of unique random integers in the half-open interval |
| 541 |
// [0, hi) using the provided seed value. The number of elements in the |
| 542 |
// resulting slice is n or hi, whichever is less. |
| 543 |
// |
| 544 |
// If n <= hi, it returns a sorted random sample of size n using J. S. Vitter’s |
| 545 |
// Method D for sequential random sampling. |
| 546 |
// |
| 547 |
// If n > hi, it returns the full, sorted range [0, hi) of size hi. |
| 548 |
// |
| 549 |
// If n == 0 or hi == 0, it returns an empty slice. |
| 550 |
// |
| 551 |
// Reference: |
| 552 |
// |
| 553 |
// J. S. Vitter, "An efficient algorithm for sequential random sampling," ACM Trans. Math. Softw., vol. 11, no. 1, pp. 37–57, 1985. |
| 554 |
// See also: https://getkerf.wordpress.com/2016/03/30/the-best-algorithm-no-one-knows-about/ |
| 555 |
func (ns *Namespace) D(seed, n, hi any) ([]int, error) { |
| 556 |
seedInt, err := cast.ToInt64E(seed) |
| 557 |
if err != nil || seedInt < 0 { |
| 558 |
return nil, fmt.Errorf("the seed value (%v) must be a non-negative integer", seed) |
| 559 |
} |
| 560 |
|
| 561 |
nInt, err := cast.ToIntE(n) |
| 562 |
if err != nil || nInt < 0 || nInt > maxSeqSize { |
| 563 |
return nil, fmt.Errorf("the number of requested values (%v) must be a non-negative integer <= %d", n, maxSeqSize) |
| 564 |
} |
| 565 |
|
| 566 |
hiInt, err := cast.ToIntE(hi) |
| 567 |
if err != nil || hiInt < 0 || hiInt > maxSeqSize { |
| 568 |
return nil, fmt.Errorf("the maximum requested value (%v) must be a non-negative integer <= %d", hi, maxSeqSize) |
| 569 |
} |
| 570 |
|
| 571 |
if nInt == 0 || hiInt == 0 { |
| 572 |
return []int{}, nil |
| 573 |
} |
| 574 |
|
| 575 |
key := dKey{seed: uint64(seedInt), n: nInt, hi: hiInt} |
| 576 |
|
| 577 |
v, err := ns.dCache.GetOrCreate(key, func() ([]int, error) { |
| 578 |
if key.n > key.hi { |
| 579 |
result := make([]int, key.hi) |
| 580 |
for i := 0; i < key.hi; i++ { |
| 581 |
result[i] = i |
| 582 |
} |
| 583 |
return result, nil |
| 584 |
} |
| 585 |
|
| 586 |
prng := rand.New(rand.NewPCG(key.seed, 0)) |
| 587 |
result := make([]int, 0, key.n) |
| 588 |
_d(prng, key.n, key.hi, func(i int) { |
| 589 |
result = append(result, i) |
| 590 |
}) |
| 591 |
|
| 592 |
return result, nil |
| 593 |
}) |
| 594 |
|
| 595 |
return v, err |
| 596 |
} |
| 597 |
|
| 598 |
type intersector struct { |
| 599 |
r reflect.Value |
| 600 |
seen map[any]bool |
| 601 |
} |
| 602 |
|
| 603 |
func (i *intersector) appendIfNotSeen(v reflect.Value) { |
| 604 |
k := normalize(v) |
| 605 |
if !i.seen[k] { |
| 606 |
i.r = reflect.Append(i.r, v) |
| 607 |
i.seen[k] = true |
| 608 |
} |
| 609 |
} |
| 610 |
|
| 611 |
func (i *intersector) handleValuePair(l1vv, l2vv reflect.Value) { |
| 612 |
switch kind := l1vv.Kind(); { |
| 613 |
case kind == reflect.String: |
| 614 |
l2t, err := hreflect.ToStringE(l2vv) |
| 615 |
if err == nil && l1vv.String() == l2t { |
| 616 |
i.appendIfNotSeen(l1vv) |
| 617 |
} |
| 618 |
case hreflect.IsNumber(kind): |
| 619 |
f1, err1 := hreflect.ToFloat64E(l1vv) |
| 620 |
f2, err2 := hreflect.ToFloat64E(l2vv) |
| 621 |
if err1 == nil && err2 == nil && f1 == f2 { |
| 622 |
i.appendIfNotSeen(l1vv) |
| 623 |
} |
| 624 |
case kind == reflect.Pointer, kind == reflect.Struct: |
| 625 |
if types.Unwrapv(l1vv.Interface()) == types.Unwrapv(l2vv.Interface()) { |
| 626 |
i.appendIfNotSeen(l1vv) |
| 627 |
} |
| 628 |
case kind == reflect.Interface: |
| 629 |
i.handleValuePair(reflect.ValueOf(l1vv.Interface()), l2vv) |
| 630 |
} |
| 631 |
} |
| 632 |
|
| 633 |
// Union returns the union of the given sets, l1 and l2. l1 and |
| 634 |
// l2 must be of the same type and may be either arrays or slices. |
| 635 |
// If l1 and l2 aren't of the same type then l1 will be returned. |
| 636 |
// If either l1 or l2 is nil then the non-nil list will be returned. |
| 637 |
func (ns *Namespace) Union(l1, l2 any) (any, error) { |
| 638 |
if l1 == nil && l2 == nil { |
| 639 |
return []any{}, nil |
| 640 |
} else if l1 == nil && l2 != nil { |
| 641 |
return l2, nil |
| 642 |
} else if l1 != nil && l2 == nil { |
| 643 |
return l1, nil |
| 644 |
} |
| 645 |
|
| 646 |
l1v := reflect.ValueOf(l1) |
| 647 |
l2v := reflect.ValueOf(l2) |
| 648 |
|
| 649 |
var ins *intersector |
| 650 |
|
| 651 |
switch l1v.Kind() { |
| 652 |
case reflect.Array, reflect.Slice: |
| 653 |
switch l2v.Kind() { |
| 654 |
case reflect.Array, reflect.Slice: |
| 655 |
ins = &intersector{r: reflect.MakeSlice(l1v.Type(), 0, 0), seen: make(map[any]bool)} |
| 656 |
|
| 657 |
if l1v.Type() != l2v.Type() && |
| 658 |
l1v.Type().Elem().Kind() != reflect.Interface && |
| 659 |
l2v.Type().Elem().Kind() != reflect.Interface { |
| 660 |
return ins.r.Interface(), nil |
| 661 |
} |
| 662 |
|
| 663 |
var ( |
| 664 |
l1vv reflect.Value |
| 665 |
isNil bool |
| 666 |
) |
| 667 |
|
| 668 |
for i := range l1v.Len() { |
| 669 |
l1vv, isNil = hreflect.Indirect(l1v.Index(i)) |
| 670 |
|
| 671 |
if !l1vv.Type().Comparable() { |
| 672 |
return []any{}, errors.New("union does not support slices or arrays of uncomparable types") |
| 673 |
} |
| 674 |
|
| 675 |
if !isNil { |
| 676 |
ins.appendIfNotSeen(l1vv) |
| 677 |
} |
| 678 |
} |
| 679 |
|
| 680 |
if !l1vv.IsValid() { |
| 681 |
// The first slice may be empty. Pick the first value of the second |
| 682 |
// to use as a prototype. |
| 683 |
if l2v.Len() > 0 { |
| 684 |
l1vv = l2v.Index(0) |
| 685 |
} |
| 686 |
} |
| 687 |
|
| 688 |
for j := range l2v.Len() { |
| 689 |
l2vv := l2v.Index(j) |
| 690 |
typ := l1vv.Type() |
| 691 |
|
| 692 |
switch kind := l1vv.Kind(); { |
| 693 |
case kind == reflect.String: |
| 694 |
l2t, err := hreflect.ToStringE(l2vv) |
| 695 |
if err == nil { |
| 696 |
ins.appendIfNotSeen(reflect.ValueOf(l2t)) |
| 697 |
} |
| 698 |
case hreflect.IsNumber(kind): |
| 699 |
var err error |
| 700 |
l2vv, err = convertNumber(l2vv, typ) |
| 701 |
if err == nil { |
| 702 |
ins.appendIfNotSeen(l2vv) |
| 703 |
} |
| 704 |
case kind == reflect.Interface, kind == reflect.Struct, kind == reflect.Pointer: |
| 705 |
ins.appendIfNotSeen(l2vv) |
| 706 |
|
| 707 |
} |
| 708 |
} |
| 709 |
|
| 710 |
return ins.r.Interface(), nil |
| 711 |
default: |
| 712 |
return nil, errors.New("can't iterate over " + reflect.ValueOf(l2).Type().String()) |
| 713 |
} |
| 714 |
default: |
| 715 |
return nil, errors.New("can't iterate over " + reflect.ValueOf(l1).Type().String()) |
| 716 |
} |
| 717 |
} |
| 718 |
|
| 719 |
// Uniq returns a new list with duplicate elements in the list l removed. |
| 720 |
func (ns *Namespace) Uniq(l any) (any, error) { |
| 721 |
if l == nil { |
| 722 |
return make([]any, 0), nil |
| 723 |
} |
| 724 |
|
| 725 |
v := reflect.ValueOf(l) |
| 726 |
var slice reflect.Value |
| 727 |
|
| 728 |
switch v.Kind() { |
| 729 |
case reflect.Slice: |
| 730 |
slice = reflect.MakeSlice(v.Type(), 0, 0) |
| 731 |
|
| 732 |
case reflect.Array: |
| 733 |
slice = reflect.MakeSlice(reflect.SliceOf(v.Type().Elem()), 0, 0) |
| 734 |
default: |
| 735 |
return nil, fmt.Errorf("type %T not supported", l) |
| 736 |
} |
| 737 |
|
| 738 |
seen := make(map[any]bool) |
| 739 |
|
| 740 |
for i := range v.Len() { |
| 741 |
ev, _ := hreflect.Indirect(v.Index(i)) |
| 742 |
|
| 743 |
key := normalize(ev) |
| 744 |
|
| 745 |
if _, found := seen[key]; !found { |
| 746 |
slice = reflect.Append(slice, ev) |
| 747 |
seen[key] = true |
| 748 |
} |
| 749 |
} |
| 750 |
|
| 751 |
return slice.Interface(), nil |
| 752 |
} |
| 753 |
|
| 754 |
// KeyVals creates a key and values wrapper. |
| 755 |
func (ns *Namespace) KeyVals(key any, values ...any) (types.KeyValues, error) { |
| 756 |
return types.KeyValues{Key: key, Values: values}, nil |
| 757 |
} |
| 758 |
|
| 759 |
// NewScratch creates a new Scratch which can be used to store values in a |
| 760 |
// thread safe way. |
| 761 |
func (ns *Namespace) NewScratch() *hstore.Scratch { |
| 762 |
return hstore.NewScratch() |
| 763 |
} |