go.temporal.io/server@v1.23.0/common/predicates/or.go (about) 1 // The MIT License 2 // 3 // Copyright (c) 2020 Temporal Technologies Inc. All rights reserved. 4 // 5 // Copyright (c) 2020 Uber Technologies, Inc. 6 // 7 // Permission is hereby granted, free of charge, to any person obtaining a copy 8 // of this software and associated documentation files (the "Software"), to deal 9 // in the Software without restriction, including without limitation the rights 10 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 // copies of the Software, and to permit persons to whom the Software is 12 // furnished to do so, subject to the following conditions: 13 // 14 // The above copyright notice and this permission notice shall be included in 15 // all copies or substantial portions of the Software. 16 // 17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 // THE SOFTWARE. 24 25 package predicates 26 27 import ( 28 "fmt" 29 ) 30 31 type ( 32 OrImpl[T any] struct { 33 // TODO: see if we can somehow order arbitrary predicats and store a sorted list 34 Predicates []Predicate[T] 35 } 36 ) 37 38 func Or[T any]( 39 predicates ...Predicate[T], 40 ) Predicate[T] { 41 if len(predicates) < 2 { 42 panic(fmt.Sprintf("Or requires at least 2 predicates, got %v", len(predicates))) 43 } 44 45 flattened := make([]Predicate[T], 0, len(predicates)) 46 for _, p := range predicates { 47 switch p := p.(type) { 48 case *OrImpl[T]: 49 flattened = appendPredicates(flattened, p.Predicates...) 50 case *UniversalImpl[T]: 51 return p 52 case *EmptyImpl[T]: 53 continue 54 default: 55 flattened = appendPredicates(flattened, p) 56 } 57 } 58 59 switch len(flattened) { 60 case 0: 61 return Empty[T]() 62 case 1: 63 return flattened[0] 64 default: 65 return &OrImpl[T]{ 66 Predicates: flattened, 67 } 68 } 69 } 70 71 func (o *OrImpl[T]) Test(t T) bool { 72 for _, p := range o.Predicates { 73 if p.Test(t) { 74 return true 75 } 76 } 77 78 return false 79 } 80 81 func (o *OrImpl[T]) Equals( 82 predicate Predicate[T], 83 ) bool { 84 orPredicate, ok := predicate.(*OrImpl[T]) 85 if !ok { 86 return false 87 } 88 89 return predicatesEqual(o.Predicates, orPredicate.Predicates) 90 }