github.com/tursom/GoCollections@v0.3.10/lang/Channel.go (about) 1 /* 2 * Copyright (c) 2022 tursom. All rights reserved. 3 * Use of this source code is governed by a GPL-3 4 * license that can be found in the LICENSE file. 5 */ 6 7 package lang 8 9 import "github.com/tursom/GoCollections/util/time" 10 11 type ( 12 SendChannel[T any] interface { 13 Close() 14 SCh() chan<- T 15 Send(obj T) 16 TrySend(obj T) bool 17 SendTimeout(obj T, timeout time.Duration) bool 18 } 19 20 ReceiveChannel[T any] interface { 21 Close() 22 // RCh raw channel 23 RCh() <-chan T 24 Receive() (T, bool) 25 TryReceive() (T, bool) 26 ReceiveTimeout(timeout time.Duration) (T, bool) 27 } 28 29 Channel[T any] interface { 30 SendChannel[T] 31 ReceiveChannel[T] 32 Ch() chan T 33 } 34 35 SendChannelProxy[T, P any] interface { 36 SendChannel[T] 37 ProxySendChannel() SendChannel[P] 38 } 39 40 ReceiveChannelProxy[T, P any] interface { 41 ReceiveChannel[T] 42 ProxyReceiveChannel() ReceiveChannel[P] 43 } 44 45 ChannelProxy[T, P any] interface { 46 Channel[T] 47 SendChannelProxy[T, P] 48 ReceiveChannelProxy[T, P] 49 ProxyChannel() Channel[P] 50 } 51 52 RawChannel[T any] chan T 53 54 withReceiveChannel[T any] struct { 55 ReceiveChannel[T] 56 closer func() 57 } 58 ) 59 60 func NewChannel[T any](cap int) RawChannel[T] { 61 return make(chan T, cap) 62 } 63 64 func WithReceiveChannel[T any](channel ReceiveChannel[T], closer func()) ReceiveChannel[T] { 65 return withReceiveChannel[T]{channel, closer} 66 } 67 68 func (ch RawChannel[T]) Ch() chan T { 69 return ch 70 } 71 72 func (ch RawChannel[T]) Close() { 73 close(ch) 74 } 75 76 func (ch RawChannel[T]) SCh() chan<- T { 77 return ch 78 } 79 80 func (ch RawChannel[T]) Send(obj T) { 81 ch <- obj 82 } 83 84 func (ch RawChannel[T]) TrySend(obj T) bool { 85 select { 86 case ch <- obj: 87 return true 88 default: 89 return false 90 } 91 } 92 93 func (ch RawChannel[T]) SendTimeout(obj T, timeout time.Duration) bool { 94 select { 95 case ch <- obj: 96 return true 97 case <-time.After(timeout): 98 return false 99 } 100 } 101 102 func (ch RawChannel[T]) RCh() <-chan T { 103 return ch 104 } 105 106 func (ch RawChannel[T]) Receive() (T, bool) { 107 value, ok := <-ch 108 return value, ok 109 } 110 111 func (ch RawChannel[T]) TryReceive() (T, bool) { 112 select { 113 case obj := <-ch: 114 return obj, true 115 default: 116 return Nil[T](), false 117 } 118 } 119 120 func (ch RawChannel[T]) ReceiveTimeout(timeout time.Duration) (T, bool) { 121 select { 122 case obj := <-ch: 123 return obj, true 124 case <-time.After(timeout): 125 return Nil[T](), false 126 } 127 } 128 129 func (i withReceiveChannel[T]) Close() { 130 if i.closer != nil { 131 i.closer() 132 } else { 133 i.ReceiveChannel.Close() 134 } 135 }