class DynamicSizeUtil {

    public static void putKeyValueSize( PageCursor cursor, int keySize, int valueSize )
    {
        boolean hasAdditionalKeySize = keySize > MASK_ONE_BYTE_KEY_SIZE;
        boolean hasValueSize = valueSize > 0;

        // Key size
        {
            byte firstByte = (byte) (keySize & MASK_ONE_BYTE_KEY_SIZE); // Least significant 5 bits
            if ( hasAdditionalKeySize )
            {
                firstByte |= FLAG_ADDITIONAL_KEY_SIZE;
                if ( keySize > MAX_TWO_BYTE_KEY_SIZE )
                {
                    throw new IllegalArgumentException(
                            format( "Max supported key size is %d, but tried to store key of size %d. Please see index documentation for limitations.",
                                    MAX_TWO_BYTE_KEY_SIZE, keySize ) );
                }
            }
            if ( hasValueSize )
            {
                firstByte |= FLAG_HAS_VALUE_SIZE;
            }
            cursor.putByte( firstByte );

            if ( hasAdditionalKeySize )
            {
                // Assuming no key size larger than 4k
                cursor.putByte( (byte) (keySize >> SHIFT_LSB_KEY_SIZE) );
            }
        }

        // Value size
        {
            if ( hasValueSize )
            {
                boolean needsAdditionalValueSize = valueSize > MASK_ONE_BYTE_VALUE_SIZE;
                byte firstByte = (byte) (valueSize & MASK_ONE_BYTE_VALUE_SIZE); // Least significant 7 bits
                if ( needsAdditionalValueSize )
                {
                    if ( valueSize > MAX_TWO_BYTE_VALUE_SIZE )
                    {
                        throw new IllegalArgumentException(
                                format( "Max supported value size is %d, but tried to store value of size %d. Please see index documentation for limitations.",
                                        MAX_TWO_BYTE_VALUE_SIZE, valueSize ) );
                    }
                    firstByte |= FLAG_ADDITIONAL_VALUE_SIZE;
                }
                cursor.putByte( firstByte );

                if ( needsAdditionalValueSize )
                {
                    // Assuming no value size larger than 16k
                    cursor.putByte( (byte) (valueSize >> SHIFT_LSB_VALUE_SIZE) );
                }
            }
        }
    }

}