Skip to content

Commit

Permalink
made intent of variables more explicit
Browse files Browse the repository at this point in the history
Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
  • Loading branch information
fredbi committed Dec 10, 2023
1 parent 168d308 commit a7fcf73
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions bytestream.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,54 +57,58 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer {

closer := defaultCloser
if vals.Close {
if cl, ok := reader.(io.Closer); ok {
if cl, isReaderCloser := reader.(io.Closer); isReaderCloser {
closer = cl.Close
}
}
defer func() {
_ = closer()
}()

if wrtr, ok := data.(io.Writer); ok {
if wrtr, isDataWriter := data.(io.Writer); isDataWriter {
// stream input to writer
_, err := io.Copy(wrtr, reader)
return err
}

// buffers input before writing to data
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(reader)
if err != nil {
return err
}
b := buf.Bytes()

switch dest := data.(type) {
switch destinationPointer := data.(type) {
case encoding.BinaryUnmarshaler:
return dest.UnmarshalBinary(b)
return destinationPointer.UnmarshalBinary(b)
case *string:
*dest = string(b)
*destinationPointer = string(b)

return nil

case *[]byte:
*dest = b
*destinationPointer = b

return nil
case *any:
switch (*dest).(type) {
switch (*destinationPointer).(type) {
case string:
*dest = string(b)
*destinationPointer = string(b)

return nil

case []byte:
*dest = b
*destinationPointer = b

return nil
}
default:
// check for the underlying type to be []byte or string
ptr := reflect.TypeOf(data)
if ptr.Kind() != reflect.Ptr {
break
// Check for the underlying type to be pointer to []byte or string,
// cases not as straightforward as the above *string and *[]byte.
// This code path allocates a reflect.Value.
if ptr := reflect.TypeOf(data); ptr.Kind() != reflect.Ptr {
return errors.New("destination must be a pointer")
}

v := reflect.Indirect(reflect.ValueOf(data))
Expand All @@ -114,6 +118,7 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer {
case t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8:
v.SetBytes(b)
return nil

case t.Kind() == reflect.String:
v.SetString(string(b))
return nil
Expand All @@ -137,17 +142,18 @@ func ByteStreamProducer(opts ...byteStreamOpt) Producer {
if writer == nil {
return errors.New("ByteStreamProducer requires a writer") // early exit
}

closer := defaultCloser
if vals.Close {
if cl, ok := writer.(io.Closer); ok {
if cl, isWriterCloser := writer.(io.Closer); isWriterCloser {
closer = cl.Close
}
}
defer func() {
_ = closer()
}()

if rc, ok := data.(io.ReadCloser); ok {
if rc, isDataCloser := data.(io.ReadCloser); isDataCloser {
defer rc.Close()
}

Expand Down

0 comments on commit a7fcf73

Please sign in to comment.