package utils

import (
	"io"
	"log/slog"
)

func ReadByte(reader io.Reader) (byte, error) {
	buffer, err := ReadBuffer(reader, 1)
	if err != nil {
		return 0, err
	}

	return buffer[0], nil
}

func ReadBuffer(reader io.Reader, size int) ([]byte, error) {
	if size == 0 {
		return []byte{}, nil
	}
	buffer := make([]byte, size)
	_, err := io.ReadFull(reader, buffer)
	if err != nil {
		return nil, err
	}

	return buffer, nil
}

// Close 关闭对象，传入值绝对不能为 nil
func Close(v any) {
	if v, ok := v.(io.Closer); ok {
		err := v.Close()
		if err != nil {
			slog.Warn("对象关闭失败", "err", err)
		}
	}
}
