This repository has been archived by the owner on Feb 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Achille Roussel <[email protected]>
- Loading branch information
1 parent
5fff760
commit adac0ed
Showing
2 changed files
with
95 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package stream | ||
|
||
import "io" | ||
|
||
type Optional[T any] struct { | ||
val T | ||
err error | ||
} | ||
|
||
func Opt[T any](val T, err error) Optional[T] { | ||
return Optional[T]{val: val, err: err} | ||
} | ||
|
||
func (opt *Optional[T]) Value() (T, error) { | ||
return opt.val, opt.err | ||
} | ||
|
||
func ChanReader[T any](ch <-chan Optional[T]) Reader[T] { | ||
return chanReader[T](ch) | ||
} | ||
|
||
type chanReader[T any] <-chan Optional[T] | ||
|
||
func (r chanReader[T]) Read(values []T) (int, error) { | ||
if len(values) == 0 { | ||
return 0, nil | ||
} | ||
|
||
opt, ok := <-r | ||
if !ok { | ||
return 0, io.EOF | ||
} | ||
v, err := opt.Value() | ||
if err != nil { | ||
return 0, err | ||
} | ||
values[0] = v | ||
|
||
for n := 1; n < len(values); n++ { | ||
select { | ||
case opt, ok := <-r: | ||
if !ok { | ||
return n, io.EOF | ||
} | ||
v, err := opt.Value() | ||
if err != nil { | ||
return n, err | ||
} | ||
values[n] = v | ||
default: | ||
return n, nil | ||
} | ||
} | ||
|
||
return len(values), nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters