converge/pkg/support/iowrappers/channelreadwritecloser.go
Erik Brakkee 3867b0432d a lot of progress in setting up tests for the communication.
Wrote ChannelReadWriter that simulates a connection inmemory.
This is used by the agentserver test for testing the initialization. The
first test is already working.
2024-08-19 22:31:02 +02:00

65 lines
1.2 KiB
Go

package iowrappers
import (
"context"
"io"
"log"
)
type ChannelReadWriter struct {
ctx context.Context
receiver <-chan []byte
// bytes that were read and that did not fit
readBuf []byte
sender chan<- []byte
closed bool
}
func NewChannelReadWriter(ctx context.Context, receiver <-chan []byte,
sender chan<- []byte) *ChannelReadWriter {
return &ChannelReadWriter{
ctx: ctx,
receiver: receiver,
sender: sender,
closed: false,
}
}
func (rw *ChannelReadWriter) Read(p []byte) (n int, err error) {
nread := copy(p, rw.readBuf)
if nread > 0 {
rw.readBuf = rw.readBuf[nread:]
return nread, nil
}
select {
case <-rw.ctx.Done():
log.Println("Context was canceled")
return 0, io.EOF
case data, ok := <-rw.receiver:
if !ok {
log.Println("Channel closed")
return 0, io.EOF
}
nread = copy(p, data)
rw.readBuf = data[nread:]
return nread, nil
}
}
func (rw *ChannelReadWriter) Write(p []byte) (n int, err error) {
select {
case <-rw.ctx.Done():
return 0, io.EOF
case rw.sender <- p:
}
return len(p), nil
}
func (rw *ChannelReadWriter) Close() error {
if !rw.closed {
close(rw.sender)
rw.closed = true
}
return nil
}