Debian Codegraph @

tpl/collections/symdiff.go

raw
1 // Copyright 2018 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
15
16 import (
17 "fmt"
18 "reflect"
19
20 "github.com/gohugoio/hugo/common/hreflect"
21 )
22
23 // SymDiff returns the symmetric difference of s1 and s2.
24 // Arguments must be either a slice or an array of comparable types.
25 func (ns *Namespace) SymDiff(s2, s1 any) (any, error) {
26 ids1, err := collectIdentities(s1)
27 if err != nil {
28 return nil, err
29 }
30 ids2, err := collectIdentities(s2)
31 if err != nil {
32 return nil, err
33 }
34
35 var slice reflect.Value
36 var sliceElemType reflect.Type
37
38 for i, s := range []any{s1, s2} {
39 v := reflect.ValueOf(s)
40
41 switch v.Kind() {
42 case reflect.Array, reflect.Slice:
43 if i == 0 {
44 sliceType := v.Type()
45 sliceElemType = sliceType.Elem()
46 slice = reflect.MakeSlice(sliceType, 0, 0)
47 }
48
49 for i := range v.Len() {
50 ev, _ := hreflect.Indirect(v.Index(i))
51 key := normalize(ev)
52
53 // Append if the key is not in their intersection.
54 if ids1[key] != ids2[key] {
55 v, err := convertValue(ev, sliceElemType)
56 if err != nil {
57 return nil, fmt.Errorf("symdiff: failed to convert value: %w", err)
58 }
59 slice = reflect.Append(slice, v)
60 }
61 }
62 default:
63 return nil, fmt.Errorf("arguments to symdiff must be slices or arrays")
64 }
65 }
66
67 return slice.Interface(), nil
68 }