package utils

import (
	"fmt"
	"io"
	"log/slog"
	"runtime"
)

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 c, ok := v.(io.Closer); ok {
		err := c.Close()
		if err != nil {
			var logger = slog.Default()
			_, file, line, ok := runtime.Caller(1)
			if ok {
				logger = logger.With("source", fmt.Sprintf("%s:%d", file, line))
			}
			logger.Warn("对象关闭失败", "err", err)
		}
	}
}
