package parquet

import (
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	
	
	
)

const (
	// The uncompressed page size is stored as int32 and must not be larger than the
	// maximum int32 value (see format.PageHeader).
	maxUncompressedPageSize = math.MaxInt32
)

// GenericWriter is similar to a Writer but uses a type parameter to define the
// Go type representing the schema of rows being written.
//
// Using this type over Writer has multiple advantages:
//
//   - By leveraging type information, the Go compiler can provide greater
//     guarantees that the code is correct. For example, the parquet.Writer.Write
//     method accepts an argument of type interface{}, which delays type checking
//     until runtime. The parquet.GenericWriter[T].Write method ensures at
//     compile time that the values it receives will be of type T, reducing the
//     risk of introducing errors.
//
//   - Since type information is known at compile time, the implementation of
//     parquet.GenericWriter[T] can make safe assumptions, removing the need for
//     runtime validation of how the parameters are passed to its methods.
//     Optimizations relying on type information are more effective, some of the
//     writer's state can be precomputed at initialization, which was not possible
//     with parquet.Writer.
//
//   - The parquet.GenericWriter[T].Write method uses a data-oriented design,
//     accepting an slice of T instead of a single value, creating more
//     opportunities to amortize the runtime cost of abstractions.
//     This optimization is not available for parquet.Writer because its Write
//     method's argument would be of type []interface{}, which would require
//     conversions back and forth from concrete types to empty interfaces (since
//     a []T cannot be interpreted as []interface{} in Go), would make the API
//     more difficult to use and waste compute resources in the type conversions,
//     defeating the purpose of the optimization in the first place.
//
// Note that this type is only available when compiling with Go 1.18 or later.
type GenericWriter[ any] struct {
	// At this time GenericWriter is expressed in terms of Writer to reuse the
	// underlying logic. In the future, and if we accepted to break backward
	// compatibility on the Write method, we could modify Writer to be an alias
	// to GenericWriter with:
	//
	//	type Writer = GenericWriter[any]
	//
	base Writer
	// This function writes rows of type T to the writer, it gets generated by
	// the NewGenericWriter function based on the type T and the underlying
	// schema of the parquet file.
	write writeFunc[]
	// This field is used to leverage the optimized writeRowsFunc algorithms.
	columns []ColumnBuffer
}

// NewGenericWriter is like NewWriter but returns a GenericWriter[T] suited to
// write rows of Go type T.
//
// The type parameter T should be a map, struct, or any. Any other types will
// cause a panic at runtime. Type checking is a lot more effective when the
// generic parameter is a struct type, using map and interface types is somewhat
// similar to using a Writer.
//
// If the option list may explicitly declare a schema, it must be compatible
// with the schema generated from T.
//
// Sorting columns may be set on the writer to configure the generated row
// groups metadata. However, rows are always written in the order they were
// seen, no reordering is performed, the writer expects the application to
// ensure proper correlation between the order of rows and the list of sorting
// columns. See SortingWriter[T] for a writer which handles reordering rows
// based on the configured sorting columns.
func [ any]( io.Writer,  ...WriterOption) *GenericWriter[] {
	,  := NewWriterConfig(...)
	if  != nil {
		panic()
	}

	 := .Schema
	 := typeOf[]()

	if  == nil &&  != nil {
		 = schemaOf(dereference())
		.Schema = 
	}

	if .Schema == nil {
		panic("generic writer must be instantiated with schema or concrete type.")
	}

	return &GenericWriter[]{
		base: Writer{
			output: ,
			config: ,
			schema: ,
			writer: newWriter(, ),
		},
		write: writeFuncOf[](, .Schema),
	}
}

type writeFunc[ any] func(*GenericWriter[], []) (int, error)

func writeFuncOf[ any]( reflect.Type,  *Schema) writeFunc[] {
	if  == nil {
		return (*GenericWriter[]).writeAny
	}
	switch .Kind() {
	case reflect.Interface, reflect.Map:
		return (*GenericWriter[]).writeRows

	case reflect.Struct:
		return makeWriteFunc[](, )

	case reflect.Pointer:
		if  := .Elem(); .Kind() == reflect.Struct {
			return makeWriteFunc[](, )
		}
	}
	panic("cannot create writer for values of type " + .String())
}

func makeWriteFunc[ any]( reflect.Type,  *Schema) writeFunc[] {
	 := writeRowsFuncOf(, , nil)
	return func( *GenericWriter[],  []) ( int,  error) {
		if .columns == nil {
			.columns = make([]ColumnBuffer, len(.base.writer.columns))
			for ,  := range .base.writer.columns {
				// These fields are usually lazily initialized when writing rows,
				// we need them to exist now tho.
				.columnBuffer = .newColumnBuffer()
				.columns[] = .columnBuffer
			}
		}
		 = (.columns, makeArrayOf(), columnLevels{})
		if  == nil {
			 = len()
		}
		return , 
	}
}

func ( *GenericWriter[]) () error {
	return .base.Close()
}

func ( *GenericWriter[]) () error {
	return .base.Flush()
}

func ( *GenericWriter[]) ( io.Writer) {
	.base.Reset()
}

func ( *GenericWriter[]) ( []) (int, error) {
	return .base.writer.writeRows(len(), func(,  int) (int, error) {
		,  := .write(, [::])
		if  != nil {
			return , 
		}

		for ,  := range .base.writer.columns {
			if .columnBuffer.Size() >= int64(.bufferSize) {
				if  := .flush();  != nil {
					return , 
				}
			}
		}

		return , nil
	})
}

func ( *GenericWriter[]) ( []Row) (int, error) {
	return .base.WriteRows()
}

func ( *GenericWriter[]) ( RowGroup) (int64, error) {
	return .base.WriteRowGroup()
}

// SetKeyValueMetadata sets a key/value pair in the Parquet file metadata.
//
// Keys are assumed to be unique, if the same key is repeated multiple times the
// last value is retained. While the parquet format does not require unique keys,
// this design decision was made to optimize for the most common use case where
// applications leverage this extension mechanism to associate single values to
// keys. This may create incompatibilities with other parquet libraries, or may
// cause some key/value pairs to be lost when open parquet files written with
// repeated keys. We can revisit this decision if it ever becomes a blocker.
func ( *GenericWriter[]) (,  string) {
	.base.SetKeyValueMetadata(, )
}

func ( *GenericWriter[]) ( RowReader) (int64, error) {
	return .base.ReadRowsFrom()
}

func ( *GenericWriter[]) () *Schema {
	return .base.Schema()
}

func ( *GenericWriter[]) ( []) (int, error) {
	if cap(.base.rowbuf) < len() {
		.base.rowbuf = make([]Row, len())
	} else {
		.base.rowbuf = .base.rowbuf[:len()]
	}
	defer clearRows(.base.rowbuf)

	 := .base.Schema()
	for  := range  {
		.base.rowbuf[] = .Deconstruct(.base.rowbuf[], &[])
	}

	return .base.WriteRows(.base.rowbuf)
}

func ( *GenericWriter[]) ( []) ( int,  error) {
	for  := range  {
		if  = .base.Write([]);  != nil {
			return , 
		}
		++
	}
	return , nil
}

var (
	_ RowWriterWithSchema = (*GenericWriter[any])(nil)
	_ RowReaderFrom       = (*GenericWriter[any])(nil)
	_ RowGroupWriter      = (*GenericWriter[any])(nil)

	_ RowWriterWithSchema = (*GenericWriter[struct{}])(nil)
	_ RowReaderFrom       = (*GenericWriter[struct{}])(nil)
	_ RowGroupWriter      = (*GenericWriter[struct{}])(nil)

	_ RowWriterWithSchema = (*GenericWriter[map[struct{}]struct{}])(nil)
	_ RowReaderFrom       = (*GenericWriter[map[struct{}]struct{}])(nil)
	_ RowGroupWriter      = (*GenericWriter[map[struct{}]struct{}])(nil)
)

// Deprecated: A Writer uses a parquet schema and sequence of Go values to
// produce a parquet file to an io.Writer.
//
// This example showcases a typical use of parquet writers:
//
//	writer := parquet.NewWriter(output)
//
//	for _, row := range rows {
//		if err := writer.Write(row); err != nil {
//			...
//		}
//	}
//
//	if err := writer.Close(); err != nil {
//		...
//	}
//
// The Writer type optimizes for minimal memory usage, each page is written as
// soon as it has been filled so only a single page per column needs to be held
// in memory and as a result, there are no opportunities to sort rows within an
// entire row group. Programs that need to produce parquet files with sorted
// row groups should use the Buffer type to buffer and sort the rows prior to
// writing them to a Writer.
//
// For programs building with Go 1.18 or later, the GenericWriter[T] type
// supersedes this one.
type Writer struct {
	output io.Writer
	config *WriterConfig
	schema *Schema
	writer *writer
	rowbuf []Row
}

// NewWriter constructs a parquet writer writing a file to the given io.Writer.
//
// The function panics if the writer configuration is invalid. Programs that
// cannot guarantee the validity of the options passed to NewWriter should
// construct the writer configuration independently prior to calling this
// function:
//
//	config, err := parquet.NewWriterConfig(options...)
//	if err != nil {
//		// handle the configuration error
//		...
//	} else {
//		// this call to create a writer is guaranteed not to panic
//		writer := parquet.NewWriter(output, config)
//		...
//	}
func ( io.Writer,  ...WriterOption) *Writer {
	,  := NewWriterConfig(...)
	if  != nil {
		panic()
	}
	 := &Writer{
		output: ,
		config: ,
	}
	if .Schema != nil {
		.configure(.Schema)
	}
	return 
}

func ( *Writer) ( *Schema) {
	if  != nil {
		.config.Schema = 
		.schema = 
		.writer = newWriter(.output, .config)
	}
}

// Close must be called after all values were produced to the writer in order to
// flush all buffers and write the parquet footer.
func ( *Writer) () error {
	if .writer != nil {
		return .writer.close()
	}
	return nil
}

// Flush flushes all buffers into a row group to the underlying io.Writer.
//
// Flush is called automatically on Close, it is only useful to call explicitly
// if the application needs to limit the size of row groups or wants to produce
// multiple row groups per file.
//
// If the writer attempts to create more than MaxRowGroups row groups the method
// returns ErrTooManyRowGroups.
func ( *Writer) () error {
	if .writer != nil {
		return .writer.flush()
	}
	return nil
}

// Reset clears the state of the writer without flushing any of the buffers,
// and setting the output to the io.Writer passed as argument, allowing the
// writer to be reused to produce another parquet file.
//
// Reset may be called at any time, including after a writer was closed.
func ( *Writer) ( io.Writer) {
	if .output = ; .writer != nil {
		.writer.reset(.output)
	}
}

// Write is called to write another row to the parquet file.
//
// The method uses the parquet schema configured on w to traverse the Go value
// and decompose it into a set of columns and values. If no schema were passed
// to NewWriter, it is deducted from the Go type of the row, which then have to
// be a struct or pointer to struct.
func ( *Writer) ( interface{}) error {
	if .schema == nil {
		.configure(SchemaOf())
	}
	if cap(.rowbuf) == 0 {
		.rowbuf = make([]Row, 1)
	} else {
		.rowbuf = .rowbuf[:1]
	}
	defer clearRows(.rowbuf)
	.rowbuf[0] = .schema.Deconstruct(.rowbuf[0][:0], )
	,  := .WriteRows(.rowbuf)
	return 
}

// WriteRows is called to write rows to the parquet file.
//
// The Writer must have been given a schema when NewWriter was called, otherwise
// the structure of the parquet file cannot be determined from the row only.
//
// The row is expected to contain values for each column of the writer's schema,
// in the order produced by the parquet.(*Schema).Deconstruct method.
func ( *Writer) ( []Row) (int, error) {
	return .writer.WriteRows()
}

// WriteRowGroup writes a row group to the parquet file.
//
// Buffered rows will be flushed prior to writing rows from the group, unless
// the row group was empty in which case nothing is written to the file.
//
// The content of the row group is flushed to the writer; after the method
// returns successfully, the row group will be empty and in ready to be reused.
func ( *Writer) ( RowGroup) (int64, error) {
	 := .Schema()
	switch {
	case  == nil:
		return 0, ErrRowGroupSchemaMissing
	case .schema == nil:
		.configure()
	case !nodesAreEqual(.schema, ):
		return 0, ErrRowGroupSchemaMismatch
	}
	if  := .writer.flush();  != nil {
		return 0, 
	}
	.writer.configureBloomFilters(.ColumnChunks())
	 := .Rows()
	defer .Close()
	,  := CopyRows(.writer, )
	if  != nil {
		return , 
	}
	return .writer.writeRowGroup(.Schema(), .SortingColumns())
}

// ReadRowsFrom reads rows from the reader passed as arguments and writes them
// to w.
//
// This is similar to calling WriteRow repeatedly, but will be more efficient
// if optimizations are supported by the reader.
func ( *Writer) ( RowReader) ( int64,  error) {
	if .schema == nil {
		if ,  := .(RowReaderWithSchema);  {
			.configure(.Schema())
		}
	}
	if cap(.rowbuf) < defaultRowBufferSize {
		.rowbuf = make([]Row, defaultRowBufferSize)
	} else {
		.rowbuf = .rowbuf[:cap(.rowbuf)]
	}
	return copyRows(.writer, , .rowbuf)
}

// Schema returns the schema of rows written by w.
//
// The returned value will be nil if no schema has yet been configured on w.
func ( *Writer) () *Schema { return .schema }

// SetKeyValueMetadata sets a key/value pair in the Parquet file metadata.
//
// Keys are assumed to be unique, if the same key is repeated multiple times the
// last value is retained. While the parquet format does not require unique keys,
// this design decision was made to optimize for the most common use case where
// applications leverage this extension mechanism to associate single values to
// keys. This may create incompatibilities with other parquet libraries, or may
// cause some key/value pairs to be lost when open parquet files written with
// repeated keys. We can revisit this decision if it ever becomes a blocker.
func ( *Writer) (,  string) {
	for ,  := range .writer.metadata {
		if .Key ==  {
			.Value = 
			.writer.metadata[] = 
			return
		}
	}
	.writer.metadata = append(.writer.metadata, format.KeyValue{
		Key:   ,
		Value: ,
	})
}

type writer struct {
	buffer  *bufio.Writer
	writer  offsetTrackingWriter
	values  [][]Value
	numRows int64
	maxRows int64

	createdBy string
	metadata  []format.KeyValue

	columns     []*writerColumn
	columnChunk []format.ColumnChunk
	columnIndex []format.ColumnIndex
	offsetIndex []format.OffsetIndex

	columnOrders   []format.ColumnOrder
	schemaElements []format.SchemaElement
	rowGroups      []format.RowGroup
	columnIndexes  [][]format.ColumnIndex
	offsetIndexes  [][]format.OffsetIndex
	sortingColumns []format.SortingColumn
}

func newWriter( io.Writer,  *WriterConfig) *writer {
	 := new(writer)
	if .WriteBufferSize <= 0 {
		.writer.Reset()
	} else {
		.buffer = bufio.NewWriterSize(, .WriteBufferSize)
		.writer.Reset(.buffer)
	}
	.maxRows = .MaxRowsPerRowGroup
	.createdBy = .CreatedBy
	.metadata = make([]format.KeyValue, 0, len(.KeyValueMetadata))
	for ,  := range .KeyValueMetadata {
		.metadata = append(.metadata, format.KeyValue{Key: , Value: })
	}
	sortKeyValueMetadata(.metadata)
	.sortingColumns = make([]format.SortingColumn, len(.Sorting.SortingColumns))

	.Schema.forEachNode(func( string,  Node) {
		 := .Type()

		 := (*format.FieldRepetitionType)(nil)
		if  != .Schema { // the root has no repetition type
			 = fieldRepetitionTypePtrOf()
		}
		// For backward compatibility with older readers, the parquet specification
		// recommends to set the scale and precision on schema elements when the
		// column is of logical type decimal.
		 := .LogicalType()
		,  := (*int32)(nil), (*int32)(nil)
		if  != nil && .Decimal != nil {
			 = &.Decimal.Scale
			 = &.Decimal.Precision
		}

		 := (*int32)(nil)
		if  := int32(.Length());  > 0 {
			 = &
		}

		.schemaElements = append(.schemaElements, format.SchemaElement{
			Type:           .PhysicalType(),
			TypeLength:     ,
			RepetitionType: ,
			Name:           ,
			NumChildren:    int32(len(.Fields())),
			ConvertedType:  .ConvertedType(),
			Scale:          ,
			Precision:      ,
			FieldID:        int32(.ID()),
			LogicalType:    ,
		})
	})

	 := format.DataPage
	if .DataPageVersion == 2 {
		 = format.DataPageV2
	}

	 := .Compression
	if  == nil {
		 = &Uncompressed
	}

	// Those buffers are scratch space used to generate the page header and
	// content, they are shared by all column chunks because they are only
	// used during calls to writeDictionaryPage or writeDataPage, which are
	// not done concurrently.
	 := new(writerBuffers)

	forEachLeafColumnOf(.Schema, func( leafColumn) {
		 := encodingOf(.node)
		 := Dictionary(nil)
		 := .node.Type()
		 := int(.columnIndex)
		 := .node.Compression()

		if  == nil {
			 = 
		}

		if isDictionaryEncoding() {
			 := .NewValues(
				make([]byte, 0, defaultDictBufferSize),
				nil,
			)
			 = .NewDictionary(, 0, )
			 = .Type()
		}

		 := &writerColumn{
			buffers:            ,
			pool:               .ColumnPageBuffers,
			columnPath:         .path,
			columnType:         ,
			columnIndex:        .NewColumnIndexer(.ColumnIndexSizeLimit),
			columnFilter:       searchBloomFilterColumn(.BloomFilters, .path),
			compression:        ,
			dictionary:         ,
			dataPageType:       ,
			maxRepetitionLevel: .maxRepetitionLevel,
			maxDefinitionLevel: .maxDefinitionLevel,
			bufferIndex:        int32(.columnIndex),
			bufferSize:         int32(float64(.PageBufferSize) * 0.98),
			writePageStats:     .DataPageStatistics,
			writePageBounds: !slices.ContainsFunc(.SkipPageBounds, func( []string) bool {
				return columnPath().equal(.path)
			}),
			encodings: make([]format.Encoding, 0, 3),
			// Data pages in version 2 can omit compression when dictionary
			// encoding is employed; only the dictionary page needs to be
			// compressed, the data pages are encoded with the hybrid
			// RLE/Bit-Pack encoding which doesn't benefit from an extra
			// compression layer.
			isCompressed: isCompressed() && ( != format.DataPageV2 ||  == nil),
		}

		.header.encoder.Reset(.header.protocol.NewWriter(&.header))

		if .maxDefinitionLevel > 0 {
			.encodings = addEncoding(.encodings, format.RLE)
		}

		if isDictionaryEncoding() {
			.encodings = addEncoding(.encodings, format.Plain)
		}

		.encoding = 
		.encodings = addEncoding(.encodings, .encoding.Encoding())
		sortPageEncodings(.encodings)

		.columns = append(.columns, )

		if  := searchSortingColumn(.Sorting.SortingColumns, .path);  < len(.sortingColumns) {
			.sortingColumns[] = format.SortingColumn{
				ColumnIdx:  int32(.columnIndex),
				Descending: .Sorting.SortingColumns[].Descending(),
				NullsFirst: .Sorting.SortingColumns[].NullsFirst(),
			}
		}
	})

	// Pre-allocate the backing array so that in most cases where the rows
	// contain a single value we will hit collocated memory areas when writing
	// rows to the writer. This won't benefit repeated columns much but in that
	// case we would just waste a bit of memory which we can afford.
	 := make([]Value, len(.columns))
	.values = make([][]Value, len(.columns))
	for  := range  {
		.values[] = [ :  : +1]
	}

	.columnChunk = make([]format.ColumnChunk, len(.columns))
	.columnIndex = make([]format.ColumnIndex, len(.columns))
	.offsetIndex = make([]format.OffsetIndex, len(.columns))
	.columnOrders = make([]format.ColumnOrder, len(.columns))

	for ,  := range .columns {
		.columnChunk[] = format.ColumnChunk{
			MetaData: format.ColumnMetaData{
				Type:             format.Type(.columnType.Kind()),
				Encoding:         .encodings,
				PathInSchema:     .columnPath,
				Codec:            .compression.CompressionCodec(),
				KeyValueMetadata: nil, // TODO
			},
		}
	}

	for ,  := range .columns {
		.columnChunk = &.columnChunk[]
		.offsetIndex = &.offsetIndex[]
	}

	for ,  := range .columns {
		.columnOrders[] = *.columnType.ColumnOrder()
	}

	return 
}

func ( *writer) ( io.Writer) {
	if .buffer == nil {
		.writer.Reset()
	} else {
		.buffer.Reset()
		.writer.Reset(.buffer)
	}
	for ,  := range .columns {
		.reset()
	}
	for  := range .rowGroups {
		.rowGroups[] = format.RowGroup{}
	}
	for  := range .columnIndexes {
		.columnIndexes[] = nil
	}
	for  := range .offsetIndexes {
		.offsetIndexes[] = nil
	}
	.rowGroups = .rowGroups[:0]
	.columnIndexes = .columnIndexes[:0]
	.offsetIndexes = .offsetIndexes[:0]
}

func ( *writer) () error {
	if  := .writeFileHeader();  != nil {
		return 
	}
	if  := .flush();  != nil {
		return 
	}
	if  := .writeFileFooter();  != nil {
		return 
	}
	if .buffer != nil {
		return .buffer.Flush()
	}
	return nil
}

func ( *writer) () error {
	,  := .writeRowGroup(nil, nil)
	return 
}

func ( *writer) () error {
	if .writer.writer == nil {
		return io.ErrClosedPipe
	}
	if .writer.offset == 0 {
		,  := .writer.WriteString("PAR1")
		return 
	}
	return nil
}

func ( *writer) ( []ColumnChunk) {
	for ,  := range .columns {
		if .columnFilter != nil {
			.resizeBloomFilter([].NumValues())
		}
	}
}

func ( *writer) () error {
	// The page index is composed of two sections: column and offset indexes.
	// They are written after the row groups, right before the footer (which
	// is written by the parent Writer.Close call).
	//
	// This section both writes the page index and generates the values of
	// ColumnIndexOffset, ColumnIndexLength, OffsetIndexOffset, and
	// OffsetIndexLength in the corresponding columns of the file metadata.
	//
	// Note: the page index is always written, even if we created data pages v1
	// because the parquet format is backward compatible in this case. Older
	// readers will simply ignore this section since they do not know how to
	// decode its content, nor have loaded any metadata to reference it.
	 := new(thrift.CompactProtocol)
	 := thrift.NewEncoder(.NewWriter(&.writer))

	for ,  := range .columnIndexes {
		 := &.rowGroups[]
		for  := range  {
			 := &.Columns[]
			.ColumnIndexOffset = .writer.offset
			if  := .Encode(&[]);  != nil {
				return 
			}
			.ColumnIndexLength = int32(.writer.offset - .ColumnIndexOffset)
		}
	}

	for ,  := range .offsetIndexes {
		 := &.rowGroups[]
		for  := range  {
			 := &.Columns[]
			.OffsetIndexOffset = .writer.offset
			if  := .Encode(&[]);  != nil {
				return 
			}
			.OffsetIndexLength = int32(.writer.offset - .OffsetIndexOffset)
		}
	}

	 := int64(0)
	for  := range .rowGroups {
		 += .rowGroups[].NumRows
	}

	// We implemented the parquet specification version 2+, which is represented
	// by the version number 2 in the file metadata.
	//
	// For reference, see:
	// https://github.com/apache/arrow/blob/70b9ef5/go/parquet/metadata/file.go#L122-L127
	const  = 2

	,  := thrift.Marshal(new(thrift.CompactProtocol), &format.FileMetaData{
		Version:          ,
		Schema:           .schemaElements,
		NumRows:          ,
		RowGroups:        .rowGroups,
		KeyValueMetadata: .metadata,
		CreatedBy:        .createdBy,
		ColumnOrders:     .columnOrders,
	})
	if  != nil {
		return 
	}

	 := len()
	 = append(, 0, 0, 0, 0)
	 = append(, "PAR1"...)
	binary.LittleEndian.PutUint32([:], uint32())

	_,  = .writer.Write()
	return 
}

func ( *writer) ( *Schema,  []SortingColumn) (int64, error) {
	 := .columns[0].totalRowCount()
	if  == 0 {
		return 0, nil
	}

	if len(.rowGroups) == MaxRowGroups {
		return 0, ErrTooManyRowGroups
	}

	defer func() {
		.numRows = 0
		for ,  := range .columns {
			.reset()
		}
		for  := range .columnIndex {
			.columnIndex[] = format.ColumnIndex{}
		}
	}()

	for ,  := range .columns {
		if  := .flush();  != nil {
			return 0, 
		}
		if  := .flushFilterPages();  != nil {
			return 0, 
		}
	}

	if  := .writeFileHeader();  != nil {
		return 0, 
	}
	 := .writer.offset

	for ,  := range .columns {
		if len(.filter) > 0 {
			.columnChunk.MetaData.BloomFilterOffset = .writer.offset
			if  := .writeBloomFilter(&.writer);  != nil {
				return 0, 
			}
		}
	}

	for ,  := range .columns {
		.columnIndex[] = format.ColumnIndex(.columnIndex.ColumnIndex())

		if .dictionary != nil {
			.columnChunk.MetaData.DictionaryPageOffset = .writer.offset
			if  := .writeDictionaryPage(&.writer, .dictionary);  != nil {
				return 0, fmt.Errorf("writing dictionary page of row group colum %d: %w", , )
			}
		}

		 := .writer.offset
		.columnChunk.MetaData.DataPageOffset = 
		for  := range .offsetIndex.PageLocations {
			.offsetIndex.PageLocations[].Offset += 
		}

		if ,  := .pageBuffer.Seek(0, io.SeekStart);  != nil {
			return 0, 
		} else if  != 0 {
			return 0, fmt.Errorf("resetting parquet page buffer to the start expected offset zero but got %d", )
		}
		if ,  := io.Copy(&.writer, .pageBuffer);  != nil {
			return 0, fmt.Errorf("writing buffered pages of row group column %d: %w", , )
		}
	}

	 := int64(0)
	 := int64(0)

	for  := range .columnChunk {
		 := &.columnChunk[].MetaData
		sortPageEncodingStats(.EncodingStats)
		 += int64(.TotalUncompressedSize)
		 += int64(.TotalCompressedSize)
	}

	 := .sortingColumns
	if len() == 0 && len() > 0 {
		 = make([]format.SortingColumn, 0, len())
		forEachLeafColumnOf(, func( leafColumn) {
			if  := searchSortingColumn(, .path);  < len() {
				[] = format.SortingColumn{
					ColumnIdx:  int32(.columnIndex),
					Descending: [].Descending(),
					NullsFirst: [].NullsFirst(),
				}
			}
		})
	}

	 := make([]format.ColumnChunk, len(.columnChunk))
	copy(, .columnChunk)

	 := make([]format.ColumnIndex, len(.columnIndex))
	copy(, .columnIndex)

	 := make([]format.OffsetIndex, len(.offsetIndex))
	copy(, .offsetIndex)

	for  := range  {
		 := &[]
		.MetaData.EncodingStats = make([]format.PageEncodingStats, len(.MetaData.EncodingStats))
		copy(.MetaData.EncodingStats, .columnChunk[].MetaData.EncodingStats)
	}

	for  := range  {
		 := &[]
		.PageLocations = make([]format.PageLocation, len(.PageLocations))
		copy(.PageLocations, .offsetIndex[].PageLocations)
	}

	.rowGroups = append(.rowGroups, format.RowGroup{
		Columns:             ,
		TotalByteSize:       ,
		NumRows:             ,
		SortingColumns:      ,
		FileOffset:          ,
		TotalCompressedSize: ,
		Ordinal:             int16(len(.rowGroups)),
	})

	.columnIndexes = append(.columnIndexes, )
	.offsetIndexes = append(.offsetIndexes, )
	return , nil
}

func ( *writer) ( []Row) (int, error) {
	return .writeRows(len(), func(,  int) (int, error) {
		defer func() {
			for ,  := range .values {
				clearValues()
				.values[] = [:0]
			}
		}()

		// TODO: if an error occurs in this method the writer may be left in an
		// partially functional state. Applications are not expected to continue
		// using the writer after getting an error, but maybe we could ensure that
		// we are preventing further use as well?
		for ,  := range [:] {
			.Range(func( int,  []Value) bool {
				.values[] = append(.values[], ...)
				return true
			})
		}

		for ,  := range .values {
			if len() > 0 {
				if  := .columns[].writeRows();  != nil {
					return 0, 
				}
			}
		}

		return  - , nil
	})
}

func ( *writer) ( int,  func(,  int) (int, error)) (int, error) {
	 := 0

	for  <  {
		 := .maxRows - .numRows
		 :=  - 

		if  == 0 {
			 = .maxRows

			if  := .flush();  != nil {
				return , 
			}
		}

		if  < int64() {
			 = int()
		}

		// Since the writer cannot flush pages across row boundaries, calls to
		// WriteRows with very large slices can result in greatly exceeding the
		// target page size. To set a limit to the impact of these large writes
		// we chunk the input in slices of 64 rows.
		//
		// Note that this mechanism isn't perfect; for example, values may hold
		// large byte slices which could still cause the column buffers to grow
		// beyond the target page size.
		const  = 64
		if  >  {
			 = 
		}

		,  := (, +)
		 += 
		.numRows += int64()
		if  != nil {
			return , 
		}
	}

	return , nil
}

// The WriteValues method is intended to work in pair with WritePage to allow
// programs to target writing values to specific columns of of the writer.
func ( *writer) ( []Value) ( int,  error) {
	return .columns[[0].Column()].WriteValues()
}

// One writerBuffers is used by each writer instance, the memory buffers here
// are shared by all columns of the writer because serialization is not done
// concurrently, which helps keep memory utilization low, both in the total
// footprint and GC cost.
//
// The type also exposes helper methods to facilitate the generation of parquet
// pages. A scratch space is used when serialization requires combining multiple
// buffers or compressing the page data, with double-buffering technique being
// employed by swapping the scratch and page buffers to minimize memory copies.
type writerBuffers struct {
	header      bytes.Buffer // buffer where page headers are encoded
	repetitions []byte       // buffer used to encode repetition levels
	definitions []byte       // buffer used to encode definition levels
	page        []byte       // page buffer holding the page data
	scratch     []byte       // scratch space used for compression
}

func ( *writerBuffers) () ( uint32) {
	 = crc32.Update(, crc32.IEEETable, .repetitions)
	 = crc32.Update(, crc32.IEEETable, .definitions)
	 = crc32.Update(, crc32.IEEETable, .page)
	return 
}

func ( *writerBuffers) () int {
	return len(.repetitions) + len(.definitions) + len(.page)
}

func ( *writerBuffers) () {
	.repetitions = .repetitions[:0]
	.definitions = .definitions[:0]
	.page = .page[:0]
}

func encodeLevels(,  []byte,  byte) ([]byte, error) {
	 := bits.Len8()
	return levelEncodingsRLE[-1].EncodeLevels(, )
}

func ( *writerBuffers) ( Page,  byte) ( error) {
	.repetitions,  = encodeLevels(.repetitions, .RepetitionLevels(), )
	return
}

func ( *writerBuffers) ( Page,  byte) ( error) {
	.definitions,  = encodeLevels(.definitions, .DefinitionLevels(), )
	return
}

func ( *writerBuffers) (,  byte) {
	 :=  > 0
	 :=  > 0

	if  ||  {
		.scratch = .scratch[:0]
		// In data pages v1, the repetition and definition levels are prefixed
		// with the 4 bytes length of the sections. While the parquet-format
		// documentation indicates that the length prefix is part of the hybrid
		// RLE/Bit-Pack encoding, this is the only condition where it is used
		// so we treat it as a special case rather than implementing it in the
		// encoding.
		//
		// Reference https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3
		if  {
			.scratch = plain.AppendInt32(.scratch, int32(len(.repetitions)))
			.scratch = append(.scratch, .repetitions...)
			.repetitions = .repetitions[:0]
		}
		if  {
			.scratch = plain.AppendInt32(.scratch, int32(len(.definitions)))
			.scratch = append(.scratch, .definitions...)
			.definitions = .definitions[:0]
		}
		.scratch = append(.scratch, .page...)
		.swapPageAndScratchBuffers()
	}
}

func ( *writerBuffers) ( Page,  encoding.Encoding) ( error) {
	 := .Type()
	 := .Data()
	.page,  = .Encode(.page[:0], , )
	return 
}

func ( *writerBuffers) ( compress.Codec) ( error) {
	.scratch,  = .Encode(.scratch[:0], .page)
	.swapPageAndScratchBuffers()
	return 
}

func ( *writerBuffers) () {
	.page, .scratch = .scratch, .page[:0]
}

type writerColumn struct {
	pool       BufferPool
	pageBuffer io.ReadWriteSeeker
	numPages   int

	columnPath   columnPath
	columnType   Type
	columnIndex  ColumnIndexer
	columnBuffer ColumnBuffer
	columnFilter BloomFilterColumn
	encoding     encoding.Encoding
	compression  compress.Codec
	dictionary   Dictionary

	dataPageType       format.PageType
	maxRepetitionLevel byte
	maxDefinitionLevel byte

	buffers *writerBuffers

	header struct {
		protocol thrift.CompactProtocol
		encoder  thrift.Encoder
	}

	filter          []byte
	numRows         int64
	bufferIndex     int32
	bufferSize      int32
	writePageStats  bool
	writePageBounds bool
	isCompressed    bool
	encodings       []format.Encoding

	columnChunk *format.ColumnChunk
	offsetIndex *format.OffsetIndex
}

func ( *writerColumn) () {
	if .columnBuffer != nil {
		.columnBuffer.Reset()
	}
	if .columnIndex != nil {
		.columnIndex.Reset()
	}
	if .dictionary != nil {
		.dictionary.Reset()
	}
	if .pageBuffer != nil {
		.pool.PutBuffer(.pageBuffer)
		.pageBuffer = nil
	}
	.numPages = 0
	// Bloom filters may change in size between row groups, but we retain the
	// buffer to avoid reallocating large memory blocks.
	.filter = .filter[:0]
	.numRows = 0
	// Reset the fields of column chunks that change between row groups,
	// but keep the ones that remain unchanged.
	.columnChunk.MetaData.NumValues = 0
	.columnChunk.MetaData.TotalUncompressedSize = 0
	.columnChunk.MetaData.TotalCompressedSize = 0
	.columnChunk.MetaData.DataPageOffset = 0
	.columnChunk.MetaData.DictionaryPageOffset = 0
	.columnChunk.MetaData.Statistics = format.Statistics{}
	.columnChunk.MetaData.EncodingStats = .columnChunk.MetaData.EncodingStats[:0]
	.columnChunk.MetaData.BloomFilterOffset = 0
	.offsetIndex.PageLocations = .offsetIndex.PageLocations[:0]
}

func ( *writerColumn) () int64 {
	 := .numRows
	if .columnBuffer != nil {
		 += int64(.columnBuffer.Len())
	}
	return 
}

func ( *writerColumn) () ( error) {
	if .columnBuffer.Len() > 0 {
		defer .columnBuffer.Reset()
		_,  = .writeDataPage(.columnBuffer.Page())
	}
	return 
}

func ( *writerColumn) () ( error) {
	if .columnFilter == nil {
		return nil
	}

	// If there is a dictionary, it contains all the values that we need to
	// write to the filter.
	if  := .dictionary;  != nil {
		// Need to always attempt to resize the filter, as the writer might
		// be reused after resetting which would have reset the length of
		// the filter to 0.
		.resizeBloomFilter(int64(.Len()))
		return .writePageToFilter(.Page())
	}

	// When the filter was already allocated, pages have been written to it as
	// they were seen by the column writer.
	if len(.filter) > 0 {
		return nil
	}

	// When the filter was not allocated, the writer did not know how many
	// values were going to be seen and therefore could not properly size the
	// filter ahead of time. In this case, we read back all the pages that we
	// have encoded and copy their values back to the filter.
	//
	// A prior implementation of the column writer used to create in-memory
	// copies of the pages to avoid this decoding step; however, this unbounded
	// allocation caused memory exhaustion in production applications. CPU being
	// a somewhat more stretchable resource, we prefer spending time on this
	// decoding step than having to trigger incident response when production
	// systems are getting OOM-Killed.
	.resizeBloomFilter(.columnChunk.MetaData.NumValues)

	 := &Column{
		// Set all the fields required by the decodeDataPage* methods.
		typ:                .columnType,
		encoding:           .encoding,
		compression:        .compression,
		maxRepetitionLevel: .maxRepetitionLevel,
		maxDefinitionLevel: .maxDefinitionLevel,
		index:              int16(.bufferIndex),
	}

	var  io.Reader = .pageBuffer
	if ,  := .pageBuffer.Seek(0, io.SeekStart);  != nil {
		return 
	} else if  != 0 {
		return fmt.Errorf("resetting parquet page buffer to the start expected offset zero but got %d", )
	}

	if ,  := .(*os.File);  {
		,  := getBufioReader(, 1024)
		defer func() {
			putBufioReader(, )
		}()
		 = 
	}

	 := (*buffer)(nil)
	defer func() {
		if  != nil {
			.unref()
		}
	}()

	 := thrift.NewDecoder(.header.protocol.NewReader())

	for  := 0;  < .numPages; ++ {
		 := new(format.PageHeader)
		if  := .Decode();  != nil {
			return 
		}

		if  != nil {
			.unref()
		}
		 = buffers.get(int(.CompressedPageSize))
		if ,  := io.ReadFull(, .data);  != nil {
			return 
		}

		var  Page

		switch .Type {
		case format.DataPage:
			,  = .decodeDataPageV1(DataPageHeaderV1{.DataPageHeader}, , nil, .UncompressedPageSize)
		case format.DataPageV2:
			,  = .decodeDataPageV2(DataPageHeaderV2{.DataPageHeaderV2}, , nil, .UncompressedPageSize)
		}
		if  != nil {
			 = .writePageToFilter()
			Release()
		}
		if  != nil {
			return 
		}
	}

	return nil
}

func ( *writerColumn) ( int64) {
	 := .columnFilter.Size()
	if cap(.filter) <  {
		.filter = make([]byte, )
	} else {
		.filter = .filter[:]
		for  := range .filter {
			.filter[] = 0
		}
	}
}

func ( *writerColumn) () ColumnBuffer {
	 := .columnType.NewColumnBuffer(int(.bufferIndex), .columnType.EstimateNumValues(int(.bufferSize)))
	switch {
	case .maxRepetitionLevel > 0:
		 = newRepeatedColumnBuffer(, .maxRepetitionLevel, .maxDefinitionLevel, nullsGoLast)
	case .maxDefinitionLevel > 0:
		 = newOptionalColumnBuffer(, .maxDefinitionLevel, nullsGoLast)
	}
	return 
}

func ( *writerColumn) ( []Value) error {
	if .columnBuffer == nil {
		// Lazily create the row group column so we don't need to allocate it if
		// rows are not written individually to the column.
		.columnBuffer = .newColumnBuffer()
	}
	if ,  := .columnBuffer.WriteValues();  != nil {
		return 
	}
	if .columnBuffer.Size() >= int64(.bufferSize) {
		return .flush()
	}
	return nil
}

func ( *writerColumn) ( []Value) ( int,  error) {
	if .columnBuffer == nil {
		.columnBuffer = .newColumnBuffer()
	}
	return .columnBuffer.WriteValues()
}

func ( *writerColumn) ( io.Writer) error {
	 := thrift.NewEncoder(.header.protocol.NewWriter())
	 := bloomFilterHeader(.columnFilter)
	.NumBytes = int32(len(.filter))
	if  := .Encode(&);  != nil {
		return 
	}
	,  := .Write(.filter)
	return 
}

func ( *writerColumn) ( Page) (int64, error) {
	 := .NumValues()
	if  == 0 {
		return 0, nil
	}

	 := .buffers
	.reset()

	if .maxRepetitionLevel > 0 {
		.encodeRepetitionLevels(, .maxRepetitionLevel)
	}
	if .maxDefinitionLevel > 0 {
		.encodeDefinitionLevels(, .maxDefinitionLevel)
	}

	if  := .encode(, .encoding);  != nil {
		return 0, fmt.Errorf("encoding parquet data page: %w", )
	}
	if .dataPageType == format.DataPage {
		.prependLevelsToDataPageV1(.maxDefinitionLevel, .maxDefinitionLevel)
	}

	 := .size()
	if  > maxUncompressedPageSize {
		return 0, fmt.Errorf("page size limit exceeded: %d>%d", , maxUncompressedPageSize)
	}
	if .isCompressed {
		if  := .compress(.compression);  != nil {
			return 0, fmt.Errorf("compressing parquet data page: %w", )
		}
	}

	if .Dictionary() == nil && len(.filter) > 0 {
		// When the writer knows the number of values in advance (e.g. when
		// writing a full row group), the filter encoding is set and the page
		// can be directly applied to the filter, which minimizes memory usage
		// since there is no need to buffer the values in order to determine
		// the size of the filter.
		if  := .writePageToFilter();  != nil {
			return 0, 
		}
	}

	 := format.Statistics{}
	if .writePageStats {
		 = .makePageStatistics()
	}

	 := &format.PageHeader{
		Type:                 .dataPageType,
		UncompressedPageSize: int32(),
		CompressedPageSize:   int32(.size()),
		CRC:                  int32(.crc32()),
	}

	 := .NumRows()
	 := .NumNulls()
	switch .dataPageType {
	case format.DataPage:
		.DataPageHeader = &format.DataPageHeader{
			NumValues:               int32(),
			Encoding:                .encoding.Encoding(),
			DefinitionLevelEncoding: format.RLE,
			RepetitionLevelEncoding: format.RLE,
			Statistics:              ,
		}
	case format.DataPageV2:
		.DataPageHeaderV2 = &format.DataPageHeaderV2{
			NumValues:                  int32(),
			NumNulls:                   int32(),
			NumRows:                    int32(),
			Encoding:                   .encoding.Encoding(),
			DefinitionLevelsByteLength: int32(len(.definitions)),
			RepetitionLevelsByteLength: int32(len(.repetitions)),
			IsCompressed:               &.isCompressed,
			Statistics:                 ,
		}
	}

	.header.Reset()
	if  := .header.encoder.Encode();  != nil {
		return 0, 
	}

	 := int64(.header.Len()) +
		int64(len(.repetitions)) +
		int64(len(.definitions)) +
		int64(len(.page))

	 := .writePageTo(, func( io.Writer) ( int64,  error) {
		for ,  := range [...][]byte{
			.header.Bytes(),
			.repetitions,
			.definitions,
			.page,
		} {
			,  := .Write()
			 += int64()
			if  != nil {
				return , 
			}
		}
		return , nil
	})
	if  != nil {
		return 0, 
	}

	.recordPageStats(int32(.header.Len()), , )
	return , nil
}

func ( *writerColumn) ( io.Writer,  Dictionary) ( error) {
	 := .buffers
	.reset()

	if  := .encode(.Page(), &Plain);  != nil {
		return fmt.Errorf("writing parquet dictionary page: %w", )
	}

	 := .size()
	if  > maxUncompressedPageSize {
		return fmt.Errorf("page size limit exceeded: %d>%d", , maxUncompressedPageSize)
	}
	if isCompressed(.compression) {
		if  := .compress(.compression);  != nil {
			return fmt.Errorf("copmressing parquet dictionary page: %w", )
		}
	}

	 := &format.PageHeader{
		Type:                 format.DictionaryPage,
		UncompressedPageSize: int32(),
		CompressedPageSize:   int32(.size()),
		CRC:                  int32(.crc32()),
		DictionaryPageHeader: &format.DictionaryPageHeader{
			NumValues: int32(.Len()),
			Encoding:  format.Plain,
			IsSorted:  false,
		},
	}

	 := &.buffers.header
	.Reset()
	if  := .header.encoder.Encode();  != nil {
		return 
	}
	if ,  := .Write(.Bytes());  != nil {
		return 
	}
	if ,  := .Write(.page);  != nil {
		return 
	}
	.recordPageStats(int32(.Len()), , nil)
	return nil
}

func ( *writerColumn) ( Page) ( error) {
	 := .Type()
	 := .Data()
	.filter,  = .Encode(.filter, , .columnFilter.Encoding())
	return 
}

func ( *writerColumn) ( int64,  func(io.Writer) (int64, error)) ( error) {
	if .pageBuffer == nil {
		.pageBuffer = .pool.GetBuffer()
		defer func() {
			if  != nil {
				.pool.PutBuffer(.pageBuffer)
				.pageBuffer = nil
			}
		}()
		if _,  = .pageBuffer.Seek(0, io.SeekStart);  != nil {
			return 
		}
	}
	,  := (.pageBuffer)
	if  != nil {
		return 
	}
	if  !=  {
		return fmt.Errorf("writing parquet column page expected %dB but got %dB: %w", , , io.ErrShortWrite)
	}
	.numPages++
	return nil
}

func ( *writerColumn) ( Page) format.Statistics {
	 := .NumNulls()
	, ,  := .Bounds()
	 := .Bytes()
	 := .Bytes()
	return format.Statistics{
		Min:       , // deprecated
		Max:       , // deprecated
		NullCount: ,
		MinValue:  ,
		MaxValue:  ,
	}
}

func ( *writerColumn) ( int32,  *format.PageHeader,  Page) {
	 :=  + .UncompressedPageSize
	 :=  + .CompressedPageSize

	if  != nil {
		 := .NumNulls()
		 := .NumValues()

		var ,  Value
		var  bool
		if .writePageBounds {
			, ,  = .Bounds()
		}

		.columnIndex.IndexPage(, , , )
		.columnChunk.MetaData.NumValues += 
		.columnChunk.MetaData.Statistics.NullCount += 

		if  {
			var ,  Value

			if .columnChunk.MetaData.Statistics.MaxValue != nil && .columnChunk.MetaData.Statistics.MinValue != nil {
				 = .columnType.Kind().Value(.columnChunk.MetaData.Statistics.MaxValue)
				 = .columnType.Kind().Value(.columnChunk.MetaData.Statistics.MinValue)
			}

			if .isNull() || .columnType.Compare(, ) > 0 {
				 := .columnChunk.MetaData.Statistics.MaxValue[:0]
				// if maxValue is empty string, c.columnChunk.MetaData.Statistics.MaxValue should be []bytes{}, but nil
				if  == nil && .Kind() == ByteArray && len(.ByteArray()) == 0 {
					 = make([]byte, 0)
				}
				.columnChunk.MetaData.Statistics.MaxValue = .AppendBytes()
			}

			if .isNull() || .columnType.Compare(, ) < 0 {
				 := .columnChunk.MetaData.Statistics.MinValue[:0]
				// same as above
				if  == nil && .Kind() == ByteArray && len(.ByteArray()) == 0 {
					 = make([]byte, 0)
				}
				.columnChunk.MetaData.Statistics.MinValue = .AppendBytes()
			}
		}

		.offsetIndex.PageLocations = append(.offsetIndex.PageLocations, format.PageLocation{
			Offset:             .columnChunk.MetaData.TotalCompressedSize,
			CompressedPageSize: ,
			FirstRowIndex:      .numRows,
		})

		.numRows += .NumRows()
	}

	 := .Type
	 := format.Encoding(-1)
	switch  {
	case format.DataPageV2:
		 = .DataPageHeaderV2.Encoding
	case format.DataPage:
		 = .DataPageHeader.Encoding
	case format.DictionaryPage:
		 = .DictionaryPageHeader.Encoding
	}

	.columnChunk.MetaData.TotalUncompressedSize += int64()
	.columnChunk.MetaData.TotalCompressedSize += int64()
	.columnChunk.MetaData.EncodingStats = addPageEncodingStats(.columnChunk.MetaData.EncodingStats, format.PageEncodingStats{
		PageType: ,
		Encoding: ,
		Count:    1,
	})
}

func addEncoding( []format.Encoding,  format.Encoding) []format.Encoding {
	for ,  := range  {
		if  ==  {
			return 
		}
	}
	return append(, )
}

func addPageEncodingStats( []format.PageEncodingStats,  ...format.PageEncodingStats) []format.PageEncodingStats {
:
	for ,  := range  {
		for ,  := range  {
			if .PageType == .PageType && .Encoding == .Encoding {
				[].Count += .Count
				continue 
			}
		}
		 = append(, )
	}
	return 
}

func sortPageEncodings( []format.Encoding) {
	sort.Slice(, func(,  int) bool {
		return [] < []
	})
}

func sortPageEncodingStats( []format.PageEncodingStats) {
	sort.Slice(, func(,  int) bool {
		 := &[]
		 := &[]
		if .PageType != .PageType {
			return .PageType < .PageType
		}
		return .Encoding < .Encoding
	})
}

type offsetTrackingWriter struct {
	writer io.Writer
	offset int64
}

func ( *offsetTrackingWriter) ( io.Writer) {
	.writer = 
	.offset = 0
}

func ( *offsetTrackingWriter) ( []byte) (int, error) {
	,  := .writer.Write()
	.offset += int64()
	return , 
}

func ( *offsetTrackingWriter) ( string) (int, error) {
	,  := io.WriteString(.writer, )
	.offset += int64()
	return , 
}

func ( *offsetTrackingWriter) ( io.Reader) (int64, error) {
	// io.Copy will make use of io.ReaderFrom if w.writer implements it.
	,  := io.Copy(.writer, )
	.offset += 
	return , 
}

var (
	_ RowWriterWithSchema = (*Writer)(nil)
	_ RowReaderFrom       = (*Writer)(nil)
	_ RowGroupWriter      = (*Writer)(nil)

	_ RowWriter   = (*writer)(nil)
	_ ValueWriter = (*writer)(nil)

	_ ValueWriter = (*writerColumn)(nil)

	_ io.ReaderFrom   = (*offsetTrackingWriter)(nil)
	_ io.StringWriter = (*offsetTrackingWriter)(nil)
)