Debian Codegraph @

td/uniq_type_behind.go

raw
1 // Copyright (c) 2018-2021, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package td
8
9 import (
10 "reflect"
11 )
12
13 // uniqTypeBehindSlice can return a non-nil reflect.Type if all items
14 // known non-interface types are equal, or if only interface types
15 // are found (mostly issued from Isa()) and they are equal.
16 func uniqTypeBehindSlice(items []reflect.Value) reflect.Type {
17 var (
18 lastIfType, lastType, curType reflect.Type
19 severalIfTypes bool
20 )
21
22 for _, item := range items {
23 if !item.IsValid() {
24 return nil // no need to go further
25 }
26
27 if item.Type().Implements(testDeeper) {
28 curType = item.Interface().(TestDeep).TypeBehind()
29
30 // Ignore unknown TypeBehind
31 if curType == nil {
32 continue
33 }
34
35 // Ignore interfaces & interface pointers too (see Isa), but
36 // keep them in mind in case we encounter always the same
37 // interface pointer
38 if curType.Kind() == reflect.Interface ||
39 (curType.Kind() == reflect.Ptr &&
40 curType.Elem().Kind() == reflect.Interface) {
41 if lastIfType == nil {
42 lastIfType = curType
43 } else if lastIfType != curType {
44 severalIfTypes = true
45 }
46 continue
47 }
48 } else {
49 curType = item.Type()
50 }
51
52 if lastType != curType {
53 if lastType != nil {
54 return nil
55 }
56 lastType = curType
57 }
58 }
59
60 // Only one type found
61 if lastType != nil {
62 return lastType
63 }
64
65 // Only one interface type found
66 if lastIfType != nil && !severalIfTypes {
67 return lastIfType
68 }
69 return nil
70 }