// Copyright (C) 2022 Marius Schellenberger

package fs

import (
	"io"
	"sync"
)

var Discard io.Writer = discard{}

type discard struct{}

var _ io.ReaderFrom = discard{}

func (discard) Write(p []byte) (int, error) {
	return len(p), nil
}

func (discard) WriteString(s string) (int, error) {
	return len(s), nil
}

const DefaultBufferSize = 8192

var blackHolePool = sync.Pool{
	New: func() any {
		b := make([]byte, DefaultBufferSize)
		return &b
	},
}

func SetBufferSize(size int) bool {
	if size < 0 || size == DefaultBufferSize {
		return false
	}
	blackHolePool = sync.Pool{
		New: func() any {
			b := make([]byte, size)
			return &b
		},
	}
	return true
}

func (discard) ReadFrom(r io.Reader) (n int64, err error) {
	bufp := blackHolePool.Get().(*[]byte)
	readSize := 0
	for {
		readSize, err = r.Read(*bufp)
		n += int64(readSize)
		if err != nil {
			blackHolePool.Put(bufp)
			if err == io.EOF {
				return n, nil
			}
			return
		}
	}
}
