// 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 compress

import (
	
	

	
	
)

type brotliCodec struct{}

func (brotliCodec) ( io.Reader) io.ReadCloser {
	return io.NopCloser(brotli.NewReader())
}

func ( brotliCodec) (,  []byte,  int) []byte {
	if  == DefaultCompressionLevel {
		 = brotli.DefaultCompression
	}

	 := int(.CompressBound(int64(len())))
	if  == nil || cap() <  {
		 = make([]byte, 0, )
	}
	 := bytes.NewBuffer([:0])
	 := brotli.NewWriterLevel(, )
	,  := .Write()
	if  != nil {
		panic()
	}
	if  := .Close();  != nil {
		panic()
	}
	return .Bytes()
}

func ( brotliCodec) (,  []byte) []byte {
	return .EncodeLevel(, , brotli.DefaultCompression)
}

func (brotliCodec) (,  []byte) []byte {
	 := brotli.NewReader(bytes.NewReader())
	if  != nil {
		var (
			       = 0
			           = -1
			   error = nil
		)
		for  != 0 &&  == nil {
			,  = .Read([:])
			 += 
		}
		if  != nil &&  != io.EOF {
			panic()
		}
		return [:]
	}

	,  := io.ReadAll()
	if  != nil {
		panic()
	}

	return 
}

// taken from brotli/enc/encode.c:1426
// BrotliEncoderMaxCompressedSize
func (brotliCodec) ( int64) int64 {
	// [window bits / empty metadata] + N * [uncompressed] + [last empty]
	debug.Assert( > 0, "brotli compressbound should be > 0")
	 :=  >> 14
	 := 2 + (4 * ) + 3 + 1
	 :=  + 
	if  == 0 {
		return 2
	}
	if  <  {
		return 0
	}
	return 
}

func (brotliCodec) ( io.Writer) io.WriteCloser {
	return brotli.NewWriter()
}

func (brotliCodec) ( io.Writer,  int) (io.WriteCloser, error) {
	if  == DefaultCompressionLevel {
		 = brotli.DefaultCompression
	}
	return brotli.NewWriterLevel(, ), nil
}

func init() {
	RegisterCodec(Codecs.Brotli, brotliCodec{})
}