File tree Expand file tree Collapse file tree 3 files changed +53
-0
lines changed Expand file tree Collapse file tree 3 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -10,6 +10,8 @@ type Channel[T any] interface {
10
10
ReceiveNonBlocking () (v T , ok bool )
11
11
12
12
Close ()
13
+
14
+ Len () int
13
15
}
14
16
15
17
type Receiver [T any ] struct {
@@ -52,6 +54,10 @@ type channel[T any] struct {
52
54
size int
53
55
}
54
56
57
+ func (c * channel [T ]) Len () int {
58
+ return len (c .c )
59
+ }
60
+
55
61
func (c * channel [T ]) Close () {
56
62
c .closed = true
57
63
Original file line number Diff line number Diff line change @@ -470,3 +470,47 @@ func Test_CancellationHandler_Remove(t *testing.T) {
470
470
471
471
require .Equal (t , 1 , f )
472
472
}
473
+
474
+ func Test_Channel_Len (t * testing.T ) {
475
+ tests := []struct {
476
+ name string
477
+ setup func (ctx Context ) Channel [int ]
478
+ expected int
479
+ }{
480
+ {
481
+ name : "EmptyChannel" ,
482
+ setup : func (ctx Context ) Channel [int ] {
483
+ return NewChannel [int ]()
484
+ },
485
+ expected : 0 ,
486
+ },
487
+ {
488
+ name : "NonEmptyBufferedChannel" ,
489
+ setup : func (ctx Context ) Channel [int ] {
490
+ c := NewBufferedChannel [int ](4 )
491
+ c .Send (ctx , 42 )
492
+ c .Send (ctx , 23 )
493
+ return c
494
+ },
495
+ expected : 2 ,
496
+ },
497
+ }
498
+
499
+ for _ , tt := range tests {
500
+ t .Run (tt .name , func (t * testing.T ) {
501
+ var actual int
502
+ ctx := Background ()
503
+
504
+ cr := NewCoroutine (ctx , func (ctx Context ) error {
505
+ c := tt .setup (ctx )
506
+ actual = c .Len ()
507
+
508
+ return nil
509
+ })
510
+
511
+ cr .Execute ()
512
+
513
+ require .Equal (t , tt .expected , actual )
514
+ })
515
+ }
516
+ }
Original file line number Diff line number Diff line change @@ -19,6 +19,9 @@ type Channel[T any] interface {
19
19
20
20
// Close closes the channel. This will cause all future send operations to panic.
21
21
Close ()
22
+
23
+ // Len returns the number of elements currently in the channel.
24
+ Len () int
22
25
}
23
26
24
27
// NewChannel creates a new channel.
You can’t perform that action at this time.
0 commit comments