// Copyright (C) 2022 Marius Schellenberger

package fs

import (
	"io"
)

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 (
	StreamingBufferSize = 32768
	DefaultBufferSize   = 8192
)

func poolNewFunc(size int) func() *[]byte {
	return func() *[]byte {
		b := make([]byte, size)
		return &b
	}
}

var (
	streamingPool = newPool(poolNewFunc(StreamingBufferSize))
	blackHolePool = newPool(poolNewFunc(DefaultBufferSize))
)

func SetBufferSize(size int) bool {
	if size < 0 || size == DefaultBufferSize {
		return false
	}
	blackHolePool = newPool(poolNewFunc(size))
	return true
}

func (discard) ReadFrom(r io.Reader) (n int64, err error) {
	bufp := blackHolePool.Get()
	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
		}
	}
}
