Last active
September 2, 2020 15:45
-
-
Save risentveber/6a274ff145e6e952f9386b2038b22c30 to your computer and use it in GitHub Desktop.
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
func NewDynamicallyBufferedChannel(in <- chan interface{}) <- chan interface{} { | |
out := make(chan interface{}) | |
var storage []interface{} | |
go func() { | |
defer close(out) | |
for { | |
if len(storage) == 0 { | |
item, ok := <-in | |
if !ok { | |
return | |
} | |
storage = append(storage, item) | |
continue | |
} | |
select { | |
case item, ok := <- in: | |
if ok { | |
storage = append(storage, item) | |
} else { | |
// unwind storage | |
for _, item := range storage { | |
out <- item | |
} | |
return | |
} | |
case out <- storage[0]: | |
if len(storage) == 1 { | |
storage = nil | |
} else { | |
storage = storage[1:] | |
} | |
} | |
} | |
}() | |
return out | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment