ptupitsyn commented on code in PR #4142:
URL: https://github.com/apache/ignite-3/pull/4142#discussion_r1722889004


##########
modules/binary-tuple/src/main/java/org/apache/ignite/internal/binarytuple/inlineschema/TupleWithSchemaMarshalling.java:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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.ignite.internal.binarytuple.inlineschema;
+
+import static org.apache.ignite.lang.ErrorGroups.Client.PROTOCOL_ERR;
+
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.Period;
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import org.apache.ignite.internal.binarytuple.BinaryTupleBuilder;
+import org.apache.ignite.internal.binarytuple.BinaryTupleReader;
+import org.apache.ignite.lang.IgniteException;
+import org.apache.ignite.marshalling.UnmarshallingException;
+import org.apache.ignite.marshalling.UnsupportedObjectTypeMarshallingException;
+import org.apache.ignite.sql.ColumnType;
+import org.apache.ignite.table.Tuple;
+import org.jetbrains.annotations.Nullable;
+
+/** Tuple with schema marshalling. */
+public final class TupleWithSchemaMarshalling {
+    private static final ByteOrder BYTE_ORDER = ByteOrder.LITTLE_ENDIAN;
+
+    /**
+     * Marshal tuple in the following format (LITTLE_ENDIAN).
+     *
+     * <pre>
+     * marshalledTuple := | size | valuePosition | binaryTupleWithSchema |
+     *
+     * size            := int32
+     * valuePosition   := int32
+     * binaryTupleWithSchema := | schemaBinaryTuple | valueBinaryTuple |
+     * schemaBinaryTuple := | column1 | ... | columnN |
+     * column              := | columnName | columnType |
+     * columnName          := string
+     * columnType          := int32
+     * valueBinaryTuple := | value1 | ... | valueN |.
+     * </pre>
+     */
+    public static byte @Nullable [] marshal(@Nullable Tuple tuple) {
+        if (tuple == null) {
+            return null;
+        }
+
+        // Allocate all the memory we need upfront.
+        int size = tuple.columnCount();
+        Object[] values = new Object[size];
+        String[] columns = new String[size];
+        ColumnType[] types = new ColumnType[size];
+
+        // Fill in the values, column names, and types.
+        for (int i = 0; i < size; i++) {
+            var value = tuple.value(i);
+            values[i] = value;
+            columns[i] = tuple.columnName(i);
+            types[i] = inferType(value);
+        }
+
+        ByteBuffer schemaBf = schemaBuilder(columns, types).build();
+        ByteBuffer valueBf = valueBuilder(columns, types, values).build();
+
+        byte[] schemaArr = getByteArray(schemaBf);
+        byte[] valueArr = getByteArray(valueBf);
+        // Size: int32 (tuple size), int32 (value offset), schema, value.
+        byte[] result = new byte[4 + 4 + schemaArr.length + valueArr.length];
+        ByteBuffer buff = ByteBuffer.wrap(result).order(BYTE_ORDER);
+
+        // Put the size of the schema in the first 4 bytes.
+        buff.putInt(0, size);
+
+        // Put the value offset in the second 4 bytes.
+        int offset = schemaArr.length + 8;
+        buff.putInt(4, offset);
+
+        System.arraycopy(schemaArr, 0, result, 8, schemaArr.length);
+        System.arraycopy(valueArr, 0, result, schemaArr.length + 8, 
valueArr.length);
+
+        return result;
+    }
+
+    /** Get byte array from ByteBuffer without capacity overhead, only 
meaningful bytes are returned. */
+    private static byte[] getByteArray(ByteBuffer buff) {
+        int offset = buff.arrayOffset();
+        int limit = buff.limit();
+        byte[] result = new byte[limit - offset];
+
+        buff.get(result, offset, limit);
+        return result;
+    }
+
+    /**
+     * Unmarshal tuple (LITTLE_ENDIAN).
+     *
+     * @param raw byte[] bytes that are marshaled by {@link #marshal(Tuple)}.
+     */
+    public static @Nullable Tuple unmarshal(byte @Nullable [] raw) {
+        if (raw == null) {
+            return null;
+        }
+        if (raw.length < 8) {
+            throw new UnmarshallingException("byte[] length can not be less 
than 8");
+        }
+
+        // Read first int32.
+        ByteBuffer buff = ByteBuffer.wrap(raw).order(BYTE_ORDER);
+        int size = buff.getInt(0);
+        if (size < 0) {
+            throw new UnmarshallingException("Size of the tuple can not be 
less than zero");
+        }
+
+        // Read second int32.
+        int valueOffset = buff.getInt(4);
+        if (valueOffset < 0) {
+            throw new UnmarshallingException("valueOffset can not be less than 
zero");
+        }
+        if (valueOffset > raw.length) {
+            throw new UnmarshallingException(
+                    "valueOffset can not be greater than byte[] length, 
valueOffset: "
+                            + valueOffset + ", length: " + raw.length
+            );
+        }
+
+        ByteBuffer schemaBuff = buff
+                .position(8).limit(valueOffset)
+                .slice().order(BYTE_ORDER);
+        ByteBuffer valueBuff = buff
+                .position(valueOffset).limit(raw.length)
+                .slice().order(BYTE_ORDER);
+
+        BinaryTupleReader schemaReader = new BinaryTupleReader(size * 2, 
schemaBuff);
+        BinaryTupleReader valueReader = new BinaryTupleReader(size, valueBuff);
+
+        String[] columns = new String[size];
+        ColumnType[] types = new ColumnType[size];
+        Tuple tup = Tuple.create(size);
+
+        int readerInd = 0;
+        int i = 0;
+        while (i < size) {
+            String colName = schemaReader.stringValue(readerInd++);
+            int colTypeId = schemaReader.intValue(readerInd++);
+
+            columns[i] = colName;
+            types[i] = ColumnType.getById(colTypeId);
+
+            i += 1;
+        }
+
+        int k = 0;
+        while (k < size) {
+            setColumnValue(valueReader, tup, columns[k], types[k].id(), k);
+            k += 1;
+        }
+
+        return tup;
+    }
+
+    private static BinaryTupleBuilder schemaBuilder(String[] columns, 
ColumnType[] types) {
+        BinaryTupleBuilder builder = new BinaryTupleBuilder(columns.length * 
2, columns.length * 2);
+
+        for (int i = 0; i < columns.length; i++) {
+            builder.appendString(columns[i]);
+            builder.appendInt(types[i].id());
+        }
+
+        return builder;
+    }
+
+    private static BinaryTupleBuilder valueBuilder(String[] columnNames, 
ColumnType[] types, Object[] values) {
+        BinaryTupleBuilder builder = new BinaryTupleBuilder(values.length, 
values.length);
+
+        for (int i = 0; i < values.length; i++) {
+            ColumnType type = types[i];
+            Object v = values[i];
+
+            appender(type, columnNames[i]).accept(builder, v);
+        }
+
+        return builder;
+    }
+
+    private static BiConsumer<BinaryTupleBuilder, Object> appender(ColumnType 
type, String name) {

Review Comment:
   This method returns a `BiConsumer` that is immediately invoked, which causes 
unnecessary allocation and indirection.
   
   We can either inline this method, or make it `void` and perform the append 
action immediately.



##########
modules/binary-tuple/src/main/java/org/apache/ignite/internal/binarytuple/inlineschema/TupleWithSchemaMarshalling.java:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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.ignite.internal.binarytuple.inlineschema;
+
+import static org.apache.ignite.lang.ErrorGroups.Client.PROTOCOL_ERR;
+
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.Period;
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import org.apache.ignite.internal.binarytuple.BinaryTupleBuilder;
+import org.apache.ignite.internal.binarytuple.BinaryTupleReader;
+import org.apache.ignite.lang.IgniteException;
+import org.apache.ignite.marshalling.UnmarshallingException;
+import org.apache.ignite.marshalling.UnsupportedObjectTypeMarshallingException;
+import org.apache.ignite.sql.ColumnType;
+import org.apache.ignite.table.Tuple;
+import org.jetbrains.annotations.Nullable;
+
+/** Tuple with schema marshalling. */
+public final class TupleWithSchemaMarshalling {
+    private static final ByteOrder BYTE_ORDER = ByteOrder.LITTLE_ENDIAN;
+
+    /**
+     * Marshal tuple in the following format (LITTLE_ENDIAN).
+     *
+     * <pre>
+     * marshalledTuple := | size | valuePosition | binaryTupleWithSchema |
+     *
+     * size            := int32
+     * valuePosition   := int32
+     * binaryTupleWithSchema := | schemaBinaryTuple | valueBinaryTuple |
+     * schemaBinaryTuple := | column1 | ... | columnN |
+     * column              := | columnName | columnType |
+     * columnName          := string
+     * columnType          := int32
+     * valueBinaryTuple := | value1 | ... | valueN |.
+     * </pre>
+     */
+    public static byte @Nullable [] marshal(@Nullable Tuple tuple) {
+        if (tuple == null) {
+            return null;
+        }
+
+        // Allocate all the memory we need upfront.
+        int size = tuple.columnCount();
+        Object[] values = new Object[size];
+        String[] columns = new String[size];
+        ColumnType[] types = new ColumnType[size];
+
+        // Fill in the values, column names, and types.
+        for (int i = 0; i < size; i++) {
+            var value = tuple.value(i);
+            values[i] = value;
+            columns[i] = tuple.columnName(i);
+            types[i] = inferType(value);
+        }
+
+        ByteBuffer schemaBf = schemaBuilder(columns, types).build();
+        ByteBuffer valueBf = valueBuilder(columns, types, values).build();
+
+        byte[] schemaArr = getByteArray(schemaBf);
+        byte[] valueArr = getByteArray(valueBf);
+        // Size: int32 (tuple size), int32 (value offset), schema, value.
+        byte[] result = new byte[4 + 4 + schemaArr.length + valueArr.length];
+        ByteBuffer buff = ByteBuffer.wrap(result).order(BYTE_ORDER);
+
+        // Put the size of the schema in the first 4 bytes.
+        buff.putInt(0, size);
+
+        // Put the value offset in the second 4 bytes.
+        int offset = schemaArr.length + 8;
+        buff.putInt(4, offset);
+
+        System.arraycopy(schemaArr, 0, result, 8, schemaArr.length);
+        System.arraycopy(valueArr, 0, result, schemaArr.length + 8, 
valueArr.length);
+
+        return result;
+    }
+
+    /** Get byte array from ByteBuffer without capacity overhead, only 
meaningful bytes are returned. */
+    private static byte[] getByteArray(ByteBuffer buff) {
+        int offset = buff.arrayOffset();
+        int limit = buff.limit();
+        byte[] result = new byte[limit - offset];
+
+        buff.get(result, offset, limit);
+        return result;
+    }
+
+    /**
+     * Unmarshal tuple (LITTLE_ENDIAN).
+     *
+     * @param raw byte[] bytes that are marshaled by {@link #marshal(Tuple)}.
+     */
+    public static @Nullable Tuple unmarshal(byte @Nullable [] raw) {
+        if (raw == null) {
+            return null;
+        }
+        if (raw.length < 8) {
+            throw new UnmarshallingException("byte[] length can not be less 
than 8");
+        }
+
+        // Read first int32.
+        ByteBuffer buff = ByteBuffer.wrap(raw).order(BYTE_ORDER);
+        int size = buff.getInt(0);
+        if (size < 0) {
+            throw new UnmarshallingException("Size of the tuple can not be 
less than zero");
+        }
+
+        // Read second int32.
+        int valueOffset = buff.getInt(4);
+        if (valueOffset < 0) {
+            throw new UnmarshallingException("valueOffset can not be less than 
zero");
+        }
+        if (valueOffset > raw.length) {
+            throw new UnmarshallingException(
+                    "valueOffset can not be greater than byte[] length, 
valueOffset: "
+                            + valueOffset + ", length: " + raw.length
+            );
+        }
+
+        ByteBuffer schemaBuff = buff
+                .position(8).limit(valueOffset)
+                .slice().order(BYTE_ORDER);
+        ByteBuffer valueBuff = buff
+                .position(valueOffset).limit(raw.length)
+                .slice().order(BYTE_ORDER);
+
+        BinaryTupleReader schemaReader = new BinaryTupleReader(size * 2, 
schemaBuff);
+        BinaryTupleReader valueReader = new BinaryTupleReader(size, valueBuff);
+
+        String[] columns = new String[size];
+        ColumnType[] types = new ColumnType[size];
+        Tuple tup = Tuple.create(size);
+
+        int readerInd = 0;
+        int i = 0;
+        while (i < size) {
+            String colName = schemaReader.stringValue(readerInd++);
+            int colTypeId = schemaReader.intValue(readerInd++);
+
+            columns[i] = colName;
+            types[i] = ColumnType.getById(colTypeId);
+
+            i += 1;
+        }
+
+        int k = 0;
+        while (k < size) {
+            setColumnValue(valueReader, tup, columns[k], types[k].id(), k);

Review Comment:
   We convert `ColumnType` to int here, then convert back inside 
`setColumnValue`, can we pass it as is?



##########
modules/binary-tuple/src/main/java/org/apache/ignite/internal/binarytuple/inlineschema/TupleWithSchemaMarshalling.java:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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.ignite.internal.binarytuple.inlineschema;
+
+import static org.apache.ignite.lang.ErrorGroups.Client.PROTOCOL_ERR;
+
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.Period;
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import org.apache.ignite.internal.binarytuple.BinaryTupleBuilder;
+import org.apache.ignite.internal.binarytuple.BinaryTupleReader;
+import org.apache.ignite.lang.IgniteException;
+import org.apache.ignite.marshalling.UnmarshallingException;
+import org.apache.ignite.marshalling.UnsupportedObjectTypeMarshallingException;
+import org.apache.ignite.sql.ColumnType;
+import org.apache.ignite.table.Tuple;
+import org.jetbrains.annotations.Nullable;
+
+/** Tuple with schema marshalling. */
+public final class TupleWithSchemaMarshalling {
+    private static final ByteOrder BYTE_ORDER = ByteOrder.LITTLE_ENDIAN;
+
+    /**
+     * Marshal tuple in the following format (LITTLE_ENDIAN).
+     *
+     * <pre>
+     * marshalledTuple := | size | valuePosition | binaryTupleWithSchema |
+     *
+     * size            := int32
+     * valuePosition   := int32
+     * binaryTupleWithSchema := | schemaBinaryTuple | valueBinaryTuple |
+     * schemaBinaryTuple := | column1 | ... | columnN |
+     * column              := | columnName | columnType |
+     * columnName          := string
+     * columnType          := int32
+     * valueBinaryTuple := | value1 | ... | valueN |.
+     * </pre>
+     */
+    public static byte @Nullable [] marshal(@Nullable Tuple tuple) {
+        if (tuple == null) {
+            return null;
+        }
+
+        // Allocate all the memory we need upfront.
+        int size = tuple.columnCount();
+        Object[] values = new Object[size];
+        String[] columns = new String[size];
+        ColumnType[] types = new ColumnType[size];
+
+        // Fill in the values, column names, and types.
+        for (int i = 0; i < size; i++) {
+            var value = tuple.value(i);
+            values[i] = value;
+            columns[i] = tuple.columnName(i);
+            types[i] = inferType(value);
+        }
+
+        ByteBuffer schemaBf = schemaBuilder(columns, types).build();
+        ByteBuffer valueBf = valueBuilder(columns, types, values).build();
+
+        byte[] schemaArr = getByteArray(schemaBf);
+        byte[] valueArr = getByteArray(valueBf);
+        // Size: int32 (tuple size), int32 (value offset), schema, value.
+        byte[] result = new byte[4 + 4 + schemaArr.length + valueArr.length];
+        ByteBuffer buff = ByteBuffer.wrap(result).order(BYTE_ORDER);
+
+        // Put the size of the schema in the first 4 bytes.
+        buff.putInt(0, size);
+
+        // Put the value offset in the second 4 bytes.
+        int offset = schemaArr.length + 8;
+        buff.putInt(4, offset);
+
+        System.arraycopy(schemaArr, 0, result, 8, schemaArr.length);
+        System.arraycopy(valueArr, 0, result, schemaArr.length + 8, 
valueArr.length);

Review Comment:
   Remove `getByteArray` method, it performs unnecessary allocations. You can 
copy from one `ByteBuffer` to another directly.
   
   ```suggestion
           int schemaBufLen = schemaBf.remaining();
           int valueBufLen = valueBf.remaining();
   
           // Size: int32 (tuple size), int32 (value offset), schema, value.
           byte[] result = new byte[4 + 4 + schemaBufLen + valueBufLen];
           ByteBuffer buff = ByteBuffer.wrap(result).order(BYTE_ORDER);
   
           // Put the size of the schema in the first 4 bytes.
           buff.putInt(size);
   
           // Put the value offset in the second 4 bytes.
           int offset = schemaBufLen + 8;
           buff.putInt(offset);
   
           buff.put(schemaBf);
           buff.put(valueBf);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to