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