Skip to content

Commit 7852759

Browse files
committed
Add Len for channel
1 parent b40e6ea commit 7852759

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

internal/sync/channel.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ type Channel[T any] interface {
1010
ReceiveNonBlocking() (v T, ok bool)
1111

1212
Close()
13+
14+
Len() int
1315
}
1416

1517
type Receiver[T any] struct {
@@ -52,6 +54,10 @@ type channel[T any] struct {
5254
size int
5355
}
5456

57+
func (c *channel[T]) Len() int {
58+
return len(c.c)
59+
}
60+
5561
func (c *channel[T]) Close() {
5662
c.closed = true
5763

internal/sync/channel_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,3 +470,47 @@ func Test_CancellationHandler_Remove(t *testing.T) {
470470

471471
require.Equal(t, 1, f)
472472
}
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+
}

workflow/channel.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ type Channel[T any] interface {
1919

2020
// Close closes the channel. This will cause all future send operations to panic.
2121
Close()
22+
23+
// Len returns the number of elements currently in the channel.
24+
Len() int
2225
}
2326

2427
// NewChannel creates a new channel.

0 commit comments

Comments
 (0)