package sftp

// bufPool provides a pool of byte-slices to be reused in various parts of the package.
// It is safe to use concurrently through a pointer.
type bufPool struct {
	ch   chan []byte
	blen int
}

func newBufPool(,  int) *bufPool {
	return &bufPool{
		ch:   make(chan []byte, ),
		blen: ,
	}
}

func ( *bufPool) () []byte {
	if .blen <= 0 {
		panic("bufPool: new buffer creation length must be greater than zero")
	}

	for {
		select {
		case  := <-.ch:
			if cap() < .blen {
				// just in case: throw away any buffer with insufficient capacity.
				continue
			}

			return [:.blen]

		default:
			return make([]byte, .blen)
		}
	}
}

func ( *bufPool) ( []byte) {
	if  == nil {
		// functional default: no reuse.
		return
	}

	if cap() < .blen || cap() > .blen*2 {
		// DO NOT reuse buffers with insufficient capacity.
		// This could cause panics when resizing to p.blen.

		// DO NOT reuse buffers with excessive capacity.
		// This could cause memory leaks.
		return
	}

	select {
	case .ch <- :
	default:
	}
}

type resChanPool chan chan result

func newResChanPool( int) resChanPool {
	return make(chan chan result, )
}

func ( resChanPool) () chan result {
	select {
	case  := <-:
		return 
	default:
		return make(chan result, 1)
	}
}

func ( resChanPool) ( chan result) {
	select {
	case  <- :
	default:
	}
}