// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ipc

import (
	
	
	
	

	
	
	
	
	
)

type compressor interface {
	MaxCompressedLen(n int) int
	Reset(io.Writer)
	io.WriteCloser
	Type() flatbuf.CompressionType
}

type lz4Compressor struct {
	*lz4.Writer
}

func (lz4Compressor) ( int) int {
	return lz4.CompressBlockBound()
}

func (lz4Compressor) () flatbuf.CompressionType {
	return flatbuf.CompressionTypeLZ4_FRAME
}

type zstdCompressor struct {
	*zstd.Encoder
	pool interface{ Put(any) }
}

// zstdEncoderPools holds reusable encoders: index 0 for the library default
// level, 1-4 for the zstd.EncoderLevel a WithZstdLevel value maps to. A new
// encoder allocates its window and match tables (about 2 MB at the default
// level), which dominates the cost of compressing a small record batch.
var zstdEncoderPools [zstd.SpeedBestCompression + 1]sync.Pool

func zstdEncoderPoolIndex( int) int {
	if  <= 0 {
		return 0
	}
	return int(zstd.EncoderLevelFromZstd())
}

// releaseCompressors returns the pooled compressors in cs and clears their
// slots, so calling it twice on the same slice is safe.
func releaseCompressors( []compressor) {
	for ,  := range  {
		,  := .(*zstdCompressor)
		if ! {
			continue
		}
		// Reset waits for in-flight block goroutines, also after a failed
		// Write, and drops the reference to the last output buffer.
		.Reset(nil)
		.pool.Put()
		[] = nil
	}
}

// from zstd.h, ZSTD_COMPRESSBOUND
func (zstdCompressor) ( int) int {
	debug.Assert( >= 0, "MaxCompressedLen called with len less than 0")
	 := uint((uint(128<<10) - uint()) >> 11)
	if  >= (128 << 10) {
		 = 0
	}
	return int(uint(+(>>8)) + )
}

func (zstdCompressor) () flatbuf.CompressionType {
	return flatbuf.CompressionTypeZSTD
}

func getCompressor( flatbuf.CompressionType,  int) compressor {
	switch  {
	case flatbuf.CompressionTypeLZ4_FRAME:
		 := lz4.NewWriter(nil)
		// options here chosen in order to match the C++ implementation
		.Apply(lz4.ChecksumOption(false), lz4.BlockSizeOption(lz4.Block64Kb))
		return &lz4Compressor{}
	case flatbuf.CompressionTypeZSTD:
		 := &zstdEncoderPools[zstdEncoderPoolIndex()]
		if ,  := .Get().(*zstdCompressor);  {
			return 
		}
		var  *zstd.Encoder
		var  error
		if  > 0 {
			,  = zstd.NewWriter(nil,
				zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd()),
			)
		} else {
			,  = zstd.NewWriter(nil)
		}
		if  != nil {
			panic()
		}
		return &zstdCompressor{Encoder: , pool: }
	}
	return nil
}

type decompressor interface {
	// Decompress decodes src into dst, which must be sized to the exact
	// uncompressed length.
	Decompress(dst, src []byte) error
	// Close releases the decompressor; it must not be used afterwards.
	// Implementations may return it to a pool, so calling Close twice hands
	// the same decompressor to two owners.
	Close()
}

var zstdDecompressorPool = sync.Pool{
	New: func() any {
		// WithDecoderConcurrency(1): Each pooled decoder is used by one goroutine at a time, so a single
		// block decoder is enough. The default would create up to four that
		// could never run in parallel;
		//
		// WithDecodeAllCapLimit(true): The cap limit bounds DecodeAll to cap(dst), so a frame claiming a
		// larger content size can't allocate beyond the buffer the caller
		// sized from the uncompressed length prefix.
		,  := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1), zstd.WithDecodeAllCapLimit(true))
		if  != nil {
			panic()
		}
		return &zstdDecompressor{Decoder: }
	},
}

type zstdDecompressor struct {
	*zstd.Decoder
}

func ( *zstdDecompressor) (,  []byte) error {
	if len() == 0 {
		return nil
	}

	// The decoder was created with WithDecodeAllCapLimit, so it decodes into
	// dst's own capacity and fails rather than allocating a larger slice.
	,  := .DecodeAll(, [:0])
	if  != nil {
		return 
	}
	// Catch cases where the prefix says fewer bytes than the content, but the content fits in the dst's spare capacity
	if len() != len() {
		return fmt.Errorf("arrow/ipc: zstd decompressed to %d bytes, expected %d", len(), len())
	}
	return nil
}

// Close returns the decoder to the pool. z.Decoder.Close() is deliberately
// not called: zstd.NewReader(nil) starts no goroutines, so a pooled decoder
// only holds GC-reclaimable state and there is nothing to tear down. Closing
// it would make the decoder unusable for the next borrower.
func ( *zstdDecompressor) () {
	zstdDecompressorPool.Put()
}

type lz4Decompressor struct {
	*lz4.Reader
	extra [1]byte // probe buffer for trailing data
}

func ( *lz4Decompressor) (,  []byte) error {
	if len() == 0 {
		return nil
	}

	.Reset(bytes.NewReader())
	if ,  := io.ReadFull(.Reader, );  != nil {
		return 
	}
	// ReadFull stops once dst is full, so probe for one more byte: if there is
	// one, the frame decompresses to more than the length prefix claims, and we
	// reject it rather than silently truncate (mirrors the zstd path).
	,  := .Read(.extra[:])
	if  > 0 {
		return fmt.Errorf("arrow/ipc: lz4 decompressed to more than the expected %d bytes", len())
	}
	if  != io.EOF {
		return 
	}
	return nil
}

func ( *lz4Decompressor) () {
	.Reset(nil)
}

func getDecompressor( flatbuf.CompressionType) decompressor {
	switch  {
	case flatbuf.CompressionTypeLZ4_FRAME:
		return &lz4Decompressor{Reader: lz4.NewReader(nil)}
	case flatbuf.CompressionTypeZSTD:
		return zstdDecompressorPool.Get().(*zstdDecompressor)
	}
	return nil
}

type bufferWriter struct {
	buf *memory.Buffer
	pos int
}

func ( *bufferWriter) ( []byte) ( int,  error) {
	if .pos+len() >= .buf.Cap() {
		.buf.Reserve(.pos + len())
	}
	 = copy(.buf.Buf()[.pos:], )
	.pos += 
	return
}