/*
 * 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 org.apache.fluss.row.compacted;

import org.apache.fluss.row.BinaryWriter;
import org.apache.fluss.types.DataType;

import static org.apache.fluss.row.BinaryRow.BinaryRowFormat.COMPACTED;

/**
 * A wrapping of {@link CompactedRowWriter} used to encode key columns.
 *
 * <p>The encoding is the same as {@link CompactedRowWriter}, but is without header of null bits to
 * represent whether the field value is null or not since the key columns must be not null.
 */
public class CompactedKeyWriter extends CompactedRowWriter {

    public CompactedKeyWriter() {
        // in compacted key encoder, we don't need to set null bits as the key columns must be not
        // null, to use field count 0 to init to make the null bits 0
        super(0);
    }

    public static ValueWriter createValueWriter(DataType fieldType) {
        ValueWriter valueWriter = BinaryWriter.createValueWriter(fieldType, COMPACTED);
        return (writer, pos, value) -> {
            if (value == null) {
                throw new IllegalArgumentException(
                        String.format(
                                "Null value is not allowed for compacted key encoder in position %d with type %s.",
                                pos, fieldType));
            } else {
                valueWriter.writeValue(writer, pos, value);
            }
        };
    }
}
