You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by ag...@apache.org on 2015/11/03 11:30:29 UTC

[1/5] ignite git commit: IGNITE-1418: Implemented compact field offsets.

Repository: ignite
Updated Branches:
  refs/heads/ignite-950-new 7b9136ea2 -> c050b4ce6


http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/src/impl/portable/portable_schema.cpp
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/src/impl/portable/portable_schema.cpp b/modules/platforms/cpp/core/src/impl/portable/portable_schema.cpp
index 57c23a7..448cf02 100644
--- a/modules/platforms/cpp/core/src/impl/portable/portable_schema.cpp
+++ b/modules/platforms/cpp/core/src/impl/portable/portable_schema.cpp
@@ -15,6 +15,8 @@
 * limitations under the License.
 */
 
+#include <cassert>
+
 #include "ignite/impl/portable/portable_schema.h"
 #include "ignite/impl/portable/portable_writer_impl.h"
 
@@ -66,10 +68,43 @@ namespace ignite
 
             void PortableSchema::Write(interop::InteropOutputStream& out) const
             {
-                for (FieldContainer::const_iterator i = fieldsInfo->begin(); i != fieldsInfo->end(); ++i)
+                switch (GetType())
                 {
-                    out.WriteInt32(i->id);
-                    out.WriteInt32(i->offset);
+                    case OFFSET_TYPE_1_BYTE:
+                    {
+                        for (FieldContainer::const_iterator i = fieldsInfo->begin(); i != fieldsInfo->end(); ++i)
+                        {
+                            out.WriteInt32(i->id);
+                            out.WriteInt8(static_cast<int8_t>(i->offset));
+                        }
+                        break;
+                    }
+
+                    case OFFSET_TYPE_2_BYTE:
+                    {
+                        for (FieldContainer::const_iterator i = fieldsInfo->begin(); i != fieldsInfo->end(); ++i)
+                        {
+                            out.WriteInt32(i->id);
+                            out.WriteInt16(static_cast<int16_t>(i->offset));
+                        }
+                        break;
+                    }
+
+                    case OFFSET_TYPE_4_BYTE:
+                    {
+                        for (FieldContainer::const_iterator i = fieldsInfo->begin(); i != fieldsInfo->end(); ++i)
+                        {
+                            out.WriteInt32(i->id);
+                            out.WriteInt32(i->offset);
+                        }
+                        break;
+                    }
+
+                    default:
+                    {
+                        assert(false);
+                        break;
+                    }
                 }
             }
 
@@ -83,6 +118,18 @@ namespace ignite
                 id = 0;
                 fieldsInfo->clear();
             }
+
+            PortableOffsetType PortableSchema::GetType() const
+            {
+                int32_t maxOffset = fieldsInfo->back().offset;
+
+                if (maxOffset < 0x100)
+                    return OFFSET_TYPE_1_BYTE;
+                else if (maxOffset < 0x10000)
+                    return OFFSET_TYPE_2_BYTE;
+
+                return OFFSET_TYPE_4_BYTE;
+            }
         }
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/src/impl/portable/portable_writer_impl.cpp
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/src/impl/portable/portable_writer_impl.cpp b/modules/platforms/cpp/core/src/impl/portable/portable_writer_impl.cpp
index 4b65b4b..2dac125 100644
--- a/modules/platforms/cpp/core/src/impl/portable/portable_writer_impl.cpp
+++ b/modules/platforms/cpp/core/src/impl/portable/portable_writer_impl.cpp
@@ -567,13 +567,12 @@ namespace ignite
             {
                 int32_t lenWithoutSchema = stream->Position() - start;
 
+                int32_t nonRawLen = rawPos == -1 ? lenWithoutSchema : rawPos - start;
+                
                 if (schema.Empty())
                 {
-                    InteropStreamPositionGuard<InteropOutputStream> guard(*stream);
-
-                    stream->Position(start + IGNITE_OFFSET_FLAGS);
-                    stream->WriteInt16(IGNITE_PORTABLE_FLAG_USER_OBJECT | IGNITE_PORTABLE_FLAG_RAW_ONLY);
-
+                    stream->WriteInt16(start + IGNITE_OFFSET_FLAGS, IGNITE_PORTABLE_FLAG_USER_OBJECT | 
+                                                                    IGNITE_PORTABLE_FLAG_RAW_ONLY);
                     stream->WriteInt32(start + IGNITE_OFFSET_LEN, lenWithoutSchema);
                     stream->WriteInt32(start + IGNITE_OFFSET_SCHEMA_ID, 0);
                     stream->WriteInt32(start + IGNITE_OFFSET_SCHEMA_OR_RAW_OFF, GetRawPosition() - start);
@@ -581,6 +580,7 @@ namespace ignite
                 else
                 {
                     int32_t schemaId = schema.GetId();
+                    PortableOffsetType schemaType = schema.GetType();
 
                     WriteAndClearSchema();
 
@@ -589,6 +589,17 @@ namespace ignite
 
                     int32_t length = stream->Position() - start;
 
+                    if (schemaType == OFFSET_TYPE_1_BYTE)
+                    {
+                        stream->WriteInt16(start + IGNITE_OFFSET_FLAGS, 
+                            IGNITE_PORTABLE_FLAG_USER_OBJECT | IGNITE_PORTABLE_FLAG_OFFSET_1_BYTE);
+                    }
+                    else if (schemaType == OFFSET_TYPE_2_BYTE)
+                    {
+                        stream->WriteInt16(start + IGNITE_OFFSET_FLAGS, 
+                            IGNITE_PORTABLE_FLAG_USER_OBJECT | IGNITE_PORTABLE_FLAG_OFFSET_2_BYTE);
+                    }
+
                     stream->WriteInt32(start + IGNITE_OFFSET_LEN, length);
                     stream->WriteInt32(start + IGNITE_OFFSET_SCHEMA_ID, schemaId);
                     stream->WriteInt32(start + IGNITE_OFFSET_SCHEMA_OR_RAW_OFF, lenWithoutSchema);

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Portable/PortableSelfTest.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Portable/PortableSelfTest.cs b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Portable/PortableSelfTest.cs
index 08e0b31..2313f92 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Portable/PortableSelfTest.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Portable/PortableSelfTest.cs
@@ -1225,6 +1225,38 @@ namespace Apache.Ignite.Core.Tests.Portable
             Assert.AreEqual(nDateArr, obj2.NDateArr);
         }
 
+        /// <summary>
+        /// Writes objects of various sizes to test schema compaction 
+        /// (where field offsets can be stored as 1, 2 or 4 bytes).
+        /// </summary>
+        [Test]
+        public void TestCompactSchema()
+        {
+            var marsh = new PortableMarshaller(new PortableConfiguration
+            {
+                TypeConfigurations = new List<PortableTypeConfiguration>
+                {
+                    new PortableTypeConfiguration(typeof (SpecialArray)),
+                    new PortableTypeConfiguration(typeof (SpecialArrayMarshalAware))
+                }
+            });
+
+            var dt = new SpecialArrayMarshalAware();
+
+            foreach (var i in new[] {1, 5, 10, 13, 14, 15, 100, 200, 1000, 5000, 15000, 30000})
+            {
+                dt.NGuidArr = Enumerable.Range(1, i).Select(x => (Guid?) Guid.NewGuid()).ToArray();
+                dt.NDateArr = Enumerable.Range(1, i).Select(x => (DateTime?) DateTime.Now.AddDays(x)).ToArray();
+
+                var bytes = marsh.Marshal(dt);
+
+                var res = marsh.Unmarshal<SpecialArrayMarshalAware>(bytes);
+
+                CollectionAssert.AreEquivalent(dt.NGuidArr, res.NGuidArr);
+                CollectionAssert.AreEquivalent(dt.NDateArr, res.NDateArr);
+            }
+        }
+
         private static void CheckKeepSerialized(PortableConfiguration cfg, bool expKeep)
         {
             if (cfg.TypeConfigurations == null)

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Common/ResizeableArray.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Common/ResizeableArray.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Common/ResizeableArray.cs
index cb432e5..82a8eee 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Common/ResizeableArray.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Common/ResizeableArray.cs
@@ -1,4 +1,4 @@
-/*
+/*
  * 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.
@@ -27,9 +27,6 @@ namespace Apache.Ignite.Core.Impl.Common
         /** Array. */
         private T[] _arr;
 
-        /** Items count. */
-        private int _count;
-
         /// <summary>
         /// Constructor.
         /// </summary>
@@ -50,10 +47,7 @@ namespace Apache.Ignite.Core.Impl.Common
         /// <summary>
         /// Count.
         /// </summary>
-        public int Count
-        {
-            get { return _count; }
-        }
+        public int Count { get; private set; }
 
         /// <summary>
         /// Add element.
@@ -61,10 +55,10 @@ namespace Apache.Ignite.Core.Impl.Common
         /// <param name="element">Element.</param>
         public void Add(T element)
         {
-            if (_count == _arr.Length)
+            if (Count == _arr.Length)
                 System.Array.Resize(ref _arr, _arr.Length*2);
 
-            _arr[_count++] = element;
+            _arr[Count++] = element;
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/ExceptionUtils.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/ExceptionUtils.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/ExceptionUtils.cs
index ea109ba..c12a651 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/ExceptionUtils.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/ExceptionUtils.cs
@@ -21,7 +21,6 @@ namespace Apache.Ignite.Core.Impl
     using System.Collections.Generic;
     using System.Diagnostics;
     using System.Diagnostics.CodeAnalysis;
-    using System.Runtime.InteropServices;
     using System.Security;
     using System.Threading;
     using Apache.Ignite.Core.Cache;
@@ -35,7 +34,6 @@ namespace Apache.Ignite.Core.Impl
     /// <summary>
     /// Managed environment. Acts as a gateway for native code.
     /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
     internal static class ExceptionUtils
     {
         /** NoClassDefFoundError fully-qualified class name which is important during startup phase. */

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableBuilderImpl.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableBuilderImpl.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableBuilderImpl.cs
index 08a1d00..c299039 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableBuilderImpl.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableBuilderImpl.cs
@@ -569,7 +569,7 @@ namespace Apache.Ignite.Core.Impl.Portable
         /// <param name="hash">New hash.</param>
         /// <param name="vals">Values to be replaced.</param>
         /// <returns>Mutated object.</returns>
-        private unsafe void Mutate0(Context ctx, PortableHeapStream inStream, IPortableStream outStream,
+        private void Mutate0(Context ctx, PortableHeapStream inStream, IPortableStream outStream,
             bool changeHash, int hash, IDictionary<int, PortableBuilderField> vals)
         {
             int inStartPos = inStream.Position;
@@ -694,12 +694,14 @@ namespace Apache.Ignite.Core.Impl.Portable
 
                         // Write schema
                         int outSchemaOff = outRawOff;
+                        short flags = 0;
 
                         if (outSchema != null)
                         {
                             outSchemaOff = outStream.Position - outStartPos;
 
-                            PortableObjectSchemaField.WriteArray(outSchema.Array, outStream, outSchema.Count);
+                            flags = PortableObjectHeader.WriteSchema(outSchema.Array, outStream, outSchema.Count,
+                                outStream.Position - outStartPos);
 
                             if (inRawLen > 0)
                                 outStream.WriteInt(outRawOff);
@@ -712,7 +714,7 @@ namespace Apache.Ignite.Core.Impl.Portable
                         var outHash = changeHash ? hash : inHeader.HashCode;
 
                         var outHeader = new PortableObjectHeader(inHeader.IsUserType, inHeader.TypeId, outHash, 
-                            outLen, outSchemaId, outSchemaOff, outSchema == null);
+                            outLen, outSchemaId, outSchemaOff, outSchema == null, flags);
 
                         PortableObjectHeader.Write(outHeader, outStream, outStartPos);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectHeader.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectHeader.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectHeader.cs
index b3768a0..50adc02 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectHeader.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectHeader.cs
@@ -27,17 +27,23 @@ namespace Apache.Ignite.Core.Impl.Portable
     /// <summary>
     /// Portable object header structure.
     /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
+    [StructLayout(LayoutKind.Sequential, Pack = 0)]
     internal struct PortableObjectHeader : IEquatable<PortableObjectHeader>
     {
-        /** Size, equals to sizeof(PortableObjectHeader) */
+        /** Size, equals to sizeof(PortableObjectHeader). */
         public const int Size = 24;
 
-        /** User type flag */
-        private const int FlagUserType = 0x1;
+        /** User type flag. */
+        public const short FlagUserType = 0x1;
 
-        /** Raw only flag */
-        private const int FlagRawOnly = 0x2;
+        /** Raw only flag. */
+        public const short FlagRawOnly = 0x2;
+
+        /** Byte-sized field offsets flag. */
+        public const short FlagByteOffsets = 0x4;
+
+        /** Short-sized field offsets flag. */
+        public const short FlagShortOffsets = 0x8;
 
         /** Actual header layout */
         public readonly byte Header;        // Header code, always 103 (HdrFull)
@@ -50,7 +56,7 @@ namespace Apache.Ignite.Core.Impl.Portable
         public readonly int SchemaOffset;   // Schema offset, or raw offset when RawOnly flag is set.
 
         /// <summary>
-        /// Initializes a new instance of the <see cref="PortableObjectHeader"/> struct.
+        /// Initializes a new instance of the <see cref="PortableObjectHeader" /> struct.
         /// </summary>
         /// <param name="userType">User type flag.</param>
         /// <param name="typeId">Type ID.</param>
@@ -59,18 +65,23 @@ namespace Apache.Ignite.Core.Impl.Portable
         /// <param name="schemaId">Schema ID.</param>
         /// <param name="schemaOffset">Schema offset.</param>
         /// <param name="rawOnly">Raw flag.</param>
-        public PortableObjectHeader(bool userType, int typeId, int hashCode, int length, int schemaId, int schemaOffset, bool rawOnly)
+        /// <param name="flags">The flags.</param>
+        public PortableObjectHeader(bool userType, int typeId, int hashCode, int length, int schemaId, int schemaOffset, 
+            bool rawOnly, short flags)
         {
             Header = PortableUtils.HdrFull;
             Version = PortableUtils.ProtoVer;
 
             Debug.Assert(schemaOffset <= length);
             Debug.Assert(schemaOffset >= Size);
-            
-            Flags = (short) (userType ? FlagUserType : 0);
+
+            if (userType)
+                flags |= FlagUserType;
 
             if (rawOnly)
-                Flags = (short) (Flags | FlagRawOnly);
+                flags |= FlagRawOnly;
+
+            Flags = flags;
 
             TypeId = typeId;
             HashCode = hashCode;
@@ -134,49 +145,50 @@ namespace Apache.Ignite.Core.Impl.Portable
         {
             get
             {
-                // Odd amount of records in schema => raw offset is the very last 4 bytes in object.
-                return !IsRawOnly && (((Length - SchemaOffset) >> 2) & 0x1) != 0x0;
+                // Remainder => raw offset is the very last 4 bytes in object.
+                return !IsRawOnly && ((Length - SchemaOffset) % SchemaFieldSize) == 4;
             }
         }
 
         /// <summary>
-        /// Gets the schema field count.
+        /// Gets the size of the schema field offset (1, 2 or 4 bytes).
         /// </summary>
-        public int SchemaFieldCount
+        public int SchemaFieldOffsetSize
         {
             get
             {
-                if (IsRawOnly)
-                    return 0;
-
-                var schemaSize = Length - SchemaOffset;
+                if ((Flags & FlagByteOffsets) == FlagByteOffsets)
+                    return 1;
 
-                if (HasRawOffset)
-                    schemaSize -= 4;
+                if ((Flags & FlagShortOffsets) == FlagShortOffsets)
+                    return 2;
 
-                return schemaSize >> 3;  // 8 == PortableObjectSchemaField.Size
+                return 4;
             }
         }
 
         /// <summary>
-        /// Gets the schema end.
+        /// Gets the size of the schema field.
         /// </summary>
-        public int GetSchemaEnd(int position)
+        public int SchemaFieldSize
         {
-            var res = position + Length;
-
-            if (HasRawOffset)
-                res -= 4;
-
-            return res;
+            get { return SchemaFieldOffsetSize + 4; }
         }
 
         /// <summary>
-        /// Gets the schema start.
+        /// Gets the schema field count.
         /// </summary>
-        public int GetSchemaStart(int position)
+        public int SchemaFieldCount
         {
-            return IsRawOnly ? GetSchemaEnd(position) : position + SchemaOffset;
+            get
+            {
+                if (IsRawOnly)
+                    return 0;
+
+                var schemaSize = Length - SchemaOffset;
+
+                return schemaSize / SchemaFieldSize;
+            }
         }
 
         /// <summary>
@@ -214,10 +226,25 @@ namespace Apache.Ignite.Core.Impl.Portable
 
             stream.Seek(position + SchemaOffset, SeekOrigin.Begin);
 
-            var schema = new Dictionary<int, int>(schemaSize >> 3);
+            var schema = new Dictionary<int, int>(schemaSize);
+
+            var offsetSize = SchemaFieldOffsetSize;
 
-            for (var i = 0; i < schemaSize; i++)
-                schema.Add(stream.ReadInt(), stream.ReadInt());
+            if (offsetSize == 1)
+            {
+                for (var i = 0; i < schemaSize; i++)
+                    schema.Add(stream.ReadInt(), stream.ReadByte());
+            }
+            else if (offsetSize == 2)
+            {
+                for (var i = 0; i < schemaSize; i++)
+                    schema.Add(stream.ReadInt(), stream.ReadShort());
+            }
+            else
+            {
+                for (var i = 0; i < schemaSize; i++)
+                    schema.Add(stream.ReadInt(), stream.ReadInt());
+            }
 
             return schema;
         }
@@ -239,7 +266,98 @@ namespace Apache.Ignite.Core.Impl.Portable
 
             stream.Seek(position + SchemaOffset, SeekOrigin.Begin);
 
-            return PortableObjectSchemaField.ReadArray(stream, schemaSize);
+            var schema = new PortableObjectSchemaField[schemaSize];
+
+            var offsetSize = SchemaFieldOffsetSize;
+
+            if (offsetSize == 1)
+            {
+                for (var i = 0; i < schemaSize; i++)
+                    schema[i] = new PortableObjectSchemaField(stream.ReadInt(), stream.ReadByte());
+            }
+            else if (offsetSize == 2)
+            {
+                for (var i = 0; i < schemaSize; i++)
+                    schema[i] = new PortableObjectSchemaField(stream.ReadInt(), stream.ReadShort());
+            }
+            else
+            {
+                for (var i = 0; i < schemaSize; i++)
+                    schema[i] = new PortableObjectSchemaField(stream.ReadInt(), stream.ReadInt());
+            }
+
+            return schema;
+        }
+
+        /// <summary>
+        /// Writes an array of fields to a stream.
+        /// </summary>
+        /// <param name="fields">Fields.</param>
+        /// <param name="stream">Stream.</param>
+        /// <param name="count">Field count to write.</param>
+        /// <param name="maxOffset">The maximum field offset to determine 
+        /// whether 1, 2 or 4 bytes are needed for offsets.</param>
+        /// <returns>
+        /// Flags according to offset sizes: <see cref="PortableObjectHeader.FlagByteOffsets"/>, 
+        /// <see cref="PortableObjectHeader.FlagShortOffsets"/>, or 0.
+        /// </returns>
+        public static unsafe short WriteSchema(PortableObjectSchemaField[] fields, IPortableStream stream, int count,
+            int maxOffset)
+        {
+            Debug.Assert(fields != null);
+            Debug.Assert(stream != null);
+            Debug.Assert(count > 0);
+
+            unchecked
+            {
+                if (maxOffset <= byte.MaxValue)
+                {
+                    for (int i = 0; i < count; i++)
+                    {
+                        var field = fields[i];
+
+                        stream.WriteInt(field.Id);
+                        stream.WriteByte((byte)field.Offset);
+                    }
+
+                    return FlagByteOffsets;
+                }
+
+                if (maxOffset <= ushort.MaxValue)
+                {
+                    for (int i = 0; i < count; i++)
+                    {
+                        var field = fields[i];
+
+                        stream.WriteInt(field.Id);
+
+                        stream.WriteShort((short)field.Offset);
+                    }
+
+                    return FlagShortOffsets;
+                }
+
+                if (BitConverter.IsLittleEndian)
+                {
+                    fixed (PortableObjectSchemaField* ptr = &fields[0])
+                    {
+                        stream.Write((byte*)ptr, count / PortableObjectSchemaField.Size);
+                    }
+                }
+                else
+                {
+                    for (int i = 0; i < count; i++)
+                    {
+                        var field = fields[i];
+
+                        stream.WriteInt(field.Id);
+                        stream.WriteInt(field.Offset);
+                    }
+                }
+
+                return 0;
+            }
+
         }
 
         /// <summary>
@@ -284,6 +402,10 @@ namespace Apache.Ignite.Core.Impl.Portable
                 Debug.Assert(hdr.SchemaOffset <= hdr.Length);
                 Debug.Assert(hdr.SchemaOffset >= Size);
 
+                // Only one of the flags can be set
+                var f = hdr.Flags;
+                Debug.Assert((f & (FlagShortOffsets | FlagByteOffsets)) != (FlagShortOffsets | FlagByteOffsets));
+
                 return hdr;
             }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchema.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchema.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchema.cs
index 7d3663c..51ae34e 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchema.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchema.cs
@@ -20,7 +20,7 @@ namespace Apache.Ignite.Core.Impl.Portable
     using System.Collections.Generic;
 
     /// <summary>
-    /// Holds and manages portable object schema for a specific type.
+    /// Holds and manages portable object schemas for a specific type.
     /// </summary>
     internal class PortableObjectSchema
     {
@@ -44,7 +44,7 @@ namespace Apache.Ignite.Core.Impl.Portable
         /// </summary>
         /// <param name="id">Schema id.</param>
         /// <returns>Schema or null.</returns>
-        public int[] GetSchema(int id)
+        public int[] Get(int id)
         {
             if (_schemaId1 == id)
                 return _schema1;
@@ -65,7 +65,7 @@ namespace Apache.Ignite.Core.Impl.Portable
         /// </summary>
         /// <param name="id">Schema id.</param>
         /// <param name="schema">Schema.</param>
-        public void AddSchema(int id, int[] schema)
+        public void Add(int id, int[] schema)
         {
             lock (this)
             {

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchemaField.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchemaField.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchemaField.cs
index 48fd9c1..bc18191 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchemaField.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableObjectSchemaField.cs
@@ -17,15 +17,12 @@
 
 namespace Apache.Ignite.Core.Impl.Portable
 {
-    using System;
-    using System.Diagnostics;
     using System.Runtime.InteropServices;
-    using Apache.Ignite.Core.Impl.Portable.IO;
 
     /// <summary>
     /// Portable schema field DTO (as it is stored in a stream).
     /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
+    [StructLayout(LayoutKind.Sequential, Pack = 0)]
     internal struct PortableObjectSchemaField
     {
         /* Field ID */
@@ -35,7 +32,7 @@ namespace Apache.Ignite.Core.Impl.Portable
         public readonly int Offset;
 
         /** Size, equals to sizeof(PortableObjectSchemaField) */
-        private const int Size = 8;
+        public const int Size = 8;
 
         /// <summary>
         /// Initializes a new instance of the <see cref="PortableObjectSchemaField"/> struct.
@@ -47,67 +44,5 @@ namespace Apache.Ignite.Core.Impl.Portable
             Id = id;
             Offset = offset;
         }
-
-        /// <summary>
-        /// Writes an array of fields to a stream.
-        /// </summary>
-        /// <param name="fields">Fields.</param>
-        /// <param name="stream">Stream.</param>
-        /// <param name="count">Field count to write.</param>
-        public static unsafe void WriteArray(PortableObjectSchemaField[] fields, IPortableStream stream, int count)
-        {
-            Debug.Assert(fields != null);
-            Debug.Assert(stream != null);
-            Debug.Assert(count > 0);
-
-            if (BitConverter.IsLittleEndian)
-            {
-                fixed (PortableObjectSchemaField* ptr = &fields[0])
-                {
-                    stream.Write((byte*) ptr, count * Size);
-                }
-            }
-            else
-            {
-                for (int i = 0; i < count; i++)
-                {
-                    var field = fields[i];
-
-                    stream.WriteInt(field.Id);
-                    stream.WriteInt(field.Offset);
-                }
-            }
-        }
-
-        /// <summary>
-        /// Reads an array of fields from a stream.
-        /// </summary>
-        /// <param name="stream">Stream.</param>
-        /// <param name="count">Count.</param>
-        /// <returns></returns>
-        public static unsafe PortableObjectSchemaField[] ReadArray(IPortableStream stream, int count)
-        {
-            Debug.Assert(stream != null);
-            Debug.Assert(count > 0);
-
-            var res = new PortableObjectSchemaField[count];
-
-            if (BitConverter.IsLittleEndian)
-            {
-                fixed (PortableObjectSchemaField* ptr = &res[0])
-                {
-                    stream.Read((byte*) ptr, count * Size);
-                }
-            }
-            else
-            {
-                for (int i = 0; i < count; i++) 
-                {
-                    res[i] = new PortableObjectSchemaField(stream.ReadInt(), stream.ReadInt());
-                }
-            }
-
-            return res;
-        }
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableReaderImpl.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableReaderImpl.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableReaderImpl.cs
index 48ea799..2b7ddb8 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableReaderImpl.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableReaderImpl.cs
@@ -45,15 +45,9 @@ namespace Apache.Ignite.Core.Impl.Portable
         /** Handles. */
         private PortableReaderHandleDictionary _hnds;
 
-        /** Current type ID. */
-        private int _curTypeId;
-
         /** Current position. */
         private int _curPos;
 
-        /** Current raw data offset. */
-        private int _curRawOffset;
-
         /** Current raw flag. */
         private bool _curRaw;
 
@@ -66,14 +60,14 @@ namespace Apache.Ignite.Core.Impl.Portable
         /** Current type structure tracker. */
         private PortableStructureTracker _curStruct;
 
-        /** */
-        private int _curFooterStart;
+        /** Current schema. */
+        private int[] _curSchema;
 
-        /** */
-        private int _curFooterEnd;
+        /** Current schema with positions. */
+        private Dictionary<int, int> _curSchemaMap;
 
-        /** */
-        private int[] _curSchema;
+        /** Current header. */
+        private PortableObjectHeader _curHdr;
 
         /// <summary>
         /// Constructor.
@@ -432,9 +426,7 @@ namespace Apache.Ignite.Core.Impl.Portable
             if (_curRaw)
                 throw new PortableException("Cannot read named fields after raw data is read.");
 
-            int fieldId = _curStruct.GetFieldId(fieldName);
-
-            if (SeekField(fieldId))
+            if (SeekField(fieldName))
                 return Deserialize<T>();
 
             return default(T);
@@ -669,31 +661,26 @@ namespace Apache.Ignite.Core.Impl.Portable
                                                     desc.TypeId + ", typeName=" + desc.TypeName + ']');
 
                     // Preserve old frame.
-                    int oldTypeId = _curTypeId;
+                    var oldHdr = _curHdr;
                     int oldPos = _curPos;
-                    int oldRawOffset = _curRawOffset;
                     var oldStruct = _curStruct;
                     bool oldRaw = _curRaw;
-                    var oldFooterStart = _curFooterStart;
-                    var oldFooterEnd = _curFooterEnd;
                     var oldSchema = _curSchema;
+                    var oldSchemaMap = _curSchemaMap;
 
                     // Set new frame.
-                    _curTypeId = hdr.TypeId;
+                    _curHdr = hdr;
                     _curPos = pos;
-                    _curFooterEnd = hdr.GetSchemaEnd(pos);
-                    _curFooterStart = hdr.GetSchemaStart(pos);
                     
-                    _curSchema = desc.Schema.GetSchema(hdr.SchemaId);
+                    _curSchema = desc.Schema.Get(hdr.SchemaId);
 
                     if (_curSchema == null)
                     {
                         _curSchema = ReadSchema();
 
-                        desc.Schema.AddSchema(hdr.SchemaId, _curSchema);
+                        desc.Schema.Add(hdr.SchemaId, _curSchema);
                     }
 
-                    _curRawOffset = hdr.GetRawOffset(Stream, pos);
                     _curStruct = new PortableStructureTracker(desc, desc.ReaderTypeStructure);
                     _curRaw = false;
 
@@ -727,14 +714,12 @@ namespace Apache.Ignite.Core.Impl.Portable
                     _curStruct.UpdateReaderStructure();
 
                     // Restore old frame.
-                    _curTypeId = oldTypeId;
+                    _curHdr = oldHdr;
                     _curPos = oldPos;
-                    _curRawOffset = oldRawOffset;
                     _curStruct = oldStruct;
                     _curRaw = oldRaw;
-                    _curFooterStart = oldFooterStart;
-                    _curFooterEnd = oldFooterEnd;
                     _curSchema = oldSchema;
+                    _curSchemaMap = oldSchemaMap;
 
                     // Process wrappers. We could introduce a common interface, but for only 2 if-else is faster.
                     var wrappedSerializable = obj as SerializableObjectHolder;
@@ -762,21 +747,22 @@ namespace Apache.Ignite.Core.Impl.Portable
         /// </summary>
         private int[] ReadSchema()
         {
-            Stream.Seek(_curFooterStart, SeekOrigin.Begin);
-            
-            var count = (_curFooterEnd - _curFooterStart) >> 3;
-            
+            Stream.Seek(_curPos + _curHdr.SchemaOffset, SeekOrigin.Begin);
+
+            var count = _curHdr.SchemaFieldCount;
+
+            var offsetSize = _curHdr.SchemaFieldOffsetSize;
+
             var res = new int[count];
 
             for (int i = 0; i < count; i++)
             {
                 res[i] = Stream.ReadInt();
-                Stream.Seek(4, SeekOrigin.Current);
+                Stream.Seek(offsetSize, SeekOrigin.Current);
             }
 
             return res;
         }
-
         /// <summary>
         /// Reads the handle object.
         /// </summary>
@@ -846,38 +832,11 @@ namespace Apache.Ignite.Core.Impl.Portable
             {
                 _curRaw = true;
 
-                Stream.Seek(_curPos + _curRawOffset, SeekOrigin.Begin);
+                Stream.Seek(_curPos + _curHdr.GetRawOffset(Stream, _curPos), SeekOrigin.Begin);
             }
         }
 
         /// <summary>
-        /// Seek field with the given ID in the current object.
-        /// </summary>
-        /// <param name="fieldId">Field ID.</param>
-        /// <returns>True in case the field was found and position adjusted, false otherwise.</returns>
-        private bool SeekField(int fieldId)
-        {
-            Stream.Seek(_curFooterStart, SeekOrigin.Begin);
-
-            while (Stream.Position < _curFooterEnd)
-            {
-                var id = Stream.ReadInt();
-
-                if (id == fieldId)
-                {
-                    var fieldOffset = Stream.ReadInt();
-
-                    Stream.Seek(_curPos + fieldOffset, SeekOrigin.Begin);
-                    return true;
-                }
-
-                Stream.Seek(4, SeekOrigin.Current);
-            }
-
-            return false;
-        }
-
-        /// <summary>
         /// Determines whether header at current position is HDR_NULL.
         /// </summary>
         private bool IsNotNullHeader(byte expHdr)
@@ -899,23 +858,43 @@ namespace Apache.Ignite.Core.Impl.Portable
         /// </summary>
         private bool SeekField(string fieldName, byte expHdr)
         {
+            if (!SeekField(fieldName)) 
+                return false;
+
+            // Expected read order, no need to seek.
+            return IsNotNullHeader(expHdr);
+        }
+
+        /// <summary>
+        /// Seeks the field by name.
+        /// </summary>
+        private bool SeekField(string fieldName)
+        {
             if (_curRaw)
                 throw new PortableException("Cannot read named fields after raw data is read.");
 
+            if (_curHdr.IsRawOnly)
+                return false;
+
             var actionId = _curStruct.CurStructAction;
 
             var fieldId = _curStruct.GetFieldId(fieldName);
 
             if (_curSchema == null || actionId >= _curSchema.Length || fieldId != _curSchema[actionId])
             {
-                _curSchema = null;   // read order is different, ignore schema for future reads
+                _curSchema = null; // read order is different, ignore schema for future reads
+
+                _curSchemaMap = _curSchemaMap ?? _curHdr.ReadSchemaAsDictionary(Stream, _curPos);
+
+                int pos;
 
-                if (!SeekField(fieldId))
+                if (!_curSchemaMap.TryGetValue(fieldId, out pos))
                     return false;
+
+                Stream.Seek(pos, SeekOrigin.Begin);
             }
 
-            // Expected read order, no need to seek.
-            return IsNotNullHeader(expHdr);
+            return true;
         }
 
         /// <summary>

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableUtils.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableUtils.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableUtils.cs
index a0657b2..79c4858 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableUtils.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableUtils.cs
@@ -1804,7 +1804,7 @@ namespace Apache.Ignite.Core.Impl.Portable
         /// <summary>
         /// Struct with .Net-style Guid memory layout.
         /// </summary>
-        [StructLayout(LayoutKind.Sequential)]
+        [StructLayout(LayoutKind.Sequential, Pack = 0)]
         private struct GuidAccessor
         {
             public readonly ulong ABC;
@@ -1828,7 +1828,7 @@ namespace Apache.Ignite.Core.Impl.Portable
         /// <summary>
         /// Struct with Java-style Guid memory layout.
         /// </summary>
-        [StructLayout(LayoutKind.Sequential)]
+        [StructLayout(LayoutKind.Sequential, Pack = 0)]
         private struct JavaGuid
         {
             public readonly ulong CBA;

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableWriterImpl.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableWriterImpl.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableWriterImpl.cs
index e17449d..66caca3 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableWriterImpl.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortableWriterImpl.cs
@@ -73,7 +73,6 @@ namespace Apache.Ignite.Core.Impl.Portable
         /** Current schema. */
         private ResizeableArray<PortableObjectSchemaField> _curSchema;
 
-
         /// <summary>
         /// Gets the marshaller.
         /// </summary>
@@ -1092,9 +1091,11 @@ namespace Apache.Ignite.Core.Impl.Portable
                 // Write schema
                 var hasSchema = _curSchema != null;
                 var schemaOffset = hasSchema ? _stream.Position - pos : PortableObjectHeader.Size;
+                short flags = 0;
 
                 if (hasSchema)
-                    PortableObjectSchemaField.WriteArray(_curSchema.Array, _stream, _curSchema.Count);
+                    flags = PortableObjectHeader.WriteSchema(_curSchema.Array, _stream, _curSchema.Count,
+                        _curSchema.Array[_curSchema.Count - 1].Offset);
 
                 // Calculate and write header.
                 if (hasSchema && _curRawPos > 0)
@@ -1103,7 +1104,7 @@ namespace Apache.Ignite.Core.Impl.Portable
                 var len = _stream.Position - pos;
 
                 var header = new PortableObjectHeader(desc.UserType, desc.TypeId, obj.GetHashCode(), len,
-                    PU.GetSchemaId(_curSchema), schemaOffset, !hasSchema);
+                    PU.GetSchemaId(_curSchema), schemaOffset, !hasSchema, flags);
 
                 PortableObjectHeader.Write(header, _stream, pos);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortablesImpl.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortablesImpl.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortablesImpl.cs
index f48f120..e72ffac 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortablesImpl.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Portable/PortablesImpl.cs
@@ -166,7 +166,7 @@ namespace Apache.Ignite.Core.Impl.Portable
         {
             var len = PortableObjectHeader.Size;
 
-            var hdr = new PortableObjectHeader(desc.UserType, desc.TypeId, 0, len, 0, len, true);
+            var hdr = new PortableObjectHeader(desc.UserType, desc.TypeId, 0, len, 0, len, true, 0);
 
             var stream = new PortableHeapStream(len);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs
index 07cf309..8147e9d 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs
@@ -22,7 +22,7 @@ namespace Apache.Ignite.Core.Impl.Unmanaged
     /// <summary>
     /// Unmanaged callback handler function pointers.
     /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
+    [StructLayout(LayoutKind.Sequential, Pack = 0)]
     internal unsafe struct UnmanagedCallbackHandlers
     {
         internal void* target;


[4/5] ignite git commit: Merge branch ignite-1282 into ignite-950-new

Posted by ag...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/c050b4ce/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryReaderExImpl.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryReaderExImpl.java
index 2c3fd91,0000000..82bb2f8
mode 100644,000000..100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryReaderExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryReaderExImpl.java
@@@ -1,2765 -1,0 +1,2774 @@@
 +/*
 + * 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.portable;
 +
 +import java.io.ByteArrayInputStream;
 +import java.io.EOFException;
 +import java.io.IOException;
 +import java.io.ObjectInput;
 +import java.lang.reflect.Array;
 +import java.lang.reflect.Constructor;
 +import java.lang.reflect.InvocationTargetException;
 +import java.math.BigDecimal;
 +import java.math.BigInteger;
 +import java.sql.Timestamp;
 +import java.util.ArrayList;
 +import java.util.Collection;
 +import java.util.Date;
 +import java.util.LinkedHashMap;
 +import java.util.LinkedList;
 +import java.util.Map;
 +import java.util.Properties;
 +import java.util.TreeMap;
 +import java.util.TreeSet;
 +import java.util.UUID;
 +import java.util.concurrent.ConcurrentHashMap;
 +import java.util.concurrent.ConcurrentSkipListSet;
 +import org.apache.ignite.IgniteCheckedException;
 +import org.apache.ignite.binary.BinaryObject;
 +import org.apache.ignite.binary.BinaryObjectException;
 +import org.apache.ignite.binary.BinaryTypeIdMapper;
 +import org.apache.ignite.binary.BinaryInvalidTypeException;
 +import org.apache.ignite.binary.BinaryRawReader;
 +import org.apache.ignite.binary.BinaryReader;
 +import org.apache.ignite.internal.portable.streams.PortableHeapInputStream;
 +import org.apache.ignite.internal.portable.streams.PortableInputStream;
 +import org.apache.ignite.internal.util.GridEnumCache;
 +import org.apache.ignite.internal.util.lang.GridMapEntry;
 +import org.apache.ignite.internal.util.typedef.internal.SB;
 +import org.apache.ignite.internal.util.typedef.internal.U;
 +import org.apache.ignite.lang.IgniteBiTuple;
 +import org.jetbrains.annotations.NotNull;
 +import org.jetbrains.annotations.Nullable;
 +
 +import static java.nio.charset.StandardCharsets.UTF_8;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.ARR_LIST;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BOOLEAN;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BOOLEAN_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BYTE;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BYTE_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.CHAR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.CHAR_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.CLASS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.COL;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.CONC_HASH_MAP;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.CONC_SKIP_LIST_SET;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DATE;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DATE_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DECIMAL;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DECIMAL_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DFLT_HDR_LEN;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DOUBLE;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DOUBLE_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.ENUM;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.ENUM_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLOAT;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLOAT_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.HANDLE;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.HASH_MAP;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.HASH_SET;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.INT;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.INT_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.LINKED_HASH_MAP;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.LINKED_HASH_SET;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.LINKED_LIST;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.LONG;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.LONG_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.MAP;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.MAP_ENTRY;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.NULL;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.OBJ;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.OBJECT_TYPE_ID;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.OBJ_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.OPTM_MARSH;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.PORTABLE_OBJ;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.PROPERTIES_MAP;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.SHORT;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.SHORT_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.STRING;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.STRING_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.TIMESTAMP;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.TIMESTAMP_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.TREE_MAP;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.TREE_SET;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.UNREGISTERED_TYPE_ID;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.USER_COL;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.USER_SET;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.UUID;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.UUID_ARR;
 +
 +/**
 + * Portable reader implementation.
 + */
 +@SuppressWarnings("unchecked")
 +public class BinaryReaderExImpl implements BinaryReader, BinaryRawReaderEx, ObjectInput {
 +    /** Length of a single field descriptor. */
 +    private static final int FIELD_DESC_LEN = 16;
 +
 +    /** */
 +    private final PortableContext ctx;
 +
 +    /** */
 +    private final PortableInputStream in;
 +
 +    /** */
 +    private final int start;
 +
 +    /** */
 +    private final PortableReaderContext rCtx;
 +
 +    /** */
 +    private final ClassLoader ldr;
 +
 +    /** */
 +    private PortableClassDescriptor desc;
 +
 +    /** Flag indicating that object header was parsed. */
 +    private boolean hdrParsed;
 +
 +    /** Type ID. */
 +    private int typeId;
 +
 +    /** Raw offset. */
 +    private int rawOff;
 +
 +    /** */
 +    private int hdrLen;
 +
 +    /** Footer start. */
 +    private int footerStart;
 +
 +    /** Footer end. */
 +    private int footerLen;
 +
 +    /** ID mapper. */
 +    private BinaryTypeIdMapper idMapper;
 +
 +    /** Schema Id. */
 +    private int schemaId;
 +
++    /** Offset size in bytes. */
++    private int offsetSize;
++
 +    /** Object schema. */
 +    private PortableSchema schema;
 +
 +    /**
 +     * @param ctx Context.
 +     * @param arr Array.
 +     * @param start Start.
 +     * @param ldr Class loader.
 +     */
 +    public BinaryReaderExImpl(PortableContext ctx, byte[] arr, int start, ClassLoader ldr) {
 +        this(ctx, new PortableHeapInputStream(arr), start, ldr, new PortableReaderContext());
 +    }
 +
 +    /**
 +     * @param ctx Context.
 +     * @param in Input stream.
 +     * @param start Start.
 +     */
 +    BinaryReaderExImpl(PortableContext ctx, PortableInputStream in, int start, ClassLoader ldr) {
 +        this(ctx, in, start, ldr, new PortableReaderContext());
 +    }
 +
 +    /**
 +     * @param ctx Context.
 +     * @param in Input stream.
 +     * @param start Start.
 +     * @param rCtx Context.
 +     */
 +    BinaryReaderExImpl(PortableContext ctx, PortableInputStream in, int start, ClassLoader ldr,
 +        PortableReaderContext rCtx) {
 +        this.ctx = ctx;
 +        this.in = in;
 +        this.start = start;
 +        this.ldr = ldr;
 +        this.rCtx = rCtx;
 +
 +        in.position(start);
 +    }
 +
 +    /**
 +     * Preloads typeId from the input array.
 +     */
 +    private void parseHeaderIfNeeded() {
 +        if (hdrParsed)
 +            return;
 +
 +        int retPos = in.position();
 +
 +        in.position(start);
 +
 +        byte hdr = in.readByte();
 +
 +        if (hdr != GridPortableMarshaller.OBJ)
 +            throw new BinaryObjectException("Invalid header [pos=" + retPos + "expected=" + GridPortableMarshaller.OBJ +
 +                ", actual=" + hdr + ']');
 +
 +        PortableUtils.checkProtocolVersion(in.readByte());
 +
-         in.position(in.position() + 2); // Skip flags.
++        short flags = in.readShort();
++
++        offsetSize = PortableUtils.fieldOffsetSize(flags);
 +
 +        typeId = in.readIntPositioned(start + GridPortableMarshaller.TYPE_ID_POS);
 +
-         IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(in, start);
++        IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(in, start, offsetSize);
 +
 +        footerStart = footer.get1();
 +        footerLen = footer.get2() - footerStart;
 +
 +        schemaId = in.readIntPositioned(start + GridPortableMarshaller.SCHEMA_ID_POS);
 +
-         rawOff = PortableUtils.rawOffsetAbsolute(in, start);
++        rawOff = PortableUtils.rawOffsetAbsolute(in, start, offsetSize);
 +
 +        if (typeId == UNREGISTERED_TYPE_ID) {
 +            // Skip to the class name position.
 +            in.position(start + GridPortableMarshaller.DFLT_HDR_LEN);
 +
 +            int off = in.position();
 +
 +            Class cls = doReadClass(typeId);
 +
 +            // registers class by typeId, at least locally if the cache is not ready yet.
 +            PortableClassDescriptor desc = ctx.descriptorForClass(cls);
 +
 +            typeId = desc.typeId();
 +
 +            int clsNameLen = in.position() - off;
 +
 +            hdrLen = DFLT_HDR_LEN + clsNameLen;
 +        }
 +        else
 +            hdrLen = DFLT_HDR_LEN;
 +
 +        // Restore state.
 +        in.position(retPos);
 +
 +        hdrParsed = true;
 +    }
 +
 +    /**
 +     * @return Descriptor.
 +     */
 +    PortableClassDescriptor descriptor() {
 +        return desc;
 +    }
 +
 +    /**
 +     * @return Unmarshalled value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Object unmarshal() throws BinaryObjectException {
 +        return unmarshal(false);
 +    }
 +
 +    /**
 +     * @param offset Offset in the array.
 +     * @return Unmarshalled value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    public Object unmarshal(int offset) throws BinaryObjectException {
 +        in.position(offset);
 +
 +        return in.position() >= 0 ? unmarshal() : null;
 +    }
 +
 +    /**
 +     * @param fieldName Field name.
 +     * @return Unmarshalled value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Object unmarshalField(String fieldName) throws BinaryObjectException {
 +        return hasField(fieldName) ? unmarshal() : null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Unmarshalled value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Object unmarshalField(int fieldId) throws BinaryObjectException {
 +        parseHeaderIfNeeded();
 +
 +        return hasField(fieldId) ? unmarshal() : null;
 +    }
 +
 +    /**
-      * @param fieldOffset Field offset.
-      * @return Unmarshalled value.
-      * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
++     * Unmarshal field by absolute position.
++     *
++     * @param pos Absolute position.
++     * @return Field value.
++     * @throws BinaryObjectException In case of error.
 +     */
-     @Nullable Object unmarshalFieldByOffset(int fieldOffset) throws BinaryObjectException {
-         assert fieldOffset != 0;
- 
++    @Nullable Object unmarshalFieldByAbsolutePosition(int pos) throws BinaryObjectException {
 +        parseHeaderIfNeeded();
 +
-         in.position(start + in.readIntPositioned(footerStart + fieldOffset));
++        in.position(pos);
 +
 +        return unmarshal();
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Byte readByte(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(BYTE) == Flag.NULL)
 +                return null;
 +
 +            return in.readByte();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Short readShort(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(SHORT) == Flag.NULL)
 +                return null;
 +
 +            return in.readShort();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Integer readInt(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(INT) == Flag.NULL)
 +                return null;
 +
 +            return in.readInt();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Long readLong(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(LONG) == Flag.NULL)
 +                return null;
 +
 +            return in.readLong();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Float readFloat(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(FLOAT) == Flag.NULL)
 +                return null;
 +
 +            return in.readFloat();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Double readDouble(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(DOUBLE) == Flag.NULL)
 +                return null;
 +
 +            return in.readDouble();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Character readChar(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(CHAR) == Flag.NULL)
 +                return null;
 +
 +            return in.readChar();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Boolean readBoolean(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(BOOLEAN) == Flag.NULL)
 +                return null;
 +
 +            return in.readBoolean();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable BigDecimal readDecimal(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(DECIMAL) == Flag.NULL)
 +                return null;
 +
 +            return doReadDecimal();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable String readString(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(STRING) == Flag.NULL)
 +                return null;
 +
 +            return doReadString();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable UUID readUuid(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(UUID) == Flag.NULL)
 +                return null;
 +
 +            return doReadUuid();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Date readDate(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(DATE) == Flag.NULL)
 +                return null;
 +
 +            return doReadDate();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Timestamp readTimestamp(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(TIMESTAMP) == Flag.NULL)
 +                return null;
 +
 +            return doReadTimestamp();
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Object readObject(int fieldId) throws BinaryObjectException {
 +        return hasField(fieldId) ? doReadObject() : null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable byte[] readByteArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(BYTE_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadByteArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable short[] readShortArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(SHORT_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadShortArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable int[] readIntArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(INT_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadIntArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable long[] readLongArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(LONG_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadLongArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable float[] readFloatArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(FLOAT_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadFloatArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable double[] readDoubleArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(DOUBLE_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadDoubleArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable char[] readCharArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(CHAR_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadCharArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable boolean[] readBooleanArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(BOOLEAN_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadBooleanArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable BigDecimal[] readDecimalArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(DECIMAL_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadDecimalArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable String[] readStringArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(STRING_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadStringArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable UUID[] readUuidArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(UUID_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadUuidArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Date[] readDateArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(DATE_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadDateArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Timestamp[] readTimestampArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(TIMESTAMP_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadTimestampArray();
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Object[] readObjectArray(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(OBJ_ARR);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadObjectArray(true);
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @param cls Collection class.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable <T> Collection<T> readCollection(int fieldId, @Nullable Class<? extends Collection> cls)
 +        throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(COL);
 +
 +            if (flag == Flag.NORMAL)
 +                return (Collection<T>)doReadCollection(true, cls);
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @param cls Map class.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Map<?, ?> readMap(int fieldId, @Nullable Class<? extends Map> cls)
 +        throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(MAP);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadMap(true, cls);
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException On case of error.
 +     */
 +    @Nullable Map.Entry<?, ?> readMapEntry(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(MAP_ENTRY);
 +
 +            if (flag == Flag.NORMAL)
 +                return doReadMapEntry(true);
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Portable object.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable BinaryObject readPortableObject(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(PORTABLE_OBJ) == Flag.NULL)
 +                return null;
 +
 +            return new BinaryObjectImpl(ctx, doReadByteArray(), in.readInt());
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @param cls Class.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Enum<?> readEnum(int fieldId, @Nullable Class<?> cls) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(ENUM) == Flag.NULL)
 +                return null;
 +
 +            // Revisit: why have we started writing Class for enums in their serialized form?
 +            if (cls == null)
 +                cls = doReadClass();
 +            else
 +                doReadClass();
 +
 +            Object[] vals = GridEnumCache.get(cls);
 +
 +            return (Enum<?>)vals[in.readInt()];
 +        }
 +        else
 +            return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @param cls Class.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Object[] readEnumArray(int fieldId, @Nullable Class<?> cls) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            Flag flag = checkFlag(ENUM_ARR);
 +
 +            if (flag == Flag.NORMAL) {
 +                if (cls == null)
 +                    cls = doReadClass();
 +                else
 +                    doReadClass();
 +
 +                return doReadEnumArray(cls);
 +            }
 +            else if (flag == Flag.HANDLE)
 +                return readHandleField();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return Field class.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable Class<?> readClass(int fieldId) throws BinaryObjectException {
 +        if (hasField(fieldId)) {
 +            if (checkFlag(CLASS) == Flag.NULL)
 +                return null;
 +
 +            return doReadClass();
 +        }
 +
 +        return null;
 +    }
 +
 +    /**
 +     * @param obj Object.
 +     */
 +    void setHandler(Object obj) {
 +        rCtx.setObjectHandler(start, obj);
 +    }
 +
 +    /**
 +     * @param obj Object.
 +     * @param pos Position.
 +     */
 +    void setHandler(Object obj, int pos) {
 +        rCtx.setObjectHandler(pos, obj);
 +    }
 +
 +    /**
 +     * Recreating field value from a handle.
 +     *
 +     * @param <T> Field type.
 +     * @return Field.
 +     */
 +    private <T> T readHandleField() {
 +        int handle = (in.position() - 1) - in.readInt();
 +
 +        Object obj = rCtx.getObjectByHandle(handle);
 +
 +        if (obj == null) {
 +            in.position(handle);
 +
 +            obj = doReadObject();
 +        }
 +
 +        return (T)obj;
 +    }
 +    /** {@inheritDoc} */
 +    @Override public byte readByte(String fieldName) throws BinaryObjectException {
 +        Byte val = readByte(fieldId(fieldName));
 +
 +        return val != null ? val : 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte readByte() throws BinaryObjectException {
 +        return in.readByte();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public short readShort(String fieldName) throws BinaryObjectException {
 +        Short val = readShort(fieldId(fieldName));
 +
 +        return val != null ? val : 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public short readShort() throws BinaryObjectException {
 +        return in.readShort();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int readInt(String fieldName) throws BinaryObjectException {
 +        Integer val = readInt(fieldId(fieldName));
 +
 +        return val != null ? val : 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int readInt() throws BinaryObjectException {
 +        return in.readInt();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public long readLong(String fieldName) throws BinaryObjectException {
 +        Long val = readLong(fieldId(fieldName));
 +
 +        return val != null ? val : 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public long readLong() throws BinaryObjectException {
 +        return in.readLong();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public float readFloat(String fieldName) throws BinaryObjectException {
 +        Float val = readFloat(fieldId(fieldName));
 +
 +        return val != null ? val : 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public float readFloat() throws BinaryObjectException {
 +        return in.readFloat();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public double readDouble(String fieldName) throws BinaryObjectException {
 +        Double val = readDouble(fieldId(fieldName));
 +
 +        return val != null ? val : 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public double readDouble() throws BinaryObjectException {
 +        return in.readDouble();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public char readChar(String fieldName) throws BinaryObjectException {
 +        Character val = readChar(fieldId(fieldName));
 +
 +        return val != null ? val : 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public char readChar() throws BinaryObjectException {
 +        return in.readChar();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean readBoolean(String fieldName) throws BinaryObjectException {
 +        Boolean val = readBoolean(fieldId(fieldName));
 +
 +        return val != null ? val : false;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean readBoolean() throws BinaryObjectException {
 +        return in.readBoolean();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override @Nullable public BigDecimal readDecimal(String fieldName) throws BinaryObjectException {
 +        return readDecimal(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override @Nullable public BigDecimal readDecimal() throws BinaryObjectException {
 +        if (checkFlag(DECIMAL) == Flag.NULL)
 +            return null;
 +
 +        return doReadDecimal();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public String readString(String fieldName) throws BinaryObjectException {
 +        return readString(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public String readString() throws BinaryObjectException {
 +        if (checkFlag(STRING) == Flag.NULL)
 +            return null;
 +
 +        return doReadString();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public UUID readUuid(String fieldName) throws BinaryObjectException {
 +        return readUuid(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public UUID readUuid() throws BinaryObjectException {
 +        if (checkFlag(UUID) == Flag.NULL)
 +            return null;
 +
 +        return doReadUuid();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Date readDate(String fieldName) throws BinaryObjectException {
 +        return readDate(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Date readDate() throws BinaryObjectException {
 +        if (checkFlag(DATE) == Flag.NULL)
 +            return null;
 +
 +        return doReadDate();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Timestamp readTimestamp(String fieldName) throws BinaryObjectException {
 +        return readTimestamp(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Timestamp readTimestamp() throws BinaryObjectException {
 +        if (checkFlag(TIMESTAMP) == Flag.NULL)
 +            return null;
 +
 +        return doReadTimestamp();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override public <T> T readObject(String fieldName) throws BinaryObjectException {
 +        return (T)readObject(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public Object readObject() throws BinaryObjectException {
 +        return doReadObject();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Object readObjectDetached() throws BinaryObjectException {
 +        return unmarshal(true);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public byte[] readByteArray(String fieldName) throws BinaryObjectException {
 +        return readByteArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public byte[] readByteArray() throws BinaryObjectException {
 +        if (checkFlag(BYTE_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadByteArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public short[] readShortArray(String fieldName) throws BinaryObjectException {
 +        return readShortArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public short[] readShortArray() throws BinaryObjectException {
 +        if (checkFlag(SHORT_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadShortArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public int[] readIntArray(String fieldName) throws BinaryObjectException {
 +        return readIntArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public int[] readIntArray() throws BinaryObjectException {
 +        if (checkFlag(INT_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadIntArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public long[] readLongArray(String fieldName) throws BinaryObjectException {
 +        return readLongArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public long[] readLongArray() throws BinaryObjectException {
 +        if (checkFlag(LONG_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadLongArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public float[] readFloatArray(String fieldName) throws BinaryObjectException {
 +        return readFloatArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public float[] readFloatArray() throws BinaryObjectException {
 +        if (checkFlag(FLOAT_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadFloatArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public double[] readDoubleArray(String fieldName) throws BinaryObjectException {
 +        return readDoubleArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public double[] readDoubleArray() throws BinaryObjectException {
 +        if (checkFlag(DOUBLE_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadDoubleArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public char[] readCharArray(String fieldName) throws BinaryObjectException {
 +        return readCharArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public char[] readCharArray() throws BinaryObjectException {
 +        if (checkFlag(CHAR_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadCharArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public boolean[] readBooleanArray(String fieldName) throws BinaryObjectException {
 +        return readBooleanArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public boolean[] readBooleanArray() throws BinaryObjectException {
 +        if (checkFlag(BOOLEAN_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadBooleanArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override @Nullable public BigDecimal[] readDecimalArray(String fieldName) throws BinaryObjectException {
 +        return readDecimalArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override @Nullable public BigDecimal[] readDecimalArray() throws BinaryObjectException {
 +        if (checkFlag(DECIMAL_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadDecimalArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public String[] readStringArray(String fieldName) throws BinaryObjectException {
 +        return readStringArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public String[] readStringArray() throws BinaryObjectException {
 +        if (checkFlag(STRING_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadStringArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public UUID[] readUuidArray(String fieldName) throws BinaryObjectException {
 +        return readUuidArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public UUID[] readUuidArray() throws BinaryObjectException {
 +        if (checkFlag(UUID_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadUuidArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Date[] readDateArray(String fieldName) throws BinaryObjectException {
 +        return readDateArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Timestamp[] readTimestampArray(String fieldName) throws BinaryObjectException {
 +        return readTimestampArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Date[] readDateArray() throws BinaryObjectException {
 +        if (checkFlag(DATE_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadDateArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Timestamp[] readTimestampArray() throws BinaryObjectException {
 +        if (checkFlag(TIMESTAMP_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadTimestampArray();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Object[] readObjectArray(String fieldName) throws BinaryObjectException {
 +        return readObjectArray(fieldId(fieldName));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public Object[] readObjectArray() throws BinaryObjectException {
 +        if (checkFlag(OBJ_ARR) == Flag.NULL)
 +            return null;
 +
 +        return doReadObjectArray(true);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <T> Collection<T> readCollection(String fieldName) throws BinaryObjectException {
 +        return readCollection(fieldId(fieldName), null);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <T> Collection<T> readCollection() throws BinaryObjectException {
 +        if (checkFlag(COL) == Flag.NULL)
 +            return null;
 +
 +        return (Collection<T>)doReadCollection(true, null);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <T> Collection<T> readCollection(String fieldName,
 +        Class<? extends Collection<T>> colCls) throws BinaryObjectException {
 +        return readCollection(fieldId(fieldName), colCls);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <T> Collection<T> readCollection(Class<? extends Collection<T>> colCls)
 +        throws BinaryObjectException {
 +        if (checkFlag(COL) == Flag.NULL)
 +            return null;
 +
 +        return (Collection<T>)doReadCollection(true, colCls);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <K, V> Map<K, V> readMap(String fieldName) throws BinaryObjectException {
 +        return (Map<K, V>)readMap(fieldId(fieldName), null);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <K, V> Map<K, V> readMap() throws BinaryObjectException {
 +        if (checkFlag(MAP) == Flag.NULL)
 +            return null;
 +
 +        return (Map<K, V>)doReadMap(true, null);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <K, V> Map<K, V> readMap(String fieldName, Class<? extends Map<K, V>> mapCls)
 +        throws BinaryObjectException {
 +        return (Map<K, V>)readMap(fieldId(fieldName), mapCls);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <K, V> Map<K, V> readMap(Class<? extends Map<K, V>> mapCls)
 +        throws BinaryObjectException {
 +        if (checkFlag(MAP) == Flag.NULL)
 +            return null;
 +
 +        return (Map<K, V>)doReadMap(true, mapCls);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <T extends Enum<?>> T readEnum(String fieldName)
 +        throws BinaryObjectException {
 +        return (T)readEnum(fieldId(fieldName), null);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <T extends Enum<?>> T readEnum() throws BinaryObjectException {
 +        if (checkFlag(ENUM) == Flag.NULL)
 +            return null;
 +
 +        Class cls = doReadClass();
 +
 +        return (T)doReadEnum(cls);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <T extends Enum<?>> T[] readEnumArray(String fieldName)
 +        throws BinaryObjectException {
 +        return (T[])readEnumArray(fieldId(fieldName), null);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public <T extends Enum<?>> T[] readEnumArray() throws BinaryObjectException {
 +        if (checkFlag(ENUM_ARR) == Flag.NULL)
 +            return null;
 +
 +        Class cls = doReadClass();
 +
 +        return (T[])doReadEnumArray(cls);
 +    }
 +
 +    /**
 +     * Ensure that type flag is either null or contains expected value.
 +     *
 +     * @param expFlag Expected value.
 +     * @return Flag.
 +     * @throws org.apache.ignite.binary.BinaryObjectException If flag is neither null, nor expected.
 +     */
 +    private Flag checkFlag(byte expFlag) {
 +        byte flag = in.readByte();
 +
 +        if (flag == NULL)
 +            return Flag.NULL;
 +        else if (flag == HANDLE)
 +            return Flag.HANDLE;
 +        else if (flag != expFlag) {
 +            int pos = in.position() - 1;
 +
 +            throw new BinaryObjectException("Unexpected flag value [pos=" + pos + ", expected=" + expFlag +
 +                ", actual=" + flag + ']');
 +        }
 +
 +        return Flag.NORMAL;
 +    }
 +
 +    /**
 +     * @param fieldName Field name.
 +     * @return {@code True} if field is set.
 +     */
 +    public boolean hasField(String fieldName) {
 +        return hasField(fieldId(fieldName));
 +    }
 +
 +    /**
 +     * @param fieldId Field ID.
 +     * @return {@code True} if field is set.
 +     */
 +    private boolean hasField(int fieldId) {
 +        return fieldOffset(fieldId) != 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryRawReader rawReader() {
 +        in.position(rawOff);
 +
 +        return this;
 +    }
 +
 +    /**
 +     * @return Unmarshalled value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable private Object unmarshal(boolean detach) throws BinaryObjectException {
 +        int start = in.position();
 +
 +        byte flag = in.readByte();
 +
 +        switch (flag) {
 +            case NULL:
 +                return null;
 +
 +            case HANDLE:
 +                int handle = start - in.readInt();
 +
 +                BinaryObject handledPo = rCtx.getPortableByHandle(handle);
 +
 +                if (handledPo != null)
 +                    return handledPo;
 +
 +                in.position(handle);
 +
 +                return unmarshal();
 +
 +            case OBJ:
 +                PortableUtils.checkProtocolVersion(in.readByte());
 +
 +                BinaryObjectEx po;
 +
 +                if (detach) {
 +                    in.position(start + GridPortableMarshaller.TOTAL_LEN_POS);
 +
 +                    int len = in.readInt();
 +
 +                    in.position(start);
 +
 +                    po = new BinaryObjectImpl(ctx, in.readByteArray(len), 0);
 +                }
 +                else
 +                    po = in.offheapPointer() > 0
 +                        ? new BinaryObjectOffheapImpl(ctx, in.offheapPointer(), start,
 +                        in.remaining() + in.position())
 +                        : new BinaryObjectImpl(ctx, in.array(), start);
 +
 +                rCtx.setPortableHandler(start, po);
 +
 +                in.position(start + po.length());
 +
 +                return po;
 +
 +            case BYTE:
 +                return in.readByte();
 +
 +            case SHORT:
 +                return in.readShort();
 +
 +            case INT:
 +                return in.readInt();
 +
 +            case LONG:
 +                return in.readLong();
 +
 +            case FLOAT:
 +                return in.readFloat();
 +
 +            case DOUBLE:
 +                return in.readDouble();
 +
 +            case CHAR:
 +                return in.readChar();
 +
 +            case BOOLEAN:
 +                return in.readBoolean();
 +
 +            case DECIMAL:
 +                return doReadDecimal();
 +
 +            case STRING:
 +                return doReadString();
 +
 +            case UUID:
 +                return doReadUuid();
 +
 +            case DATE:
 +                return doReadDate();
 +
 +            case TIMESTAMP:
 +                return doReadTimestamp();
 +
 +            case BYTE_ARR:
 +                return doReadByteArray();
 +
 +            case SHORT_ARR:
 +                return doReadShortArray();
 +
 +            case INT_ARR:
 +                return doReadIntArray();
 +
 +            case LONG_ARR:
 +                return doReadLongArray();
 +
 +            case FLOAT_ARR:
 +                return doReadFloatArray();
 +
 +            case DOUBLE_ARR:
 +                return doReadDoubleArray();
 +
 +            case CHAR_ARR:
 +                return doReadCharArray();
 +
 +            case BOOLEAN_ARR:
 +                return doReadBooleanArray();
 +
 +            case DECIMAL_ARR:
 +                return doReadDecimalArray();
 +
 +            case STRING_ARR:
 +                return doReadStringArray();
 +
 +            case UUID_ARR:
 +                return doReadUuidArray();
 +
 +            case DATE_ARR:
 +                return doReadDateArray();
 +
 +            case TIMESTAMP_ARR:
 +                return doReadTimestampArray();
 +
 +            case OBJ_ARR:
 +                return doReadObjectArray(false);
 +
 +            case COL:
 +                return doReadCollection(false, null);
 +
 +            case MAP:
 +                return doReadMap(false, null);
 +
 +            case MAP_ENTRY:
 +                return doReadMapEntry(false);
 +
 +            case PORTABLE_OBJ:
 +                return doReadPortableObject();
 +
 +            case ENUM:
 +                return doReadEnum(doReadClass());
 +
 +            case ENUM_ARR:
 +                return doReadEnumArray(doReadClass());
 +
 +            case CLASS:
 +                return in.readInt();
 +
 +            case OPTM_MARSH:
 +                int len = in.readInt();
 +
 +                ByteArrayInputStream input = new ByteArrayInputStream(in.array(), in.position(), len);
 +
 +                Object obj;
 +
 +                try {
 +                    obj = ctx.optimizedMarsh().unmarshal(input, null);
 +                }
 +                catch (IgniteCheckedException e) {
 +                    throw new BinaryObjectException("Failed to unmarshal object with optmMarsh marshaller", e);
 +                }
 +
 +                return obj;
 +
 +            default:
 +                throw new BinaryObjectException("Invalid flag value: " + flag);
 +        }
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private BigDecimal doReadDecimal() {
 +        int scale = in.readInt();
 +        byte[] mag = doReadByteArray();
 +
 +        BigInteger intVal = new BigInteger(mag);
 +
 +        if (scale < 0) {
 +            scale &= 0x7FFFFFFF;
 +
 +            intVal = intVal.negate();
 +        }
 +
 +        return new BigDecimal(intVal, scale);
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private String doReadString() {
 +        if (in.readBoolean()) {
 +            if (!in.hasArray())
 +                return new String(doReadByteArray(), UTF_8);
 +
 +            int strLen = in.readInt();
 +            int strOff = in.position();
 +
 +            String res = new String(in.array(), strOff, strLen, UTF_8);
 +
 +            in.position(in.position() + strLen);
 +
 +            return res;
 +        }
 +        else
 +            return String.valueOf(doReadCharArray());
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private UUID doReadUuid() {
 +        return new UUID(in.readLong(), in.readLong());
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private Date doReadDate() {
 +        long time = in.readLong();
 +
 +        return new Date(time);
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private Timestamp doReadTimestamp() {
 +        long time = in.readLong();
 +        int nanos = in.readInt();
 +
 +        Timestamp ts = new Timestamp(time);
 +
 +        ts.setNanos(ts.getNanos() + nanos);
 +
 +        return ts;
 +    }
 +
 +    /**
 +     * @return Object.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @Nullable private Object doReadObject() throws BinaryObjectException {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx, in, in.position(), ldr, rCtx);
 +
 +        return reader.deserialize();
 +    }
 +
 +    /**
 +     * @return Deserialized object.
 +     * @throws org.apache.ignite.binary.BinaryObjectException If failed.
 +     */
 +    @Nullable Object deserialize() throws BinaryObjectException {
 +        Object obj;
 +
 +        byte flag = in.readByte();
 +
 +        switch (flag) {
 +            case NULL:
 +                obj = null;
 +
 +                break;
 +
 +            case HANDLE:
 +                int handle = start - in.readInt();
 +
 +                obj = rCtx.getObjectByHandle(handle);
 +
 +                if (obj == null) {
 +                    int retPos = in.position();
 +
 +                    in.position(handle);
 +
 +                    obj = doReadObject();
 +
 +                    in.position(retPos);
 +                }
 +
 +                break;
 +
 +            case OBJ:
 +                parseHeaderIfNeeded();
 +
 +                assert typeId != UNREGISTERED_TYPE_ID;
 +
 +                PortableUtils.checkProtocolVersion(in.readByte());
 +
 +                boolean userType = PortableUtils.isUserType(this.readShort());
 +
 +                // Skip typeId and hash code.
 +                in.position(in.position() + 8);
 +
 +                desc = ctx.descriptorForTypeId(userType, typeId, ldr);
 +
 +                int len = in.readInt();
 +
 +                in.position(start + hdrLen);
 +
 +                if (desc == null)
 +                    throw new BinaryInvalidTypeException("Unknown type ID: " + typeId);
 +
 +                obj = desc.read(this);
 +
 +                in.position(start + len);
 +
 +                break;
 +
 +            case BYTE:
 +                obj = in.readByte();
 +
 +                break;
 +
 +            case SHORT:
 +                obj = in.readShort();
 +
 +                break;
 +
 +            case INT:
 +                obj = in.readInt();
 +
 +                break;
 +
 +            case LONG:
 +                obj = in.readLong();
 +
 +                break;
 +
 +            case FLOAT:
 +                obj = in.readFloat();
 +
 +                break;
 +
 +            case DOUBLE:
 +                obj = in.readDouble();
 +
 +                break;
 +
 +            case CHAR:
 +                obj = in.readChar();
 +
 +                break;
 +
 +            case BOOLEAN:
 +                obj = in.readBoolean();
 +
 +                break;
 +
 +            case DECIMAL:
 +                obj = doReadDecimal();
 +
 +                break;
 +
 +            case STRING:
 +                obj = doReadString();
 +
 +                break;
 +
 +            case UUID:
 +                obj = doReadUuid();
 +
 +                break;
 +
 +            case DATE:
 +                obj = doReadDate();
 +
 +                break;
 +
 +            case TIMESTAMP:
 +                obj = doReadTimestamp();
 +
 +                break;
 +
 +            case BYTE_ARR:
 +                obj = doReadByteArray();
 +
 +                break;
 +
 +            case SHORT_ARR:
 +                obj = doReadShortArray();
 +
 +                break;
 +
 +            case INT_ARR:
 +                obj = doReadIntArray();
 +
 +                break;
 +
 +            case LONG_ARR:
 +                obj = doReadLongArray();
 +
 +                break;
 +
 +            case FLOAT_ARR:
 +                obj = doReadFloatArray();
 +
 +                break;
 +
 +            case DOUBLE_ARR:
 +                obj = doReadDoubleArray();
 +
 +                break;
 +
 +            case CHAR_ARR:
 +                obj = doReadCharArray();
 +
 +                break;
 +
 +            case BOOLEAN_ARR:
 +                obj = doReadBooleanArray();
 +
 +                break;
 +
 +            case DECIMAL_ARR:
 +                obj = doReadDecimalArray();
 +
 +                break;
 +
 +            case STRING_ARR:
 +                obj = doReadStringArray();
 +
 +                break;
 +
 +            case UUID_ARR:
 +                obj = doReadUuidArray();
 +
 +                break;
 +
 +            case DATE_ARR:
 +                obj = doReadDateArray();
 +
 +                break;
 +
 +            case TIMESTAMP_ARR:
 +                obj = doReadTimestampArray();
 +
 +                break;
 +
 +            case OBJ_ARR:
 +                obj = doReadObjectArray(true);
 +
 +                break;
 +
 +            case COL:
 +                obj = doReadCollection(true, null);
 +
 +                break;
 +
 +            case MAP:
 +                obj = doReadMap(true, null);
 +
 +                break;
 +
 +            case MAP_ENTRY:
 +                obj = doReadMapEntry(true);
 +
 +                break;
 +
 +            case PORTABLE_OBJ:
 +                obj = doReadPortableObject();
 +
 +                ((BinaryObjectImpl)obj).context(ctx);
 +
 +                if (!GridPortableMarshaller.KEEP_PORTABLES.get())
 +                    obj = ((BinaryObject)obj).deserialize();
 +
 +                break;
 +
 +            case ENUM:
 +                obj = doReadEnum(doReadClass());
 +
 +                break;
 +
 +            case ENUM_ARR:
 +                obj = doReadEnumArray(doReadClass());
 +
 +                break;
 +
 +            case CLASS:
 +                obj = doReadClass();
 +
 +                break;
 +
 +            case OPTM_MARSH:
 +                int dataLen = in.readInt();
 +
 +                ByteArrayInputStream input = new ByteArrayInputStream(in.array(), in.position(), dataLen);
 +
 +                try {
 +                    obj = ctx.optimizedMarsh().unmarshal(input, null);
 +                }
 +                catch (IgniteCheckedException e) {
 +                    throw new BinaryObjectException("Failed to unmarshal object with optimized marshaller", e);
 +                }
 +
 +                in.position(in.position() + dataLen);
 +
 +                break;
 +
 +            default:
 +                throw new BinaryObjectException("Invalid flag value: " + flag);
 +        }
 +
 +        return obj;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private byte[] doReadByteArray() {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        byte[] arr = in.readByteArray(len);
 +
 +        setHandler(arr, hPos);
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private short[] doReadShortArray() {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        short[] arr = in.readShortArray(len);
 +
 +        setHandler(arr, hPos);
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private int[] doReadIntArray() {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        int[] arr = in.readIntArray(len);
 +
 +        setHandler(arr, hPos);
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private long[] doReadLongArray() {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        long[] arr = in.readLongArray(len);
 +
 +        setHandler(arr, hPos);
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private float[] doReadFloatArray() {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        float[] arr = in.readFloatArray(len);
 +
 +        setHandler(arr, hPos);
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private double[] doReadDoubleArray() {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        double[] arr = in.readDoubleArray(len);
 +
 +        setHandler(arr, hPos);
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private char[] doReadCharArray() {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        char[] arr = in.readCharArray(len);
 +
 +        setHandler(arr, hPos);
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private boolean[] doReadBooleanArray() {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        boolean[] arr = in.readBooleanArray(len);
 +
 +        setHandler(arr, hPos);
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    private BigDecimal[] doReadDecimalArray() throws BinaryObjectException {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        BigDecimal[] arr = new BigDecimal[len];
 +
 +        setHandler(arr, hPos);
 +
 +        for (int i = 0; i < len; i++) {
 +            byte flag = in.readByte();
 +
 +            if (flag == NULL)
 +                arr[i] = null;
 +            else {
 +                if (flag != DECIMAL)
 +                    throw new BinaryObjectException("Invalid flag value: " + flag);
 +
 +                arr[i] = doReadDecimal();
 +            }
 +        }
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    private String[] doReadStringArray() throws BinaryObjectException {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        String[] arr = new String[len];
 +
 +        setHandler(arr, hPos);
 +
 +        for (int i = 0; i < len; i++) {
 +            byte flag = in.readByte();
 +
 +            if (flag == NULL)
 +                arr[i] = null;
 +            else {
 +                if (flag != STRING)
 +                    throw new BinaryObjectException("Invalid flag value: " + flag);
 +
 +                arr[i] = doReadString();
 +            }
 +        }
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    private UUID[] doReadUuidArray() throws BinaryObjectException {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        UUID[] arr = new UUID[len];
 +
 +        setHandler(arr, hPos);
 +
 +        for (int i = 0; i < len; i++) {
 +            byte flag = in.readByte();
 +
 +            if (flag == NULL)
 +                arr[i] = null;
 +            else {
 +                if (flag != UUID)
 +                    throw new BinaryObjectException("Invalid flag value: " + flag);
 +
 +                arr[i] = doReadUuid();
 +            }
 +        }
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    private Date[] doReadDateArray() throws BinaryObjectException {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        Date[] arr = new Date[len];
 +
 +        setHandler(arr, hPos);
 +
 +        for (int i = 0; i < len; i++) {
 +            byte flag = in.readByte();
 +
 +            if (flag == NULL)
 +                arr[i] = null;
 +            else {
 +                if (flag != DATE)
 +                    throw new BinaryObjectException("Invalid flag value: " + flag);
 +
 +                arr[i] = doReadDate();
 +            }
 +        }
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    private Timestamp[] doReadTimestampArray() throws BinaryObjectException {
 +        int hPos = in.position() - 1;
 +
 +        int len = in.readInt();
 +
 +        Timestamp[] arr = new Timestamp[len];
 +
 +        setHandler(arr, hPos);
 +
 +        for (int i = 0; i < len; i++) {
 +            byte flag = in.readByte();
 +
 +            if (flag == NULL)
 +                arr[i] = null;
 +            else {
 +                if (flag != TIMESTAMP)
 +                    throw new BinaryObjectException("Invalid flag value: " + flag);
 +
 +                arr[i] = doReadTimestamp();
 +            }
 +        }
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @param deep Deep flag.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    private Object[] doReadObjectArray(boolean deep) throws BinaryObjectException {
 +        int hPos = in.position() - 1;
 +
 +        Class compType = doReadClass();
 +
 +        int len = in.readInt();
 +
 +        Object[] arr = deep ? (Object[])Array.newInstance(compType, len) : new Object[len];
 +
 +        setHandler(arr, hPos);
 +
 +        for (int i = 0; i < len; i++)
 +            arr[i] = deep ? doReadObject() : unmarshal();
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @param deep Deep flag.
 +     * @param cls Collection class.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @SuppressWarnings("unchecked")
 +    private Collection<?> doReadCollection(boolean deep, @Nullable Class<? extends Collection> cls)
 +        throws BinaryObjectException {
 +        int hPos = in.position() - 1;
 +
 +        int size = in.readInt();
 +
 +        assert size >= 0;
 +
 +        byte colType = in.readByte();
 +
 +        Collection<Object> col;
 +
 +        if (cls != null) {
 +            try {
 +                Constructor<? extends Collection> cons = cls.getConstructor();
 +
 +                col = cons.newInstance();
 +            }
 +            catch (NoSuchMethodException ignored) {
 +                throw new BinaryObjectException("Collection class doesn't have public default constructor: " +
 +                    cls.getName());
 +            }
 +            catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
 +                throw new BinaryObjectException("Failed to instantiate collection: " + cls.getName(), e);
 +            }
 +        }
 +        else {
 +            switch (colType) {
 +                case ARR_LIST:
 +                    col = new ArrayList<>(size);
 +
 +                    break;
 +
 +                case LINKED_LIST:
 +                    col = new LinkedList<>();
 +
 +                    break;
 +
 +                case HASH_SET:
 +                    col = U.newHashSet(size);
 +
 +                    break;
 +
 +                case LINKED_HASH_SET:
 +                    col = U.newLinkedHashSet(size);
 +
 +                    break;
 +
 +                case TREE_SET:
 +                    col = new TreeSet<>();
 +
 +                    break;
 +
 +                case CONC_SKIP_LIST_SET:
 +                    col = new ConcurrentSkipListSet<>();
 +
 +                    break;
 +
 +                case USER_SET:
 +                    col = U.newHashSet(size);
 +
 +                    break;
 +
 +                case USER_COL:
 +                    col = new ArrayList<>(size);
 +
 +                    break;
 +
 +                default:
 +                    throw new BinaryObjectException("Invalid collection type: " + colType);
 +            }
 +        }
 +
 +        setHandler(col, hPos);
 +
 +        for (int i = 0; i < size; i++)
 +            col.add(deep ? doReadObject() : unmarshal());
 +
 +        return col;
 +    }
 +
 +    /**
 +     * @param deep Deep flag.
 +     * @param cls Map class.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    @SuppressWarnings("unchecked")
 +    private Map<?, ?> doReadMap(boolean deep, @Nullable Class<? extends Map> cls)
 +        throws BinaryObjectException {
 +        int hPos = in.position() - 1;
 +
 +        int size = in.readInt();
 +
 +        assert size >= 0;
 +
 +        byte mapType = in.readByte();
 +
 +        Map<Object, Object> map;
 +
 +        if (cls != null) {
 +            try {
 +                Constructor<? extends Map> cons = cls.getConstructor();
 +
 +                map = cons.newInstance();
 +            }
 +            catch (NoSuchMethodException ignored) {
 +                throw new BinaryObjectException("Map class doesn't have public default constructor: " +
 +                    cls.getName());
 +            }
 +            catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
 +                throw new BinaryObjectException("Failed to instantiate map: " + cls.getName(), e);
 +            }
 +        }
 +        else {
 +            switch (mapType) {
 +                case HASH_MAP:
 +                    map = U.newHashMap(size);
 +
 +                    break;
 +
 +                case LINKED_HASH_MAP:
 +                    map = U.newLinkedHashMap(size);
 +
 +                    break;
 +
 +                case TREE_MAP:
 +                    map = new TreeMap<>();
 +
 +                    break;
 +
 +                case CONC_HASH_MAP:
 +                    map = new ConcurrentHashMap<>(size);
 +
 +                    break;
 +
 +                case USER_COL:
 +                    map = U.newHashMap(size);
 +
 +                    break;
 +
 +                case PROPERTIES_MAP:
 +                    map = new Properties();
 +
 +                    break;
 +
 +                default:
 +                    throw new BinaryObjectException("Invalid map type: " + mapType);
 +            }
 +        }
 +
 +        setHandler(map, hPos);
 +
 +        for (int i = 0; i < size; i++)
 +            map.put(deep ? doReadObject() : unmarshal(), deep ? doReadObject() : unmarshal());
 +
 +        return map;
 +    }
 +
 +    /**
 +     * @param deep Deep flag.
 +     * @return Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    private Map.Entry<?, ?> doReadMapEntry(boolean deep) throws BinaryObjectException {
 +        int hPos = in.position() - 1;
 +
 +        Object val1 = deep ? doReadObject() : unmarshal();
 +        Object val2 = deep ? doReadObject() : unmarshal();
 +
 +        GridMapEntry entry = new GridMapEntry<>(val1, val2);
 +
 +        setHandler(entry, hPos);
 +
 +        return entry;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private BinaryObject doReadPortableObject() {
 +        if (in.offheapPointer() > 0) {
 +            int len = in.readInt();
 +
 +            int pos = in.position();
 +
 +            in.position(in.position() + len);
 +
 +            int start = in.readInt();
 +
 +            return new BinaryObjectOffheapImpl(ctx, in.offheapPointer() + pos, start, len);
 +        }
 +        else {
 +            byte[] arr = doReadByteArray();
 +            int start = in.readInt();
 +
 +            return new BinaryObjectImpl(ctx, arr, start);
 +        }
 +    }
 +
 +    /**
 +     * @param cls Enum class.
 +     * @return Value.
 +     */
 +    private Enum<?> doReadEnum(Class<?> cls) throws BinaryObjectException {
 +        if (!cls.isEnum())
 +            throw new BinaryObjectException("Class does not represent enum type: " + cls.getName());
 +
 +        int ord = in.readInt();
 +
 +        return ord >= 0 ? (Enum<?>)GridEnumCache.get(cls)[ord] : null;
 +    }
 +
 +    /**
 +     * @param cls Enum class.
 +     * @return Value.
 +     */
 +    private Object[] doReadEnumArray(Class<?> cls) throws BinaryObjectException {
 +        int len = in.readInt();
 +
 +        Object[] arr = (Object[])Array.newInstance(cls, len);
 +
 +        for (int i = 0; i < len; i++) {
 +            byte flag = in.readByte();
 +
 +            if (flag == NULL)
 +                arr[i] = null;
 +            else
 +                arr[i] = doReadEnum(doReadClass());
 +        }
 +
 +        return arr;
 +    }
 +
 +    /**
 +     * @return Value.
 +     */
 +    private Class doReadClass() throws BinaryObjectException {
 +        return doReadClass(in.readInt());
 +    }
 +
 +    /**
 +     * @param typeId Type id.
 +     * @return Value.
 +     */
 +    private Class doReadClass(int typeId) throws BinaryObjectException {
 +        Class cls;
 +
 +        if (typeId == OBJECT_TYPE_ID)
 +            return Object.class;
 +
 +        if (typeId != UNREGISTERED_TYPE_ID)
 +            cls = ctx.descriptorForTypeId(true, typeId, ldr).describedClass();
 +        else {
 +            byte flag = in.readByte();
 +
 +            if (flag != STRING)
 +                throw new BinaryObjectException("No class definition for typeId: " + typeId);
 +
 +            String clsName = doReadString();
 +
 +            try {
 +                cls = U.forName(clsName, ldr);
 +            }
 +            catch (ClassNotFoundException e) {
 +                throw new BinaryInvalidTypeException("Failed to load the class: " + clsName, e);
 +            }
 +
 +            // forces registering of class by type id, at least locally
 +            ctx.descriptorForClass(cls);
 +        }
 +
 +        return cls;
 +    }
 +
 +    /**
 +     * @param name Field name.
 +     * @return Field offset.
 +     */
 +    private int fieldId(String name) {
 +        assert name != null;
 +
 +        parseHeaderIfNeeded();
 +
 +        assert typeId != UNREGISTERED_TYPE_ID;
 +
 +        if (idMapper == null)
 +            idMapper = ctx.userTypeIdMapper(typeId);
 +
 +        return idMapper.fieldId(typeId, name);
 +    }
 +
 +    /**
 +     * Create schema.
 +     *
 +     * @return Schema.
 +     */
 +    public PortableSchema createSchema() {
 +        parseHeaderIfNeeded();
 +
 +        LinkedHashMap<Integer, Integer> fields = new LinkedHashMap<>();
 +
 +        int searchPos = footerStart;
 +        int searchEnd = searchPos + footerLen;
 +
++        int idx = 0;
++
 +        while (searchPos < searchEnd) {
 +            int fieldId = in.readIntPositioned(searchPos);
 +
-             fields.put(fieldId, searchPos + 4 - footerStart);
++            fields.put(fieldId, idx++);
 +
-             searchPos += 8;
++            searchPos += 4 + offsetSize;
 +        }
 +
 +        return new PortableSchema(fields);
 +    }
 +
 +    /**
 +     * @param id Field ID.
 +     * @return Field offset.
 +     */
 +    private int fieldOffset(int id) {
 +        assert hdrLen != 0;
 +
 +        if (footerLen == 0)
 +            return 0;
 +
 +        int searchPos = footerStart;
 +        int searchTail = searchPos + footerLen;
 +
 +        if (hasLowFieldsCount(footerLen)) {
 +            while (true) {
 +                if (searchPos >= searchTail)
 +                    return 0;
 +
 +                int id0 = in.readIntPositioned(searchPos);
 +
 +                if (id0 == id) {
-                     int pos = start + in.readIntPositioned(searchPos + 4);
++                    int pos = start + PortableUtils.fieldOffsetRelative(in, searchPos + 4, offsetSize);
 +
 +                    in.position(pos);
 +
 +                    return pos;
 +                }
 +
-                 searchPos += 8;
++                searchPos += 4 + offsetSize;
 +            }
 +        }
 +        else {
 +            PortableSchema schema0 = schema;
 +
 +            if (schema0 == null) {
 +                schema0 = ctx.schemaRegistry(typeId).schema(schemaId);
 +
 +                if (schema0 == null) {
 +                    schema0 = createSchema();
 +
 +                    ctx.schemaRegistry(typeId).addSchema(schemaId, schema0);
 +                }
 +
 +                schema = schema0;
 +            }
 +
-             int fieldOffsetPos = schema.offset(id);
++            int order = schema.order(id);
++
++            if (order != 0) {
++                int offsetPos = footerStart + order * (4 + offsetSize) + 4;
 +
-             if (fieldOffsetPos != 0) {
-                 int pos = start + in.readIntPositioned(footerStart + fieldOffsetPos);
++                int pos = start + PortableUtils.fieldOffsetRelative(in, offsetPos, offsetSize);
 +
 +                in.position(pos);
 +
 +                return pos;
 +            }
 +            else
 +                return 0;
 +        }
 +    }
 +
 +    /**
 +     * Check whether object has low amount of fields.
 +     *
 +     * @param footerLen Footer length.
 +     */
 +    private boolean hasLowFieldsCount(int footerLen) {
 +        assert hdrParsed;
 +
 +        return footerLen < (FIELD_DESC_LEN << 4);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int readUnsignedByte() throws IOException {
 +        return readByte() & 0xff;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int readUnsignedShort() throws IOException {
 +        return readShort() & 0xffff;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public String readLine() throws IOException {
 +        SB sb = new SB();
 +
 +        int b;
 +
 +        while ((b = read()) >= 0) {
 +            char c = (char)b;
 +
 +            switch (c) {
 +                case '\n':
 +                    return sb.toString();
 +
 +                case '\r':
 +                    b = read();
 +
 +                    if (b < 0 || b == '\n')
 +                        return sb.toString();
 +                    else
 +                        sb.a((char)b);
 +
 +                    break;
 +
 +                default:
 +                    sb.a(c);
 +            }
 +        }
 +
 +        return sb.toString();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("ConstantConditions")
 +    @NotNull @Override public String readUTF() throws IOException {
 +        return readString();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("NullableProblems")
 +    @Override public void readFully(byte[] b) throws IOException {
 +        readFully(b, 0, b.length);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("NullableProblems")
 +    @Override public void readFully(byte[] b, int off, int len) throws IOException {
 +        int cnt = in.read(b, off, len);
 +
 +        if (cnt < len)
 +            throw new EOFException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int skipBytes(int n) throws IOException {
 +        int toSkip = Math.min(in.remaining(), n);
 +
 +        in.position(in.position() + toSkip);
 +
 +        return toSkip;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int read() throws IOException {
 +        return readByte();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int read(byte[] b) throws IOException {
 +        return read(b, 0, b.length);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int read(byte[] b, int off, int len) throws IOException {
 +        return in.read(b, off, len);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public long skip(long n) throws IOException {
 +        return skipBytes((int) n);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int available() throws IOException {
 +        return in.remaining();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void close() throws IOException {
 +        // No-op.
 +    }
 +
 +    /**
 +     * Flag.
 +     */
 +    private static enum Flag {
 +        /** Null. */
 +        NULL,
 +
 +        /** Handle. */
 +        HANDLE,
 +
 +        /** Regular. */
 +        NORMAL
 +    }
 +}


[3/5] ignite git commit: Merge branch ignite-1282 into ignite-950-new

Posted by ag...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/c050b4ce/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryWriterExImpl.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryWriterExImpl.java
index 75c44b5,0000000..1681e4b
mode 100644,000000..100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryWriterExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryWriterExImpl.java
@@@ -1,1855 -1,0 +1,1915 @@@
 +/*
 + * 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.portable;
 +
 +import org.apache.ignite.IgniteCheckedException;
 +import org.apache.ignite.binary.BinaryTypeIdMapper;
 +import org.apache.ignite.internal.portable.streams.PortableHeapOutputStream;
 +import org.apache.ignite.internal.portable.streams.PortableOutputStream;
 +import org.apache.ignite.internal.util.typedef.internal.A;
 +import org.apache.ignite.binary.BinaryObjectException;
 +import org.apache.ignite.binary.BinaryRawWriter;
 +import org.apache.ignite.binary.BinaryWriter;
 +import org.jetbrains.annotations.Nullable;
 +
 +import java.io.IOException;
 +import java.io.ObjectOutput;
 +import java.lang.reflect.InvocationTargetException;
 +import java.math.BigDecimal;
 +import java.math.BigInteger;
 +import java.sql.Timestamp;
 +import java.util.Collection;
 +import java.util.Date;
 +import java.util.IdentityHashMap;
 +import java.util.Map;
 +import java.util.UUID;
 +
 +import static java.nio.charset.StandardCharsets.UTF_8;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BOOLEAN;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BOOLEAN_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BYTE;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BYTE_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.CHAR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.CHAR_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.CLASS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.COL;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DATE;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DATE_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DECIMAL;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DECIMAL_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DOUBLE;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DOUBLE_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.ENUM;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.ENUM_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLAGS_POS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLOAT;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLOAT_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.INT;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.INT_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.LONG;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.LONG_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.MAP;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.MAP_ENTRY;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.NULL;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.OBJ;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.OBJ_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.OPTM_MARSH;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.PORTABLE_OBJ;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.SCHEMA_ID_POS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.SCHEMA_OR_RAW_OFF_POS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.SHORT;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.SHORT_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.STRING;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.STRING_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.TIMESTAMP;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.TIMESTAMP_ARR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.TOTAL_LEN_POS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.UNREGISTERED_TYPE_ID;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.UUID;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.UUID_ARR;
 +
 +/**
 + * Portable writer implementation.
 + */
 +public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, ObjectOutput {
 +    /** Length: integer. */
 +    private static final int LEN_INT = 4;
 +
 +    /** */
 +    private static final int INIT_CAP = 1024;
 +
 +    /** FNV1 hash offset basis. */
 +    private static final int FNV1_OFFSET_BASIS = 0x811C9DC5;
 +
 +    /** FNV1 hash prime. */
 +    private static final int FNV1_PRIME = 0x01000193;
 +
++    /** Maximum offset which fits in 1 byte. */
++    private static final int MAX_OFFSET_1 = 1 << 8;
++
++    /** Maximum offset which fits in 2 bytes. */
++    private static final int MAX_OFFSET_2 = 1 << 16;
++
 +    /** Thread-local schema. */
 +    private static final ThreadLocal<SchemaHolder> SCHEMA = new ThreadLocal<>();
 +
 +    /** */
 +    private final PortableContext ctx;
 +
 +    /** */
 +    private final int start;
 +
 +    /** */
 +    private Class<?> cls;
 +
 +    /** */
 +    private int typeId;
 +
 +    /** Raw offset position. */
 +    private int rawOffPos;
 +
 +    /** */
 +    private boolean metaEnabled;
 +
 +    /** */
 +    private int metaHashSum;
 +
 +    /** Handles. */
 +    private Map<Object, Integer> handles;
 +
 +    /** Output stream. */
 +    private PortableOutputStream out;
 +
 +    /** Schema. */
 +    private SchemaHolder schema;
 +
 +    /** Schema ID. */
 +    private int schemaId;
 +
 +    /** Amount of written fields. */
 +    private int fieldCnt;
 +
 +    /** ID mapper. */
 +    private BinaryTypeIdMapper idMapper;
 +
 +    /**
 +     * @param ctx Context.
 +     */
 +    BinaryWriterExImpl(PortableContext ctx) {
 +        this(ctx, new PortableHeapOutputStream(INIT_CAP));
 +    }
 +
 +    /**
 +     * @param ctx Context.
 +     * @param out Output stream.
 +     */
 +    BinaryWriterExImpl(PortableContext ctx, PortableOutputStream out) {
 +        this(ctx, out, new IdentityHashMap<Object, Integer>());
 +    }
 +
 +     /**
 +      * @param ctx Context.
 +      * @param out Output stream.
 +      * @param handles Handles.
 +      */
 +     private BinaryWriterExImpl(PortableContext ctx, PortableOutputStream out, Map<Object, Integer> handles) {
 +         this.ctx = ctx;
 +         this.out = out;
 +         this.handles = handles;
 +
 +         start = out.position();
 +     }
 +
 +    /**
 +     * @param ctx Context.
 +     * @param typeId Type ID.
 +     */
 +    public BinaryWriterExImpl(PortableContext ctx, int typeId, boolean metaEnabled) {
 +        this(ctx);
 +
 +        this.typeId = typeId;
 +        this.metaEnabled = metaEnabled;
 +    }
 +
 +    /**
 +     * Close the writer releasing resources if necessary.
 +     */
 +    @Override public void close() {
 +        out.close();
 +    }
 +
 +    /**
 +     * @return Meta data hash sum or {@code null} if meta data is disabled.
 +     */
 +    @Nullable Integer metaDataHashSum() {
 +        return metaEnabled ? metaHashSum : null;
 +    }
 +
 +    /**
 +     * @param obj Object.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void marshal(Object obj) throws BinaryObjectException {
 +        marshal(obj, true);
 +    }
 +
 +    /**
 +     * @param obj Object.
 +     * @param enableReplace Object replacing enabled flag.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void marshal(Object obj, boolean enableReplace) throws BinaryObjectException {
 +        assert obj != null;
 +
 +        cls = obj.getClass();
 +
 +        PortableClassDescriptor desc = ctx.descriptorForClass(cls);
 +
 +        if (desc == null)
 +            throw new BinaryObjectException("Object is not portable: [class=" + cls + ']');
 +
 +        if (desc.excluded()) {
 +            doWriteByte(NULL);
 +            return;
 +        }
 +
 +        if (desc.useOptimizedMarshaller()) {
 +            writeByte(OPTM_MARSH);
 +
 +            try {
 +                byte[] arr = ctx.optimizedMarsh().marshal(obj);
 +
 +                writeInt(arr.length);
 +
 +                write(arr);
 +            }
 +            catch (IgniteCheckedException e) {
 +                throw new BinaryObjectException("Failed to marshal object with optimized marshaller: " + obj, e);
 +            }
 +
 +            return;
 +        }
 +
 +        if (enableReplace && desc.getWriteReplaceMethod() != null) {
 +            Object replacedObj;
 +
 +            try {
 +                replacedObj = desc.getWriteReplaceMethod().invoke(obj);
 +            }
 +            catch (IllegalAccessException e) {
 +                throw new RuntimeException(e);
 +            }
 +            catch (InvocationTargetException e) {
 +                if (e.getTargetException() instanceof BinaryObjectException)
 +                    throw (BinaryObjectException)e.getTargetException();
 +
 +                throw new BinaryObjectException("Failed to execute writeReplace() method on " + obj, e);
 +            }
 +
 +            if (replacedObj == null) {
 +                doWriteByte(NULL);
 +                return;
 +            }
 +
 +            marshal(replacedObj, false);
 +
 +            return;
 +        }
 +
 +        typeId = desc.typeId();
 +
 +        metaEnabled = ctx.isMetaDataEnabled(typeId);
 +
 +        desc.write(obj, this);
 +    }
 +
 +    /**
 +     * @param obj Object.
 +     * @return Handle.
 +     */
 +    int handle(Object obj) {
 +        assert obj != null;
 +
 +        Integer h = handles.get(obj);
 +
 +        if (h != null)
 +            return out.position() - h;
 +        else {
 +            handles.put(obj, out.position());
 +
 +            return -1;
 +        }
 +    }
 +
 +    /**
 +     * @return Array.
 +     */
 +    public byte[] array() {
 +        return out.arrayCopy();
 +    }
 +
 +    /**
 +     * @return Stream current position.
 +     */
 +    int position() {
 +        return out.position();
 +    }
 +
 +    /**
 +     * Sets new position.
 +     *
 +     * @param pos Position.
 +     */
 +    void position(int pos) {
 +        out.position(pos);
 +    }
 +
 +    /**
 +     * @param bytes Number of bytes to reserve.
 +     * @return Offset.
 +     */
 +    public int reserve(int bytes) {
 +        int pos = out.position();
 +
 +        out.position(pos + bytes);
 +
 +        return pos;
 +    }
 +
 +    /**
 +     * Perform post-write activity. This includes:
 +     * - writing object length;
 +     * - writing schema offset;
 +     * - writing schema to the tail.
 +     *
 +     * @param userType User type flag.
 +     */
 +    public void postWrite(boolean userType) {
 +        if (schema != null) {
 +            // Write schema ID.
 +            out.writeInt(start + SCHEMA_ID_POS, schemaId);
 +
 +            // Write schema offset.
 +            out.writeInt(start + SCHEMA_OR_RAW_OFF_POS, out.position() - start);
 +
 +            // Write the schema.
-             schema.writeAndPop(this, fieldCnt);
++            int offsetByteCnt = schema.write(this, fieldCnt);
 +
 +            // Write raw offset if needed.
 +            if (rawOffPos != 0)
 +                out.writeInt(rawOffPos - start);
++
++            if (offsetByteCnt == PortableUtils.OFFSET_1) {
++                int flags = (userType ? PortableUtils.FLAG_USR_TYP : 0) | PortableUtils.FLAG_OFFSET_ONE_BYTE;
++
++                out.writeShort(start + FLAGS_POS, (short)flags);
++            }
++            else if (offsetByteCnt == PortableUtils.OFFSET_2) {
++                int flags = (userType ? PortableUtils.FLAG_USR_TYP : 0) | PortableUtils.FLAG_OFFSET_TWO_BYTES;
++
++                out.writeShort(start + FLAGS_POS, (short)flags);
++            }
 +        }
 +        else {
 +            // Write raw-only flag is needed.
 +            int flags = (userType ? PortableUtils.FLAG_USR_TYP : 0) | PortableUtils.FLAG_RAW_ONLY;
 +
 +            out.writeShort(start + FLAGS_POS, (short)flags);
 +
 +            // If there are no schema, we are free to write raw offset to schema offset.
 +            out.writeInt(start + SCHEMA_OR_RAW_OFF_POS, (rawOffPos == 0 ? out.position() : rawOffPos) - start);
 +        }
 +
 +        // 5. Write length.
 +        out.writeInt(start + TOTAL_LEN_POS, out.position() - start);
 +    }
 +
 +    /**
++     * Pop schema.
++     */
++    public void popSchema() {
++        if (schema != null) {
++            assert fieldCnt > 0;
++
++            schema.pop(fieldCnt);
++        }
++    }
++
++    /**
 +     * @param val Byte array.
 +     */
 +    public void write(byte[] val) {
 +        assert val != null;
 +
 +        out.writeByteArray(val);
 +    }
 +
 +    /**
 +     * @param val Byte array.
 +     * @param off Offset.
 +     * @param len Length.
 +     */
 +    public void write(byte[] val, int off, int len) {
 +        assert val != null;
 +
 +        out.write(val, off, len);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    public void doWriteByte(byte val) {
 +        out.writeByte(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    public void doWriteShort(short val) {
 +        out.writeShort(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    public void doWriteInt(int val) {
 +        out.writeInt(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    public void doWriteLong(long val) {
 +        out.writeLong(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    public void doWriteFloat(float val) {
 +        out.writeFloat(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    public void doWriteDouble(double val) {
 +        out.writeDouble(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    public void doWriteChar(char val) {
 +        out.writeChar(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    public void doWriteBoolean(boolean val) {
 +        out.writeBoolean(val);
 +    }
 +
 +    /**
 +     * @param val String value.
 +     */
 +    public void doWriteDecimal(@Nullable BigDecimal val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(DECIMAL);
 +
 +            BigInteger intVal = val.unscaledValue();
 +
 +            if (intVal.signum() == -1) {
 +                intVal = intVal.negate();
 +
 +                out.writeInt(val.scale() | 0x80000000);
 +            }
 +            else
 +                out.writeInt(val.scale());
 +
 +            byte[] vals = intVal.toByteArray();
 +
 +            out.writeInt(vals.length);
 +            out.writeByteArray(vals);
 +        }
 +    }
 +
 +    /**
 +     * @param val String value.
 +     */
 +    public void doWriteString(@Nullable String val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(STRING);
 +
 +            if (ctx.isConvertString()) {
 +                doWriteBoolean(true);
 +
 +                byte[] strArr = val.getBytes(UTF_8);
 +
 +                doWriteInt(strArr.length);
 +
 +                out.writeByteArray(strArr);
 +            }
 +            else {
 +                doWriteBoolean(false);
 +
 +                char[] strArr = val.toCharArray();
 +
 +                doWriteInt(strArr.length);
 +
 +                out.writeCharArray(strArr);
 +            }
 +        }
 +    }
 +
 +    /**
 +     * @param uuid UUID.
 +     */
 +    public void doWriteUuid(@Nullable UUID uuid) {
 +        if (uuid == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(UUID);
 +            doWriteLong(uuid.getMostSignificantBits());
 +            doWriteLong(uuid.getLeastSignificantBits());
 +        }
 +    }
 +
 +    /**
 +     * @param date Date.
 +     */
 +    public void doWriteDate(@Nullable Date date) {
 +        if (date == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(DATE);
 +            doWriteLong(date.getTime());
 +        }
 +    }
 +
 +    /**
 +     * @param ts Timestamp.
 +     */
 +    public void doWriteTimestamp(@Nullable Timestamp ts) {
 +        if (ts== null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(TIMESTAMP);
 +            doWriteLong(ts.getTime());
 +            doWriteInt(ts.getNanos() % 1000000);
 +        }
 +    }
 +
 +    /**
 +     * Write object.
 +     *
 +     * @param obj Object.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    public void doWriteObject(@Nullable Object obj) throws BinaryObjectException {
 +        if (obj == null)
 +            doWriteByte(NULL);
 +        else {
 +            BinaryWriterExImpl writer = new BinaryWriterExImpl(ctx, out, handles);
 +
 +            writer.marshal(obj);
 +        }
 +    }
 +
 +    /**
 +     * @param val Byte array.
 +     */
 +    void doWriteByteArray(@Nullable byte[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(BYTE_ARR);
 +            doWriteInt(val.length);
 +
 +            out.writeByteArray(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Short array.
 +     */
 +    void doWriteShortArray(@Nullable short[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(SHORT_ARR);
 +            doWriteInt(val.length);
 +
 +            out.writeShortArray(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Integer array.
 +     */
 +    void doWriteIntArray(@Nullable int[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(INT_ARR);
 +            doWriteInt(val.length);
 +
 +            out.writeIntArray(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Long array.
 +     */
 +    void doWriteLongArray(@Nullable long[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(LONG_ARR);
 +            doWriteInt(val.length);
 +
 +            out.writeLongArray(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Float array.
 +     */
 +    void doWriteFloatArray(@Nullable float[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(FLOAT_ARR);
 +            doWriteInt(val.length);
 +
 +            out.writeFloatArray(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Double array.
 +     */
 +    void doWriteDoubleArray(@Nullable double[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(DOUBLE_ARR);
 +            doWriteInt(val.length);
 +
 +            out.writeDoubleArray(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Char array.
 +     */
 +    void doWriteCharArray(@Nullable char[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(CHAR_ARR);
 +            doWriteInt(val.length);
 +
 +            out.writeCharArray(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Boolean array.
 +     */
 +    void doWriteBooleanArray(@Nullable boolean[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(BOOLEAN_ARR);
 +            doWriteInt(val.length);
 +
 +            out.writeBooleanArray(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Array of strings.
 +     */
 +    void doWriteDecimalArray(@Nullable BigDecimal[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(DECIMAL_ARR);
 +            doWriteInt(val.length);
 +
 +            for (BigDecimal str : val)
 +                doWriteDecimal(str);
 +        }
 +    }
 +
 +    /**
 +     * @param val Array of strings.
 +     */
 +    void doWriteStringArray(@Nullable String[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(STRING_ARR);
 +            doWriteInt(val.length);
 +
 +            for (String str : val)
 +                doWriteString(str);
 +        }
 +    }
 +
 +    /**
 +     * @param val Array of UUIDs.
 +     */
 +    void doWriteUuidArray(@Nullable UUID[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(UUID_ARR);
 +            doWriteInt(val.length);
 +
 +            for (UUID uuid : val)
 +                doWriteUuid(uuid);
 +        }
 +    }
 +
 +    /**
 +     * @param val Array of dates.
 +     */
 +    void doWriteDateArray(@Nullable Date[] val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            doWriteByte(DATE_ARR);
 +            doWriteInt(val.length);
 +
 +            for (Date date : val)
 +                doWriteDate(date);
 +        }
 +    }
 +
 +     /**
 +      * @param val Array of timestamps.
 +      */
 +     void doWriteTimestampArray(@Nullable Timestamp[] val) {
 +         if (val == null)
 +             doWriteByte(NULL);
 +         else {
 +             if (tryWriteAsHandle(val))
 +                 return;
 +
 +             doWriteByte(TIMESTAMP_ARR);
 +             doWriteInt(val.length);
 +
 +             for (Timestamp ts : val)
 +                 doWriteTimestamp(ts);
 +         }
 +     }
 +
 +    /**
 +     * @param val Array of objects.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void doWriteObjectArray(@Nullable Object[] val) throws BinaryObjectException {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(val))
 +                return;
 +
 +            PortableClassDescriptor desc = ctx.descriptorForClass(val.getClass().getComponentType());
 +
 +            doWriteByte(OBJ_ARR);
 +
 +            if (desc.registered())
 +                doWriteInt(desc.typeId());
 +            else {
 +                doWriteInt(UNREGISTERED_TYPE_ID);
 +                doWriteString(val.getClass().getComponentType().getName());
 +            }
 +
 +            doWriteInt(val.length);
 +
 +            for (Object obj : val)
 +                doWriteObject(obj);
 +        }
 +    }
 +
 +    /**
 +     * @param col Collection.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void doWriteCollection(@Nullable Collection<?> col) throws BinaryObjectException {
 +        if (col == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(col))
 +                return;
 +
 +            doWriteByte(COL);
 +            doWriteInt(col.size());
 +            doWriteByte(ctx.collectionType(col.getClass()));
 +
 +            for (Object obj : col)
 +                doWriteObject(obj);
 +        }
 +    }
 +
 +    /**
 +     * @param map Map.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void doWriteMap(@Nullable Map<?, ?> map) throws BinaryObjectException {
 +        if (map == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(map))
 +                return;
 +
 +            doWriteByte(MAP);
 +            doWriteInt(map.size());
 +            doWriteByte(ctx.mapType(map.getClass()));
 +
 +            for (Map.Entry<?, ?> e : map.entrySet()) {
 +                doWriteObject(e.getKey());
 +                doWriteObject(e.getValue());
 +            }
 +        }
 +    }
 +
 +    /**
 +     * @param e Map entry.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void doWriteMapEntry(@Nullable Map.Entry<?, ?> e) throws BinaryObjectException {
 +        if (e == null)
 +            doWriteByte(NULL);
 +        else {
 +            if (tryWriteAsHandle(e))
 +                return;
 +
 +            doWriteByte(MAP_ENTRY);
 +            doWriteObject(e.getKey());
 +            doWriteObject(e.getValue());
 +        }
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void doWriteEnum(@Nullable Enum<?> val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            PortableClassDescriptor desc = ctx.descriptorForClass(val.getClass());
 +
 +            doWriteByte(ENUM);
 +
 +            if (desc.registered())
 +                doWriteInt(desc.typeId());
 +            else {
 +                doWriteInt(UNREGISTERED_TYPE_ID);
 +                doWriteString(val.getClass().getName());
 +            }
 +
 +            doWriteInt(val.ordinal());
 +        }
 +    }
 +
 +    /**
 +     * @param val Array.
 +     */
 +    void doWriteEnumArray(@Nullable Object[] val) {
 +        assert val == null || val.getClass().getComponentType().isEnum();
 +
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            PortableClassDescriptor desc = ctx.descriptorForClass(val.getClass().getComponentType());
 +            doWriteByte(ENUM_ARR);
 +
 +            if (desc.registered())
 +                doWriteInt(desc.typeId());
 +            else {
 +                doWriteInt(UNREGISTERED_TYPE_ID);
 +                doWriteString(val.getClass().getComponentType().getName());
 +            }
 +
 +            doWriteInt(val.length);
 +
 +            // TODO: Denis: Redundant data for each element of the array.
 +            for (Object o : val)
 +                doWriteEnum((Enum<?>)o);
 +        }
 +    }
 +
 +    /**
 +     * @param val Class.
 +     */
 +    void doWriteClass(@Nullable Class val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            PortableClassDescriptor desc = ctx.descriptorForClass(val);
 +
 +            doWriteByte(CLASS);
 +
 +            if (desc.registered())
 +                doWriteInt(desc.typeId());
 +            else {
 +                doWriteInt(UNREGISTERED_TYPE_ID);
 +                doWriteString(val.getClass().getName());
 +            }
 +        }
 +    }
 +
 +    /**
 +     * @param po Portable object.
 +     */
 +    public void doWritePortableObject(@Nullable BinaryObjectImpl po) {
 +        if (po == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(PORTABLE_OBJ);
 +
 +            byte[] poArr = po.array();
 +
 +            doWriteInt(poArr.length);
 +
 +            out.writeByteArray(poArr);
 +
 +            doWriteInt(po.start());
 +        }
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeByteField(@Nullable Byte val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(BYTE);
 +            doWriteByte(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Class.
 +     */
 +    void writeClassField(@Nullable Class val) {
 +        doWriteClass(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeShortField(@Nullable Short val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(SHORT);
 +            doWriteShort(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeIntField(@Nullable Integer val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(INT);
 +            doWriteInt(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeLongField(@Nullable Long val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(LONG);
 +            doWriteLong(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeFloatField(@Nullable Float val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(FLOAT);
 +            doWriteFloat(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeDoubleField(@Nullable Double val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(DOUBLE);
 +            doWriteDouble(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeCharField(@Nullable Character val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(CHAR);
 +            doWriteChar(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeBooleanField(@Nullable Boolean val) {
 +        if (val == null)
 +            doWriteByte(NULL);
 +        else {
 +            doWriteByte(BOOLEAN);
 +            doWriteBoolean(val);
 +        }
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeDecimalField(@Nullable BigDecimal val) {
 +        doWriteDecimal(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeStringField(@Nullable String val) {
 +        doWriteString(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeUuidField(@Nullable UUID val) {
 +        doWriteUuid(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeDateField(@Nullable Date val) {
 +        doWriteDate(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeTimestampField(@Nullable Timestamp val) {
 +        doWriteTimestamp(val);
 +    }
 +
 +    /**
 +     * @param obj Object.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void writeObjectField(@Nullable Object obj) throws BinaryObjectException {
 +        doWriteObject(obj);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeByteArrayField(@Nullable byte[] val) {
 +        doWriteByteArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeShortArrayField(@Nullable short[] val) {
 +        doWriteShortArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeIntArrayField(@Nullable int[] val) {
 +        doWriteIntArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeLongArrayField(@Nullable long[] val) {
 +        doWriteLongArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeFloatArrayField(@Nullable float[] val) {
 +        doWriteFloatArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeDoubleArrayField(@Nullable double[] val) {
 +        doWriteDoubleArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeCharArrayField(@Nullable char[] val) {
 +        doWriteCharArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeBooleanArrayField(@Nullable boolean[] val) {
 +        doWriteBooleanArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeDecimalArrayField(@Nullable BigDecimal[] val) {
 +        doWriteDecimalArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeStringArrayField(@Nullable String[] val) {
 +        doWriteStringArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeUuidArrayField(@Nullable UUID[] val) {
 +        doWriteUuidArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeDateArrayField(@Nullable Date[] val) {
 +        doWriteDateArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeTimestampArrayField(@Nullable Timestamp[] val) {
 +        doWriteTimestampArray(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void writeObjectArrayField(@Nullable Object[] val) throws BinaryObjectException {
 +        doWriteObjectArray(val);
 +    }
 +
 +    /**
 +     * @param col Collection.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void writeCollectionField(@Nullable Collection<?> col) throws BinaryObjectException {
 +        doWriteCollection(col);
 +    }
 +
 +    /**
 +     * @param map Map.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void writeMapField(@Nullable Map<?, ?> map) throws BinaryObjectException {
 +        doWriteMap(map);
 +    }
 +
 +    /**
 +     * @param e Map entry.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void writeMapEntryField(@Nullable Map.Entry<?, ?> e) throws BinaryObjectException {
 +        doWriteMapEntry(e);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeEnumField(@Nullable Enum<?> val) {
 +        doWriteEnum(val);
 +    }
 +
 +    /**
 +     * @param val Value.
 +     */
 +    void writeEnumArrayField(@Nullable Object[] val) {
 +        doWriteEnumArray(val);
 +    }
 +
 +    /**
 +     * @param po Portable object.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
 +     */
 +    void writePortableObjectField(@Nullable BinaryObjectImpl po) throws BinaryObjectException {
 +        doWritePortableObject(po);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeByte(String fieldName, byte val) throws BinaryObjectException {
 +        writeFieldId(fieldName, BYTE);
 +        writeByteField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeByte(byte val) throws BinaryObjectException {
 +        doWriteByte(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeShort(String fieldName, short val) throws BinaryObjectException {
 +        writeFieldId(fieldName, SHORT);
 +        writeShortField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeShort(short val) throws BinaryObjectException {
 +        doWriteShort(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeInt(String fieldName, int val) throws BinaryObjectException {
 +        writeFieldId(fieldName, INT);
 +        writeIntField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeInt(int val) throws BinaryObjectException {
 +        doWriteInt(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeLong(String fieldName, long val) throws BinaryObjectException {
 +        writeFieldId(fieldName, LONG);
 +        writeLongField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeLong(long val) throws BinaryObjectException {
 +        doWriteLong(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeFloat(String fieldName, float val) throws BinaryObjectException {
 +        writeFieldId(fieldName, FLOAT);
 +        writeFloatField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeFloat(float val) throws BinaryObjectException {
 +        doWriteFloat(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDouble(String fieldName, double val) throws BinaryObjectException {
 +        writeFieldId(fieldName, DOUBLE);
 +        writeDoubleField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDouble(double val) throws BinaryObjectException {
 +        doWriteDouble(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeChar(String fieldName, char val) throws BinaryObjectException {
 +        writeFieldId(fieldName, CHAR);
 +        writeCharField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeChar(char val) throws BinaryObjectException {
 +        doWriteChar(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeBoolean(String fieldName, boolean val) throws BinaryObjectException {
 +        writeFieldId(fieldName, BOOLEAN);
 +        writeBooleanField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeBoolean(boolean val) throws BinaryObjectException {
 +        doWriteBoolean(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDecimal(String fieldName, @Nullable BigDecimal val) throws BinaryObjectException {
 +        writeFieldId(fieldName, DECIMAL);
 +        writeDecimalField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDecimal(@Nullable BigDecimal val) throws BinaryObjectException {
 +        doWriteDecimal(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeString(String fieldName, @Nullable String val) throws BinaryObjectException {
 +        writeFieldId(fieldName, STRING);
 +        writeStringField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeString(@Nullable String val) throws BinaryObjectException {
 +        doWriteString(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeUuid(String fieldName, @Nullable UUID val) throws BinaryObjectException {
 +        writeFieldId(fieldName, UUID);
 +        writeUuidField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeUuid(@Nullable UUID val) throws BinaryObjectException {
 +        doWriteUuid(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDate(String fieldName, @Nullable Date val) throws BinaryObjectException {
 +        writeFieldId(fieldName, DATE);
 +        writeDateField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDate(@Nullable Date val) throws BinaryObjectException {
 +        doWriteDate(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeTimestamp(String fieldName, @Nullable Timestamp val) throws BinaryObjectException {
 +        writeFieldId(fieldName, TIMESTAMP);
 +        writeTimestampField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeTimestamp(@Nullable Timestamp val) throws BinaryObjectException {
 +        doWriteTimestamp(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeObject(String fieldName, @Nullable Object obj) throws BinaryObjectException {
 +        writeFieldId(fieldName, OBJ);
 +        writeObjectField(obj);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeObject(@Nullable Object obj) throws BinaryObjectException {
 +        doWriteObject(obj);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeObjectDetached(@Nullable Object obj) throws BinaryObjectException {
 +        if (obj == null)
 +            doWriteByte(NULL);
 +        else {
 +            BinaryWriterExImpl writer = new BinaryWriterExImpl(ctx, out, new IdentityHashMap<Object, Integer>());
 +
 +            writer.marshal(obj);
 +        }
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeByteArray(String fieldName, @Nullable byte[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, BYTE_ARR);
 +        writeByteArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeByteArray(@Nullable byte[] val) throws BinaryObjectException {
 +        doWriteByteArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeShortArray(String fieldName, @Nullable short[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, SHORT_ARR);
 +        writeShortArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeShortArray(@Nullable short[] val) throws BinaryObjectException {
 +        doWriteShortArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeIntArray(String fieldName, @Nullable int[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, INT_ARR);
 +        writeIntArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeIntArray(@Nullable int[] val) throws BinaryObjectException {
 +        doWriteIntArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeLongArray(String fieldName, @Nullable long[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, LONG_ARR);
 +        writeLongArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeLongArray(@Nullable long[] val) throws BinaryObjectException {
 +        doWriteLongArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeFloatArray(String fieldName, @Nullable float[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, FLOAT_ARR);
 +        writeFloatArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeFloatArray(@Nullable float[] val) throws BinaryObjectException {
 +        doWriteFloatArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDoubleArray(String fieldName, @Nullable double[] val)
 +        throws BinaryObjectException {
 +        writeFieldId(fieldName, DOUBLE_ARR);
 +        writeDoubleArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDoubleArray(@Nullable double[] val) throws BinaryObjectException {
 +        doWriteDoubleArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeCharArray(String fieldName, @Nullable char[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, CHAR_ARR);
 +        writeCharArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeCharArray(@Nullable char[] val) throws BinaryObjectException {
 +        doWriteCharArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeBooleanArray(String fieldName, @Nullable boolean[] val)
 +        throws BinaryObjectException {
 +        writeFieldId(fieldName, BOOLEAN_ARR);
 +        writeBooleanArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeBooleanArray(@Nullable boolean[] val) throws BinaryObjectException {
 +        doWriteBooleanArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDecimalArray(String fieldName, @Nullable BigDecimal[] val)
 +        throws BinaryObjectException {
 +        writeFieldId(fieldName, DECIMAL_ARR);
 +        writeDecimalArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDecimalArray(@Nullable BigDecimal[] val) throws BinaryObjectException {
 +        doWriteDecimalArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeStringArray(String fieldName, @Nullable String[] val)
 +        throws BinaryObjectException {
 +        writeFieldId(fieldName, STRING_ARR);
 +        writeStringArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeStringArray(@Nullable String[] val) throws BinaryObjectException {
 +        doWriteStringArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeUuidArray(String fieldName, @Nullable UUID[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, UUID_ARR);
 +        writeUuidArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeUuidArray(@Nullable UUID[] val) throws BinaryObjectException {
 +        doWriteUuidArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDateArray(String fieldName, @Nullable Date[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, DATE_ARR);
 +        writeDateArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeDateArray(@Nullable Date[] val) throws BinaryObjectException {
 +        doWriteDateArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeTimestampArray(String fieldName, @Nullable Timestamp[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, TIMESTAMP_ARR);
 +        writeTimestampArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeTimestampArray(@Nullable Timestamp[] val) throws BinaryObjectException {
 +        doWriteTimestampArray(val);
 +    }
 +
 +     /** {@inheritDoc} */
 +    @Override public void writeObjectArray(String fieldName, @Nullable Object[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, OBJ_ARR);
 +        writeObjectArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeObjectArray(@Nullable Object[] val) throws BinaryObjectException {
 +        doWriteObjectArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public <T> void writeCollection(String fieldName, @Nullable Collection<T> col)
 +        throws BinaryObjectException {
 +        writeFieldId(fieldName, COL);
 +        writeCollectionField(col);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public <T> void writeCollection(@Nullable Collection<T> col) throws BinaryObjectException {
 +        doWriteCollection(col);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public <K, V> void writeMap(String fieldName, @Nullable Map<K, V> map)
 +        throws BinaryObjectException {
 +        writeFieldId(fieldName, MAP);
 +        writeMapField(map);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public <K, V> void writeMap(@Nullable Map<K, V> map) throws BinaryObjectException {
 +        doWriteMap(map);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public <T extends Enum<?>> void writeEnum(String fieldName, T val) throws BinaryObjectException {
 +        writeFieldId(fieldName, ENUM);
 +        writeEnumField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public <T extends Enum<?>> void writeEnum(T val) throws BinaryObjectException {
 +        doWriteEnum(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public <T extends Enum<?>> void writeEnumArray(String fieldName, T[] val) throws BinaryObjectException {
 +        writeFieldId(fieldName, ENUM_ARR);
 +        writeEnumArrayField(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public <T extends Enum<?>> void writeEnumArray(T[] val) throws BinaryObjectException {
 +        doWriteEnumArray(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryRawWriter rawWriter() {
 +        if (rawOffPos == 0)
 +            rawOffPos = out.position();
 +
 +        return this;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public PortableOutputStream out() {
 +        return out;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("NullableProblems")
 +    @Override public void writeBytes(String s) throws IOException {
 +        int len = s.length();
 +
 +        writeInt(len);
 +
 +        for (int i = 0; i < len; i++)
 +            writeByte(s.charAt(i));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("NullableProblems")
 +    @Override public void writeChars(String s) throws IOException {
 +        int len = s.length();
 +
 +        writeInt(len);
 +
 +        for (int i = 0; i < len; i++)
 +            writeChar(s.charAt(i));
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("NullableProblems")
 +    @Override public void writeUTF(String s) throws IOException {
 +        writeString(s);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeByte(int v) throws IOException {
 +        doWriteByte((byte) v);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeShort(int v) throws IOException {
 +        doWriteShort((short) v);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeChar(int v) throws IOException {
 +        doWriteChar((char) v);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void write(int b) throws IOException {
 +        doWriteByte((byte) b);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void flush() throws IOException {
 +        // No-op.
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int reserveInt() {
 +        return reserve(LEN_INT);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeInt(int pos, int val) throws BinaryObjectException {
 +        out.writeInt(pos, val);
 +    }
 +
 +    /**
 +     * @param fieldName Field name.
 +     * @throws org.apache.ignite.binary.BinaryObjectException If fields are not allowed.
 +     */
 +    private void writeFieldId(String fieldName, byte fieldType) throws BinaryObjectException {
 +        A.notNull(fieldName, "fieldName");
 +
 +        if (rawOffPos != 0)
 +            throw new BinaryObjectException("Individual field can't be written after raw writer is acquired " +
 +                "via rawWriter() method. Consider fixing serialization logic for class: " + cls.getName());
 +
 +        if (idMapper == null)
 +            idMapper = ctx.userTypeIdMapper(typeId);
 +
 +        int id = idMapper.fieldId(typeId, fieldName);
 +
 +        writeFieldId(id);
 +
 +        if (metaEnabled)
 +            metaHashSum = 31 * metaHashSum + (id + fieldType);
 +    }
 +
 +    /**
 +     * Write field ID.
 +     * @param fieldId Field ID.
 +     */
 +    public void writeFieldId(int fieldId) {
 +        int fieldOff = out.position() - start;
 +
 +        if (schema == null) {
 +            schema = SCHEMA.get();
 +
 +            if (schema == null) {
 +                schema = new SchemaHolder();
 +
 +                SCHEMA.set(schema);
 +            }
 +
 +            // Initialize offset when the first field is written.
 +            schemaId = FNV1_OFFSET_BASIS;
 +        }
 +
 +        // Advance schema hash.
 +        int schemaId0 = schemaId ^ (fieldId & 0xFF);
 +        schemaId0 = schemaId0 * FNV1_PRIME;
 +        schemaId0 = schemaId0 ^ ((fieldId >> 8) & 0xFF);
 +        schemaId0 = schemaId0 * FNV1_PRIME;
 +        schemaId0 = schemaId0 ^ ((fieldId >> 16) & 0xFF);
 +        schemaId0 = schemaId0 * FNV1_PRIME;
 +        schemaId0 = schemaId0 ^ ((fieldId >> 24) & 0xFF);
 +        schemaId0 = schemaId0 * FNV1_PRIME;
 +
 +        schemaId = schemaId0;
 +
 +        schema.push(fieldId, fieldOff);
 +
 +        fieldCnt++;
 +    }
 +
 +    /**
 +     * Attempts to write the object as a handle.
 +     *
 +     * @param obj Object to write.
 +     * @return {@code true} if the object has been written as a handle.
 +     */
 +    boolean tryWriteAsHandle(Object obj) {
 +        int handle = handle(obj);
 +
 +        if (handle >= 0) {
 +            doWriteByte(GridPortableMarshaller.HANDLE);
 +            doWriteInt(handle);
 +
 +            return true;
 +        }
 +
 +        return false;
 +    }
 +
 +    /**
 +     * Create new writer with same context.
 +     *
 +     * @param typeId type
 +     * @return New writer.
 +     */
 +    public BinaryWriterExImpl newWriter(int typeId) {
 +        BinaryWriterExImpl res = new BinaryWriterExImpl(ctx, out, handles);
 +
 +        res.typeId = typeId;
 +
 +        return res;
 +    }
 +
 +    /**
 +     * @return Portable context.
 +     */
 +    public PortableContext context() {
 +        return ctx;
 +    }
 +
 +    /**
 +     * Schema holder.
 +     */
 +    private static class SchemaHolder {
 +        /** Grow step. */
 +        private static final int GROW_STEP = 16;
 +
 +        /** Maximum stable size. */
 +        private static final int MAX_SIZE = 256;
 +
 +        /** Data. */
 +        private int[] data;
 +
 +        /** Index. */
 +        private int idx;
 +
 +        /**
 +         * Constructor.
 +         */
 +        public SchemaHolder() {
 +            data = new int[GROW_STEP];
 +        }
 +
 +        /**
 +         * Push another frame.
 +         *
 +         * @param id Field ID.
 +         * @param off Field offset.
 +         */
 +        public void push(int id, int off) {
 +            if (idx == data.length) {
 +                int[] data0 = new int[data.length + GROW_STEP];
 +
 +                System.arraycopy(data, 0, data0, 0, data.length);
 +
 +                data = data0;
 +            }
 +
 +            data[idx] = id;
 +            data[idx + 1] = off;
 +
 +            idx += 2;
 +        }
 +
 +        /**
 +         * Write collected frames and pop them.
 +         *
 +         * @param writer Writer.
-          * @param cnt Count.
++         * @param fieldCnt Count.
++         * @return Amount of bytes dedicated to
 +         */
-         public void writeAndPop(BinaryWriterExImpl writer, int cnt) {
-             int startIdx = idx - cnt * 2;
++        public int write(BinaryWriterExImpl writer, int fieldCnt) {
++            int startIdx = idx - fieldCnt * 2;
 +
 +            assert startIdx >= 0;
 +
-             for (int idx0 = startIdx; idx0 < idx;) {
-                 writer.writeInt(data[idx0++]);
-                 writer.writeInt(data[idx0++]);
++            int lastOffset = data[idx - 1];
++
++            int res;
++
++            if (lastOffset < MAX_OFFSET_1) {
++                for (int idx0 = startIdx; idx0 < idx; ) {
++                    writer.writeInt(data[idx0++]);
++                    writer.writeByte((byte) data[idx0++]);
++                }
++
++                res = PortableUtils.OFFSET_1;
 +            }
++            else if (lastOffset < MAX_OFFSET_2) {
++                for (int idx0 = startIdx; idx0 < idx; ) {
++                    writer.writeInt(data[idx0++]);
++                    writer.writeShort((short)data[idx0++]);
++                }
++
++                res = PortableUtils.OFFSET_2;
++            }
++            else {
++                for (int idx0 = startIdx; idx0 < idx; ) {
++                    writer.writeInt(data[idx0++]);
++                    writer.writeInt(data[idx0++]);
++                }
 +
-             idx = startIdx;
++                res = PortableUtils.OFFSET_4;
++            }
++
++            return res;
++        }
++
++        /**
++         * Pop current object's frame.
++         */
++        public void pop(int fieldCnt) {
++            idx = idx - fieldCnt * 2;
 +
 +            // Shrink data array if needed.
 +            if (idx == 0 && data.length > MAX_SIZE)
 +                data = new int[MAX_SIZE];
 +        }
 +    }
 +}

http://git-wip-us.apache.org/repos/asf/ignite/blob/c050b4ce/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
index bbd6ad9,aa72017..b95dc3d
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
@@@ -524,21 -524,26 +524,26 @@@ public class PortableClassDescriptor 
  
              case PORTABLE:
                  if (writeHeader(obj, writer)) {
-                     if (serializer != null)
-                         serializer.writeBinary(obj, writer);
-                     else
-                         ((Binarylizable)obj).writeBinary(writer);
+                     try {
+                         if (serializer != null)
 -                            serializer.writePortable(obj, writer);
++                            serializer.writeBinary(obj, writer);
+                         else
 -                            ((PortableMarshalAware) obj).writePortable(writer);
++                            ((Binarylizable)obj).writeBinary(writer);
  
-                     writer.postWrite(userType);
+                         writer.postWrite(userType);
+                     }
+                     finally {
+                         writer.popSchema();
+                     }
  
 -                    if (obj.getClass() != PortableMetaDataImpl.class
 +                    if (obj.getClass() != BinaryMetaDataImpl.class
                          && ctx.isMetaDataChanged(typeId, writer.metaDataHashSum())) {
 -                        PortableMetaDataCollector metaCollector = new PortableMetaDataCollector(typeName);
 +                        BinaryMetaDataCollector metaCollector = new BinaryMetaDataCollector(typeName);
  
                          if (serializer != null)
 -                            serializer.writePortable(obj, metaCollector);
 +                            serializer.writeBinary(obj, metaCollector);
                          else
 -                            ((PortableMarshalAware)obj).writePortable(metaCollector);
 +                            ((Binarylizable)obj).writeBinary(metaCollector);
  
                          ctx.updateMetaData(typeId, typeName, metaCollector.meta());
                      }
@@@ -552,12 -557,15 +557,15 @@@
  
                      try {
                          ((Externalizable)obj).writeExternal(writer);
+ 
+                         writer.postWrite(userType);
                      }
                      catch (IOException e) {
 -                        throw new PortableException("Failed to write Externalizable object: " + obj, e);
 +                        throw new BinaryObjectException("Failed to write Externalizable object: " + obj, e);
                      }
- 
-                     writer.postWrite(userType);
+                     finally {
+                         writer.popSchema();
+                     }
                  }
  
                  break;

http://git-wip-us.apache.org/repos/asf/ignite/blob/c050b4ce/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/ignite/blob/c050b4ce/modules/core/src/main/java/org/apache/ignite/internal/portable/builder/BinaryObjectBuilderImpl.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/portable/builder/BinaryObjectBuilderImpl.java
index e6a68c1,0000000..a809d3c
mode 100644,000000..100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/builder/BinaryObjectBuilderImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/builder/BinaryObjectBuilderImpl.java
@@@ -1,551 -1,0 +1,566 @@@
 +/*
 + * 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.portable.builder;
 +
 +import java.util.Collections;
 +import java.util.HashMap;
 +import java.util.LinkedHashMap;
 +import java.util.Map;
 +import java.util.Set;
 +import org.apache.ignite.binary.BinaryObject;
 +import org.apache.ignite.binary.BinaryObjectBuilder;
 +import org.apache.ignite.binary.BinaryObjectException;
 +import org.apache.ignite.binary.BinaryInvalidTypeException;
 +import org.apache.ignite.binary.BinaryType;
 +import org.apache.ignite.internal.portable.BinaryObjectImpl;
 +import org.apache.ignite.internal.portable.BinaryObjectOffheapImpl;
 +import org.apache.ignite.internal.portable.BinaryWriterExImpl;
 +import org.apache.ignite.internal.portable.PortableContext;
 +import org.apache.ignite.internal.portable.PortableUtils;
 +import org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessorImpl;
 +import org.apache.ignite.internal.util.GridArgumentCheck;
 +import org.apache.ignite.internal.util.typedef.F;
 +import org.apache.ignite.internal.util.typedef.internal.U;
 +import org.apache.ignite.lang.IgniteBiTuple;
 +import org.jetbrains.annotations.Nullable;
 +
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DFLT_HDR_LEN;
++import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLAGS_POS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.HASH_CODE_POS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.PROTO_VER_POS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.TYPE_ID_POS;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.UNREGISTERED_TYPE_ID;
 +
 +/**
 + *
 + */
 +public class BinaryObjectBuilderImpl implements BinaryObjectBuilder {
 +    /** */
 +    private static final Object REMOVED_FIELD_MARKER = new Object();
 +
 +    /** */
 +    private final PortableContext ctx;
 +
 +    /** */
 +    private final int typeId;
 +
 +    /** May be null. */
 +    private String typeName;
 +
 +    /** May be null. */
 +    private String clsNameToWrite;
 +
 +    /** */
 +    private boolean registeredType = true;
 +
 +    /** */
 +    private Map<String, Object> assignedVals;
 +
 +    /** */
 +    private Map<Integer, Object> readCache;
 +
 +    /** Position of object in source array, or -1 if object is not created from PortableObject. */
 +    private final int start;
 +
++    /** Flags. */
++    private final short flags;
++
 +    /** Total header length */
 +    private final int hdrLen;
 +
-     /**
-      * Context of PortableObject reading process. Or {@code null} if object is not created from PortableObject.
-      */
++    /** Context of PortableObject reading process. Or {@code null} if object is not created from PortableObject. */
 +    private final PortableBuilderReader reader;
 +
 +    /** */
 +    private int hashCode;
 +
 +    /**
 +     * @param clsName Class name.
 +     * @param ctx Portable context.
 +     */
 +    public BinaryObjectBuilderImpl(PortableContext ctx, String clsName) {
 +        this(ctx, ctx.typeId(clsName), PortableContext.typeName(clsName));
 +    }
 +
 +    /**
 +     * @param typeId Type ID.
 +     * @param ctx Portable context.
 +     */
 +    public BinaryObjectBuilderImpl(PortableContext ctx, int typeId) {
 +        this(ctx, typeId, null);
 +    }
 +
 +    /**
 +     * @param typeName Type name.
 +     * @param ctx Context.
 +     * @param typeId Type id.
 +     */
 +    public BinaryObjectBuilderImpl(PortableContext ctx, int typeId, String typeName) {
 +        this.typeId = typeId;
 +        this.typeName = typeName;
 +        this.ctx = ctx;
 +
 +        start = -1;
++        flags = -1;
 +        reader = null;
 +        hdrLen = DFLT_HDR_LEN;
 +
 +        readCache = Collections.emptyMap();
 +    }
 +
 +    /**
 +     * @param obj Object to wrap.
 +     */
 +    public BinaryObjectBuilderImpl(BinaryObjectImpl obj) {
 +        this(new PortableBuilderReader(obj), obj.start());
 +
 +        reader.registerObject(this);
 +    }
 +
 +    /**
 +     * @param reader ctx
 +     * @param start Start.
 +     */
 +    BinaryObjectBuilderImpl(PortableBuilderReader reader, int start) {
 +        this.reader = reader;
 +        this.start = start;
++        this.flags = reader.readShortPositioned(start + FLAGS_POS);
 +
 +        byte ver = reader.readBytePositioned(start + PROTO_VER_POS);
 +
 +        PortableUtils.checkProtocolVersion(ver);
 +
 +        int typeId = reader.readIntPositioned(start + TYPE_ID_POS);
 +        ctx = reader.portableContext();
 +        hashCode = reader.readIntPositioned(start + HASH_CODE_POS);
 +
 +        if (typeId == UNREGISTERED_TYPE_ID) {
 +            int mark = reader.position();
 +
 +            reader.position(start + DFLT_HDR_LEN);
 +
 +            clsNameToWrite = reader.readString();
 +
 +            Class cls;
 +
 +            try {
 +                // TODO: IGNITE-1272 - Is class loader needed here?
 +                cls = U.forName(clsNameToWrite, null);
 +            }
 +            catch (ClassNotFoundException e) {
 +                throw new BinaryInvalidTypeException("Failed to load the class: " + clsNameToWrite, e);
 +            }
 +
 +            this.typeId = ctx.descriptorForClass(cls).typeId();
 +
 +            registeredType = false;
 +
 +            hdrLen = reader.position() - mark;
 +
 +            reader.position(mark);
 +        }
 +        else {
 +            this.typeId = typeId;
 +            hdrLen = DFLT_HDR_LEN;
 +        }
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryObject build() {
 +        try (BinaryWriterExImpl writer = new BinaryWriterExImpl(ctx, typeId, false)) {
 +
 +            PortableBuilderSerializer serializationCtx = new PortableBuilderSerializer();
 +
 +            serializationCtx.registerObjectWriting(this, 0);
 +
 +            serializeTo(writer, serializationCtx);
 +
 +            byte[] arr = writer.array();
 +
 +            return new BinaryObjectImpl(ctx, arr, 0);
 +        }
 +    }
 +
 +    /**
 +     * @param writer Writer.
 +     * @param serializer Serializer.
 +     */
 +    void serializeTo(BinaryWriterExImpl writer, PortableBuilderSerializer serializer) {
-         PortableUtils.writeHeader(writer,
-             true,
-             registeredType ? typeId : UNREGISTERED_TYPE_ID,
-             hashCode,
-             registeredType ? null : clsNameToWrite);
++        try {
++            PortableUtils.writeHeader(writer,
++                true,
++                registeredType ? typeId : UNREGISTERED_TYPE_ID,
++                hashCode,
++                registeredType ? null : clsNameToWrite);
 +
-         Set<Integer> remainsFlds = null;
++            Set<Integer> remainsFlds = null;
 +
-         if (reader != null) {
-             Map<Integer, Object> assignedFldsById;
++            if (reader != null) {
++                Map<Integer, Object> assignedFldsById;
 +
-             if (assignedVals != null) {
-                 assignedFldsById = U.newHashMap(assignedVals.size());
++                if (assignedVals != null) {
++                    assignedFldsById = U.newHashMap(assignedVals.size());
 +
-                 for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
-                     int fldId = ctx.fieldId(typeId, entry.getKey());
++                    for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
++                        int fldId = ctx.fieldId(typeId, entry.getKey());
 +
-                     assignedFldsById.put(fldId, entry.getValue());
-                 }
++                        assignedFldsById.put(fldId, entry.getValue());
++                    }
 +
-                 remainsFlds = assignedFldsById.keySet();
-             }
-             else
-                 assignedFldsById = Collections.emptyMap();
++                    remainsFlds = assignedFldsById.keySet();
++                } else
++                    assignedFldsById = Collections.emptyMap();
 +
-             // Get footer details.
-             IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(reader, start);
++                // Get footer details.
++                int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
 +
-             int footerPos = footer.get1();
-             int footerEnd = footer.get2();
++                IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(reader, start, fieldOffsetSize);
 +
-             // Get raw position.
-             int rawPos = PortableUtils.rawOffsetAbsolute(reader, start);
++                int footerPos = footer.get1();
++                int footerEnd = footer.get2();
 +
-             // Position reader on data.
-             reader.position(start + hdrLen);
++                // Get raw position.
++                int rawPos = PortableUtils.rawOffsetAbsolute(reader, start, fieldOffsetSize);
 +
-             while (reader.position() < rawPos) {
-                 int fieldId = reader.readIntPositioned(footerPos);
-                 int fieldLen = fieldPositionAndLength(footerPos, footerEnd, rawPos).get2();
++                // Position reader on data.
++                reader.position(start + hdrLen);
 +
-                 footerPos += 8;
++                while (reader.position() + 4 < rawPos) {
++                    int fieldId = reader.readIntPositioned(footerPos);
++                    int fieldLen = fieldPositionAndLength(footerPos, footerEnd, rawPos, fieldOffsetSize).get2();
 +
-                 if (assignedFldsById.containsKey(fieldId)) {
-                     Object assignedVal = assignedFldsById.remove(fieldId);
++                    footerPos += 4 + fieldOffsetSize;
 +
-                     reader.skip(fieldLen);
++                    if (assignedFldsById.containsKey(fieldId)) {
++                        Object assignedVal = assignedFldsById.remove(fieldId);
 +
-                     if (assignedVal != REMOVED_FIELD_MARKER) {
-                         writer.writeFieldId(fieldId);
++                        reader.skip(fieldLen);
 +
-                         serializer.writeValue(writer, assignedVal);
-                     }
-                 }
-                 else {
-                     int type = fieldLen != 0 ? reader.readByte(0) : 0;
++                        if (assignedVal != REMOVED_FIELD_MARKER) {
++                            writer.writeFieldId(fieldId);
 +
-                     if (fieldLen != 0 && !PortableUtils.isPlainArrayType(type) && PortableUtils.isPlainType(type)) {
-                         writer.writeFieldId(fieldId);
-                         writer.write(reader.array(), reader.position(), fieldLen);
++                            serializer.writeValue(writer, assignedVal);
++                        }
++                    } else {
++                        int type = fieldLen != 0 ? reader.readByte(0) : 0;
 +
-                         reader.skip(fieldLen);
-                     }
-                     else {
-                         writer.writeFieldId(fieldId);
++                        if (fieldLen != 0 && !PortableUtils.isPlainArrayType(type) && PortableUtils.isPlainType(type)) {
++                            writer.writeFieldId(fieldId);
++                            writer.write(reader.array(), reader.position(), fieldLen);
 +
-                         Object val;
++                            reader.skip(fieldLen);
++                        } else {
++                            writer.writeFieldId(fieldId);
 +
-                         if (fieldLen == 0)
-                             val = null;
-                         else if (readCache == null) {
-                             int savedPos = reader.position();
++                            Object val;
 +
-                             val = reader.parseValue();
++                            if (fieldLen == 0)
++                                val = null;
++                            else if (readCache == null) {
++                                int savedPos = reader.position();
 +
-                             assert reader.position() == savedPos + fieldLen;
-                         }
-                         else {
-                             val = readCache.get(fieldId);
++                                val = reader.parseValue();
 +
-                             reader.skip(fieldLen);
-                         }
++                                assert reader.position() == savedPos + fieldLen;
++                            } else {
++                                val = readCache.get(fieldId);
++
++                                reader.skip(fieldLen);
++                            }
 +
-                         serializer.writeValue(writer, val);
++                            serializer.writeValue(writer, val);
++                        }
 +                    }
 +                }
 +            }
-         }
- 
-         if (assignedVals != null && (remainsFlds == null || !remainsFlds.isEmpty())) {
-             boolean metadataEnabled = ctx.isMetaDataEnabled(typeId);
 +
-             BinaryType metadata = null;
++            if (assignedVals != null && (remainsFlds == null || !remainsFlds.isEmpty())) {
++                boolean metadataEnabled = ctx.isMetaDataEnabled(typeId);
 +
-             if (metadataEnabled)
-                 metadata = ctx.metaData(typeId);
++                BinaryType metadata = null;
 +
-             Map<String, String> newFldsMetadata = null;
++                if (metadataEnabled)
++                    metadata = ctx.metaData(typeId);
 +
-             for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
-                 Object val = entry.getValue();
++                Map<String, String> newFldsMetadata = null;
 +
-                 if (val == REMOVED_FIELD_MARKER)
-                     continue;
- 
-                 String name = entry.getKey();
++                for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
++                    Object val = entry.getValue();
 +
-                 int fldId = ctx.fieldId(typeId, name);
++                    if (val == REMOVED_FIELD_MARKER)
++                        continue;
 +
-                 if (remainsFlds != null && !remainsFlds.contains(fldId))
-                     continue;
++                    String name = entry.getKey();
 +
-                 writer.writeFieldId(fldId);
++                    int fldId = ctx.fieldId(typeId, name);
 +
-                 serializer.writeValue(writer, val);
++                    if (remainsFlds != null && !remainsFlds.contains(fldId))
++                        continue;
 +
-                 if (metadataEnabled) {
-                     String oldFldTypeName = metadata == null ? null : metadata.fieldTypeName(name);
++                    writer.writeFieldId(fldId);
 +
-                     String newFldTypeName;
++                    serializer.writeValue(writer, val);
 +
-                     if (val instanceof PortableValueWithType)
-                         newFldTypeName = ((PortableValueWithType)val).typeName();
-                     else {
-                         byte type = PortableUtils.typeByClass(val.getClass());
++                    if (metadataEnabled) {
++                        String oldFldTypeName = metadata == null ? null : metadata.fieldTypeName(name);
 +
-                         newFldTypeName = CacheObjectPortableProcessorImpl.fieldTypeName(type);
-                     }
++                        String newFldTypeName;
 +
-                     if (oldFldTypeName == null) {
-                         // It's a new field, we have to add it to metadata.
++                        if (val instanceof PortableValueWithType)
++                            newFldTypeName = ((PortableValueWithType) val).typeName();
++                        else {
++                            byte type = PortableUtils.typeByClass(val.getClass());
 +
-                         if (newFldsMetadata == null)
-                             newFldsMetadata = new HashMap<>();
++                            newFldTypeName = CacheObjectPortableProcessorImpl.fieldTypeName(type);
++                        }
 +
-                         newFldsMetadata.put(name, newFldTypeName);
-                     }
-                     else {
-                         if (!"Object".equals(oldFldTypeName) && !oldFldTypeName.equals(newFldTypeName)) {
-                             throw new BinaryObjectException(
-                                 "Wrong value has been set [" +
-                                     "typeName=" + (typeName == null ? metadata.typeName() : typeName) +
-                                     ", fieldName=" + name +
-                                     ", fieldType=" + oldFldTypeName +
-                                     ", assignedValueType=" + newFldTypeName +
-                                     ", assignedValue=" + (((PortableValueWithType)val).value()) + ']'
-                             );
++                        if (oldFldTypeName == null) {
++                            // It's a new field, we have to add it to metadata.
++
++                            if (newFldsMetadata == null)
++                                newFldsMetadata = new HashMap<>();
++
++                            newFldsMetadata.put(name, newFldTypeName);
++                        } else {
++                            if (!"Object".equals(oldFldTypeName) && !oldFldTypeName.equals(newFldTypeName)) {
++                                throw new BinaryObjectException(
++                                    "Wrong value has been set [" +
++                                        "typeName=" + (typeName == null ? metadata.typeName() : typeName) +
++                                        ", fieldName=" + name +
++                                        ", fieldType=" + oldFldTypeName +
++                                        ", assignedValueType=" + newFldTypeName +
++                                        ", assignedValue=" + (((PortableValueWithType) val).value()) + ']'
++                                );
++                            }
 +                        }
 +                    }
 +                }
-             }
 +
-             if (newFldsMetadata != null) {
-                 String typeName = this.typeName;
++                if (newFldsMetadata != null) {
++                    String typeName = this.typeName;
 +
-                 if (typeName == null)
-                     typeName = metadata.typeName();
++                    if (typeName == null)
++                        typeName = metadata.typeName();
 +
-                 ctx.updateMetaData(typeId, typeName, newFldsMetadata);
++                    ctx.updateMetaData(typeId, typeName, newFldsMetadata);
++                }
 +            }
-         }
 +
-         if (reader != null) {
-             // Write raw data if any.
-             int rawOff = PortableUtils.rawOffsetAbsolute(reader, start);
-             int footerStart = PortableUtils.footerStartAbsolute(reader, start);
++            if (reader != null) {
++                // Write raw data if any.
++                int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
++
++                int rawOff = PortableUtils.rawOffsetAbsolute(reader, start, fieldOffsetSize);
++                int footerStart = PortableUtils.footerStartAbsolute(reader, start);
 +
-             if (rawOff < footerStart) {
-                 writer.rawWriter();
++                if (rawOff < footerStart) {
++                    writer.rawWriter();
 +
-                 writer.write(reader.array(), rawOff, footerStart - rawOff);
++                    writer.write(reader.array(), rawOff, footerStart - rawOff);
++                }
++
++                // Shift reader to the end of the object.
++                reader.position(start + PortableUtils.length(reader, start));
 +            }
 +
-             // Shift reader to the end of the object.
-             reader.position(start + PortableUtils.length(reader, start));
++            writer.postWrite(true);
++        }
++        finally {
++            writer.popSchema();
 +        }
- 
-         writer.postWrite(true);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryObjectBuilderImpl hashCode(int hashCode) {
 +        this.hashCode = hashCode;
 +
 +        return this;
 +    }
 +
 +    /**
 +     * Get field position and length.
 +     *
 +     * @param footerPos Field position inside the footer (absolute).
 +     * @param footerEnd Footer end (absolute).
 +     * @param rawPos Raw data position (absolute).
++     * @param fieldOffsetSize Size of field's offset.
 +     * @return Tuple with field position and length.
 +     */
-     private IgniteBiTuple<Integer, Integer> fieldPositionAndLength(int footerPos, int footerEnd, int rawPos) {
-         int fieldOffset = reader.readIntPositioned(footerPos + 4);
++    private IgniteBiTuple<Integer, Integer> fieldPositionAndLength(int footerPos, int footerEnd, int rawPos,
++        int fieldOffsetSize) {
++        // Get field offset first.
++        int fieldOffset = PortableUtils.fieldOffsetRelative(reader, footerPos + 4, fieldOffsetSize);
 +        int fieldPos = start + fieldOffset;
 +
 +        // Get field length.
 +        int fieldLen;
 +
-         if (footerPos + 8 == footerEnd)
++        if (footerPos + 4 + fieldOffsetSize == footerEnd)
 +            // This is the last field, compare to raw offset.
 +            fieldLen = rawPos - fieldPos;
 +        else {
 +            // Field is somewhere in the middle, get difference with the next offset.
-             int nextFieldOffset = reader.readIntPositioned(footerPos + 8 + 4);
++            int nextFieldOffset = PortableUtils.fieldOffsetRelative(reader, footerPos + 4 + fieldOffsetSize + 4,
++                fieldOffsetSize);
 +
 +            fieldLen = nextFieldOffset - fieldOffset;
 +        }
 +
 +        return F.t(fieldPos, fieldLen);
 +    }
 +
 +    /**
 +     * Initialize read cache if needed.
 +     */
 +    private void ensureReadCacheInit() {
 +        if (readCache == null) {
++            int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
++
 +            Map<Integer, Object> readCache = new HashMap<>();
 +
-             IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(reader, start);
++            IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(reader, start, fieldOffsetSize);
 +
 +            int footerPos = footer.get1();
 +            int footerEnd = footer.get2();
 +
-             int rawPos = PortableUtils.rawOffsetAbsolute(reader, start);
++            int rawPos = PortableUtils.rawOffsetAbsolute(reader, start, fieldOffsetSize);
 +
-             while (footerPos < footerEnd) {
++            while (footerPos + 4 < footerEnd) {
 +                int fieldId = reader.readIntPositioned(footerPos);
 +
-                 IgniteBiTuple<Integer, Integer> posAndLen = fieldPositionAndLength(footerPos, footerEnd, rawPos);
++                IgniteBiTuple<Integer, Integer> posAndLen =
++                    fieldPositionAndLength(footerPos, footerEnd, rawPos, fieldOffsetSize);
 +
 +                Object val = reader.getValueQuickly(posAndLen.get1(), posAndLen.get2());
 +
 +                readCache.put(fieldId, val);
 +
 +                // Shift current footer position.
-                 footerPos += 8;
++                footerPos += 4 + fieldOffsetSize;
 +            }
 +
 +            this.readCache = readCache;
 +        }
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Override public <T> T getField(String name) {
 +        Object val;
 +
 +        if (assignedVals != null && assignedVals.containsKey(name)) {
 +            val = assignedVals.get(name);
 +
 +            if (val == REMOVED_FIELD_MARKER)
 +                return null;
 +        }
 +        else {
 +            ensureReadCacheInit();
 +
 +            int fldId = ctx.fieldId(typeId, name);
 +
 +            val = readCache.get(fldId);
 +        }
 +
 +        return (T)PortableUtils.unwrapLazy(val);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryObjectBuilder setField(String name, Object val) {
 +        GridArgumentCheck.notNull(val, name);
 +
 +        if (assignedVals == null)
 +            assignedVals = new LinkedHashMap<>();
 +
 +        Object oldVal = assignedVals.put(name, val);
 +
 +        if (oldVal instanceof PortableValueWithType) {
 +            ((PortableValueWithType)oldVal).value(val);
 +
 +            assignedVals.put(name, oldVal);
 +        }
 +
 +        return this;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public <T> BinaryObjectBuilder setField(String name, @Nullable T val, Class<? super T> type) {
 +        if (assignedVals == null)
 +            assignedVals = new LinkedHashMap<>();
 +
 +        //int fldId = ctx.fieldId(typeId, fldName);
 +
 +        assignedVals.put(name, new PortableValueWithType(PortableUtils.typeByClass(type), val));
 +
 +        return this;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryObjectBuilder setField(String name, @Nullable BinaryObjectBuilder builder) {
 +        if (builder == null)
 +            return setField(name, null, Object.class);
 +        else
 +            return setField(name, (Object)builder);
 +    }
 +
 +    /**
 +     * Removes field from portable object.
 +     *
 +     * @param name Field name.
 +     * @return {@code this} instance for chaining.
 +     */
 +    @Override public BinaryObjectBuilderImpl removeField(String name) {
 +        if (assignedVals == null)
 +            assignedVals = new LinkedHashMap<>();
 +
 +        assignedVals.put(name, REMOVED_FIELD_MARKER);
 +
 +        return this;
 +    }
 +
 +    /**
 +     * Creates builder initialized by specified portable object.
 +     *
 +     * @param obj Portable object to initialize builder.
 +     * @return New builder.
 +     */
 +    public static BinaryObjectBuilderImpl wrap(BinaryObject obj) {
 +        BinaryObjectImpl heapObj;
 +
 +        if (obj instanceof BinaryObjectOffheapImpl)
 +            heapObj = (BinaryObjectImpl)((BinaryObjectOffheapImpl)obj).heapCopy();
 +        else
 +            heapObj = (BinaryObjectImpl)obj;
 +
 +        return new BinaryObjectBuilderImpl(heapObj);
 +    }
 +
 +    /**
 +     * @return Object start position in source array.
 +     */
 +    int start() {
 +        return start;
 +    }
 +
 +    /**
 +     * @return Object type id.
 +     */
 +    public int typeId() {
 +        return typeId;
 +    }
 +}


[5/5] ignite git commit: Merge branch ignite-1282 into ignite-950-new

Posted by ag...@apache.org.
Merge branch ignite-1282  into ignite-950-new


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/c050b4ce
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/c050b4ce
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/c050b4ce

Branch: refs/heads/ignite-950-new
Commit: c050b4ce6cb27fce48e0cae1f9a78f99c7d6ee3f
Parents: 7b9136e 845c4f2
Author: Alexey Goncharuk <al...@gmail.com>
Authored: Tue Nov 3 13:30:14 2015 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Tue Nov 3 13:30:14 2015 +0300

----------------------------------------------------------------------
 .gitignore                                      |   7 +
 .../internal/portable/BinaryFieldImpl.java      |  10 +-
 .../internal/portable/BinaryObjectEx.java       |   2 +-
 .../internal/portable/BinaryObjectImpl.java     |  46 ++-
 .../portable/BinaryObjectOffheapImpl.java       |  89 +++++-
 .../internal/portable/BinaryReaderExImpl.java   |  43 +--
 .../internal/portable/BinaryWriterExImpl.java   |  76 ++++-
 .../portable/PortableClassDescriptor.java       |  33 ++-
 .../internal/portable/PortableSchema.java       | 133 ++++-----
 .../ignite/internal/portable/PortableUtils.java |  46 ++-
 .../builder/BinaryObjectBuilderImpl.java        | 283 ++++++++++---------
 .../src/portable_reader_writer_test.cpp         | 251 +++++++++++++---
 .../ignite/impl/interop/interop_input_stream.h  |  16 ++
 .../ignite/impl/interop/interop_output_stream.h |   8 +
 .../ignite/impl/portable/portable_common.h      |   6 +
 .../ignite/impl/portable/portable_reader_impl.h |  29 +-
 .../ignite/impl/portable/portable_schema.h      |  26 +-
 .../src/impl/interop/interop_input_stream.cpp   |  20 ++
 .../src/impl/interop/interop_output_stream.cpp  |   7 +
 .../src/impl/portable/portable_reader_impl.cpp  |  45 ++-
 .../core/src/impl/portable/portable_schema.cpp  |  53 +++-
 .../src/impl/portable/portable_writer_impl.cpp  |  21 +-
 .../Portable/PortableSelfTest.cs                |  32 +++
 .../Impl/Common/ResizeableArray.cs              |  14 +-
 .../Apache.Ignite.Core/Impl/ExceptionUtils.cs   |   2 -
 .../Impl/Portable/PortableBuilderImpl.cs        |   8 +-
 .../Impl/Portable/PortableObjectHeader.cs       | 196 ++++++++++---
 .../Impl/Portable/PortableObjectSchema.cs       |   6 +-
 .../Impl/Portable/PortableObjectSchemaField.cs  |  69 +----
 .../Impl/Portable/PortableReaderImpl.cs         | 113 +++-----
 .../Impl/Portable/PortableUtils.cs              |   4 +-
 .../Impl/Portable/PortableWriterImpl.cs         |   7 +-
 .../Impl/Portable/PortablesImpl.cs              |   2 +-
 .../Impl/Unmanaged/UnmanagedCallbackHandlers.cs |   2 +-
 34 files changed, 1146 insertions(+), 559 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/c050b4ce/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryFieldImpl.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryFieldImpl.java
index da60a8b,0000000..ac0b353
mode 100644,000000..100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryFieldImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryFieldImpl.java
@@@ -1,82 -1,0 +1,82 @@@
 +/*
 + * 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.portable;
 +
 +import org.apache.ignite.binary.BinaryObject;
 +import org.apache.ignite.binary.BinaryField;
 +
 +/**
 + * Implementation of portable field descriptor.
 + */
 +public class BinaryFieldImpl implements BinaryField {
 +    /** Well-known object schemas. */
 +    private final PortableSchemaRegistry schemas;
 +
 +    /** Pre-calculated field ID. */
 +    private final int fieldId;
 +
 +    /**
 +     * Constructor.
 +     *
 +     * @param schemas Schemas.
 +     * @param fieldId Field ID.
 +     */
 +    public BinaryFieldImpl(PortableSchemaRegistry schemas, int fieldId) {
 +        this.schemas = schemas;
 +        this.fieldId = fieldId;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean exists(BinaryObject obj) {
 +        BinaryObjectEx obj0 = (BinaryObjectEx)obj;
 +
-         return fieldOffset(obj0) != 0;
++        return fieldOrder(obj0) != 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Override public <T> T value(BinaryObject obj) {
 +        BinaryObjectEx obj0 = (BinaryObjectEx)obj;
 +
-         int offset = fieldOffset(obj0);
++        int order = fieldOrder(obj0);
 +
-         return offset != 0 ? (T)obj0.fieldByOffset(offset) : null;
++        return order != 0 ? (T)obj0.fieldByOrder(order) : null;
 +    }
 +
 +    /**
 +     * Get relative field offset.
 +     *
 +     * @param obj Object.
 +     * @return Field offset.
 +     */
-     private int fieldOffset(BinaryObjectEx obj) {
++    private int fieldOrder(BinaryObjectEx obj) {
 +        int schemaId = obj.schemaId();
 +
 +        PortableSchema schema = schemas.schema(schemaId);
 +
 +        if (schema == null) {
 +            schema = obj.createSchema();
 +
 +            schemas.addSchema(schemaId, schema);
 +        }
 +
 +        assert schema != null;
 +
-         return schema.offset(fieldId);
++        return schema.order(fieldId);
 +    }
 +}

http://git-wip-us.apache.org/repos/asf/ignite/blob/c050b4ce/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectEx.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectEx.java
index aadaca8,0000000..bfbb997
mode 100644,000000..100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectEx.java
@@@ -1,245 -1,0 +1,245 @@@
 +/*
 + * 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.portable;
 +
 +import java.math.BigDecimal;
 +import java.util.Arrays;
 +import java.util.IdentityHashMap;
 +import org.apache.ignite.IgniteException;
 +import org.apache.ignite.internal.util.offheap.unsafe.GridUnsafeMemory;
 +import org.apache.ignite.internal.util.typedef.internal.SB;
 +import org.apache.ignite.binary.BinaryObjectException;
 +import org.apache.ignite.binary.BinaryType;
 +import org.apache.ignite.binary.BinaryObject;
 +import org.jetbrains.annotations.Nullable;
 +
 +/**
 + * Internal portable object interface.
 + */
 +public abstract class BinaryObjectEx implements BinaryObject {
 +    /**
 +     * @return Length.
 +     */
 +    public abstract int length();
 +
 +    /**
 +     * @return Object start.
 +     */
 +    public abstract int start();
 +
 +    /**
 +     * @return {@code True} if object is array based.
 +     */
 +    protected abstract boolean hasArray();
 +
 +    /**
 +     * @return Object array if object is array based, otherwise {@code null}.
 +     */
 +    public abstract byte[] array();
 +
 +    /**
 +     * @return Object offheap address is object is offheap based, otherwise 0.
 +     */
 +    public abstract long offheapAddress();
 +
 +    /**
 +     * Gets field value.
 +     *
 +     * @param fieldId Field ID.
 +     * @return Field value.
 +     * @throws org.apache.ignite.binary.BinaryObjectException In case of any other error.
 +     */
 +    @Nullable public abstract <F> F field(int fieldId) throws BinaryObjectException;
 +
 +    /**
 +     * Get field by offset.
 +     *
 +     * @param fieldOffset Field offset.
 +     * @return Field value.
 +     */
-     @Nullable protected abstract <F> F fieldByOffset(int fieldOffset);
++    @Nullable protected abstract <F> F fieldByOrder(int fieldOffset);
 +
 +    /**
 +     * @param ctx Reader context.
 +     * @param fieldName Field name.
 +     * @return Field value.
 +     */
 +    @Nullable protected abstract <F> F field(PortableReaderContext ctx, String fieldName);
 +
 +    /**
 +     * Get schema ID.
 +     *
 +     * @return Schema ID.
 +     */
 +    protected abstract int schemaId();
 +
 +    /**
 +     * Create schema for object.
 +     *
 +     * @return Schema.
 +     */
 +    protected abstract PortableSchema createSchema();
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryObject clone() throws CloneNotSupportedException {
 +        return (BinaryObject)super.clone();
 +    }
 +
 +    /** {@inheritDoc} */
 +    public boolean equals(Object other) {
 +        if (other == this)
 +            return true;
 +
 +        if (other == null)
 +            return false;
 +
 +        if (!(other instanceof BinaryObjectEx))
 +            return false;
 +
 +        BinaryObjectEx otherPo = (BinaryObjectEx)other;
 +
 +        if (length() != otherPo.length() || typeId() != otherPo.typeId())
 +            return false;
 +
 +        if (hasArray()) {
 +            if (otherPo.hasArray()) {
 +                int len = length();
 +                int end = start() + len;
 +
 +                byte[] arr = array();
 +                byte[] otherArr = otherPo.array();
 +
 +                for (int i = start(), j = otherPo.start(); i < end; i++, j++) {
 +                    if (arr[i] != otherArr[j])
 +                        return false;
 +                }
 +
 +                return true;
 +            }
 +            else {
 +                assert otherPo.offheapAddress() > 0;
 +
 +                return GridUnsafeMemory.compare(otherPo.offheapAddress() + otherPo.start(), array());
 +            }
 +        }
 +        else {
 +            assert offheapAddress() > 0;
 +
 +            if (otherPo.hasArray())
 +                return GridUnsafeMemory.compare(offheapAddress() + start(), otherPo.array());
 +            else {
 +                assert otherPo.offheapAddress() > 0;
 +
 +                return GridUnsafeMemory.compare(offheapAddress() + start(),
 +                    otherPo.offheapAddress() + otherPo.start(),
 +                    length());
 +            }
 +        }
 +    }
 +
 +    /**
 +     * @param ctx Reader context.
 +     * @param handles Handles for already traversed objects.
 +     * @return String representation.
 +     */
 +    private String toString(PortableReaderContext ctx, IdentityHashMap<BinaryObject, Integer> handles) {
 +        int idHash = System.identityHashCode(this);
 +
 +        BinaryType meta;
 +
 +        try {
 +            meta = metaData();
 +        }
 +        catch (BinaryObjectException ignore) {
 +            meta = null;
 +        }
 +
 +        if (meta == null)
 +            return "PortableObject [hash=" + idHash + ", typeId=" + typeId() + ']';
 +
 +        handles.put(this, idHash);
 +
 +        SB buf = new SB(meta.typeName());
 +
 +        if (meta.fields() != null) {
 +            buf.a(" [hash=").a(idHash);
 +
 +            for (String name : meta.fields()) {
 +                Object val = field(ctx, name);
 +
 +                buf.a(", ").a(name).a('=');
 +
 +                if (val instanceof byte[])
 +                    buf.a(Arrays.toString((byte[]) val));
 +                else if (val instanceof short[])
 +                    buf.a(Arrays.toString((short[])val));
 +                else if (val instanceof int[])
 +                    buf.a(Arrays.toString((int[])val));
 +                else if (val instanceof long[])
 +                    buf.a(Arrays.toString((long[])val));
 +                else if (val instanceof float[])
 +                    buf.a(Arrays.toString((float[])val));
 +                else if (val instanceof double[])
 +                    buf.a(Arrays.toString((double[])val));
 +                else if (val instanceof char[])
 +                    buf.a(Arrays.toString((char[])val));
 +                else if (val instanceof boolean[])
 +                    buf.a(Arrays.toString((boolean[]) val));
 +                else if (val instanceof BigDecimal[])
 +                    buf.a(Arrays.toString((BigDecimal[])val));
 +                else {
 +                    if (val instanceof BinaryObjectEx) {
 +                        BinaryObjectEx po = (BinaryObjectEx)val;
 +
 +                        Integer idHash0 = handles.get(val);
 +
 +                        if (idHash0 != null) {  // Circular reference.
 +                            BinaryType meta0 = po.metaData();
 +
 +                            assert meta0 != null;
 +
 +                            buf.a(meta0.typeName()).a(" [hash=").a(idHash0).a(", ...]");
 +                        }
 +                        else
 +                            buf.a(po.toString(ctx, handles));
 +                    }
 +                    else
 +                        buf.a(val);
 +                }
 +            }
 +
 +            buf.a(']');
 +        }
 +
 +        return buf.toString();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public String toString() {
 +        try {
 +            PortableReaderContext ctx = new PortableReaderContext();
 +
 +            ctx.setPortableHandler(start(), this);
 +
 +            return toString(ctx, new IdentityHashMap<BinaryObject, Integer>());
 +        }
 +        catch (BinaryObjectException e) {
 +            throw new IgniteException("Failed to create string representation of portable object.", e);
 +        }
 +    }
 +}

http://git-wip-us.apache.org/repos/asf/ignite/blob/c050b4ce/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectImpl.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectImpl.java
index d533c22,0000000..992f92c
mode 100644,000000..100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectImpl.java
@@@ -1,538 -1,0 +1,526 @@@
 +/*
 + * 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.portable;
 +
 +import org.apache.ignite.IgniteCheckedException;
 +import org.apache.ignite.internal.GridDirectTransient;
 +import org.apache.ignite.internal.IgniteCodeGeneratingFail;
 +import org.apache.ignite.internal.portable.streams.PortableHeapInputStream;
 +import org.apache.ignite.internal.processors.cache.CacheObject;
 +import org.apache.ignite.internal.processors.cache.CacheObjectContext;
 +import org.apache.ignite.internal.processors.cache.KeyCacheObject;
 +import org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessorImpl;
 +import org.apache.ignite.internal.util.typedef.internal.U;
 +import org.apache.ignite.plugin.extensions.communication.Message;
 +import org.apache.ignite.plugin.extensions.communication.MessageReader;
 +import org.apache.ignite.plugin.extensions.communication.MessageWriter;
 +import org.apache.ignite.binary.BinaryObjectException;
 +import org.apache.ignite.binary.BinaryType;
 +import org.apache.ignite.binary.BinaryObject;
 +import org.apache.ignite.binary.BinaryField;
 +import org.jetbrains.annotations.Nullable;
 +
 +import java.io.Externalizable;
 +import java.io.IOException;
 +import java.io.ObjectInput;
 +import java.io.ObjectOutput;
 +import java.nio.ByteBuffer;
 +
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BOOLEAN;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.BYTE;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.CHAR;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.DOUBLE;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLOAT;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.INT;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.LONG;
 +import static org.apache.ignite.internal.portable.GridPortableMarshaller.SHORT;
 +
 +/**
 + * Portable object implementation.
 + */
 +@IgniteCodeGeneratingFail // Fields arr and start should not be generated by MessageCodeGenerator.
 +public final class BinaryObjectImpl extends BinaryObjectEx implements Externalizable,
 +    Message, CacheObject, KeyCacheObject {
 +    /** */
 +    public static final byte TYPE_PORTABLE = 100;
 +
 +    /** */
 +    private static final long serialVersionUID = 0L;
 +
 +    /** */
 +    @GridDirectTransient
 +    private PortableContext ctx;
 +
 +    /** */
 +    private byte[] arr;
 +
 +    /** */
 +    private int start;
 +
 +    /** */
 +    @GridDirectTransient
 +    private Object obj;
 +
 +    /** */
 +    @GridDirectTransient
 +    private boolean detachAllowed;
 +
 +    /**
 +     * For {@link Externalizable}.
 +     */
 +    public BinaryObjectImpl() {
 +        // No-op.
 +    }
 +
 +    /**
 +     * @param ctx Context.
 +     * @param arr Array.
 +     * @param start Start.
 +     */
 +    public BinaryObjectImpl(PortableContext ctx, byte[] arr, int start) {
 +        assert ctx != null;
 +        assert arr != null;
 +
 +        this.ctx = ctx;
 +        this.arr = arr;
 +        this.start = start;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte type() {
 +        return TYPE_PORTABLE;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean isPlatformType() {
 +        return false;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean internal() {
 +        return false;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override public <T> T value(CacheObjectContext ctx, boolean cpy) {
 +        Object obj0 = obj;
 +
 +        if (obj0 == null || cpy)
 +            obj0 = deserializeValue();
 +
 +        return (T)obj0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte[] valueBytes(CacheObjectContext ctx) throws IgniteCheckedException {
 +        if (detached())
 +            return array();
 +
 +        int len = length();
 +
 +        byte[] arr0 = new byte[len];
 +
 +        U.arrayCopy(arr, start, arr0, 0, len);
 +
 +        return arr0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public CacheObject prepareForCache(CacheObjectContext ctx) {
 +        if (detached())
 +            return this;
 +
 +        return (BinaryObjectImpl)detach();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void finishUnmarshal(CacheObjectContext ctx, ClassLoader ldr) throws IgniteCheckedException {
 +        this.ctx = ((CacheObjectPortableProcessorImpl)ctx.processor()).portableContext();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void prepareMarshal(CacheObjectContext ctx) throws IgniteCheckedException {
 +        // No-op.
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int length() {
 +        return PortablePrimitives.readInt(arr, start + GridPortableMarshaller.TOTAL_LEN_POS);
 +    }
 +
 +    /**
 +     * @return Detached portable object.
 +     */
 +    public BinaryObject detach() {
 +        if (!detachAllowed || detached())
 +            return this;
 +
 +        int len = length();
 +
 +        byte[] arr0 = new byte[len];
 +
 +        U.arrayCopy(arr, start, arr0, 0, len);
 +
 +        return new BinaryObjectImpl(ctx, arr0, 0);
 +    }
 +
 +    /**
 +     * @return Detached or not.
 +     */
 +    public boolean detached() {
 +        return start == 0 && length() == arr.length;
 +    }
 +
 +    /**
 +     * @return {@code True} if detach is allowed.
 +     */
 +    public boolean detachAllowed() {
 +        return true;
 +    }
 +
 +    /**
 +     * @param detachAllowed Detach allowed flag.
 +     */
 +    public void detachAllowed(boolean detachAllowed) {
 +        this.detachAllowed = detachAllowed;
 +    }
 +
 +    /**
 +     * @return Context.
 +     */
 +    public PortableContext context() {
 +        return ctx;
 +    }
 +
 +    /**
 +     * @param ctx Context.
 +     */
 +    public void context(PortableContext ctx) {
 +        this.ctx = ctx;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte[] array() {
 +        return arr;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int start() {
 +        return start;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public long offheapAddress() {
 +        return 0;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override protected boolean hasArray() {
 +        return true;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int typeId() {
 +        return PortablePrimitives.readInt(arr, start + GridPortableMarshaller.TYPE_ID_POS);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public BinaryType metaData() throws BinaryObjectException {
 +        if (ctx == null)
 +            throw new BinaryObjectException("PortableContext is not set for the object.");
 +
 +        return ctx.metaData(typeId());
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override public <F> F field(String fieldName) throws BinaryObjectException {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx, arr, start, null);
 +
 +        return (F)reader.unmarshalField(fieldName);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override public <F> F field(int fieldId) throws BinaryObjectException {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx, arr, start, null);
 +
 +        return (F)reader.unmarshalField(fieldId);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
-     @Nullable @Override protected <F> F fieldByOffset(int fieldOffset) {
++    @Nullable @Override protected <F> F fieldByOrder(int order) {
 +        Object val;
 +
++        // Calculate field position.
 +        int schemaOffset = PortablePrimitives.readInt(arr, start + GridPortableMarshaller.SCHEMA_OR_RAW_OFF_POS);
-         int fieldPos = PortablePrimitives.readInt(arr, start + schemaOffset + fieldOffset);
++
++        short flags = PortablePrimitives.readShort(arr, start + GridPortableMarshaller.FLAGS_POS);
++        int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
++
++        int fieldOffsetPos = start + schemaOffset + order * (4 + fieldOffsetSize) + 4;
++
++        int fieldPos;
++
++        if (fieldOffsetSize == PortableUtils.OFFSET_1)
++            fieldPos = start + (int)PortablePrimitives.readByte(arr, fieldOffsetPos) & 0xFF;
++        else if (fieldOffsetSize == PortableUtils.OFFSET_2)
++            fieldPos = start + (int)PortablePrimitives.readShort(arr, fieldOffsetPos) & 0xFFFF;
++        else
++            fieldPos = start + PortablePrimitives.readInt(arr, fieldOffsetPos);
 +
 +        // Read header and try performing fast lookup for well-known types (the most common types go first).
 +        byte hdr = PortablePrimitives.readByte(arr, fieldPos);
 +
 +        switch (hdr) {
 +            case INT:
 +                val = PortablePrimitives.readInt(arr, fieldPos + 1);
 +
 +                break;
 +
 +            case LONG:
 +                val = PortablePrimitives.readLong(arr, fieldPos + 1);
 +
 +                break;
 +
 +            case BOOLEAN:
 +                val = PortablePrimitives.readBoolean(arr, fieldPos + 1);
 +
 +                break;
 +
 +            case SHORT:
 +                val = PortablePrimitives.readShort(arr, fieldPos + 1);
 +
 +                break;
 +
 +            case BYTE:
 +                val = PortablePrimitives.readByte(arr, fieldPos + 1);
 +
 +                break;
 +
 +            case CHAR:
 +                val = PortablePrimitives.readChar(arr, fieldPos + 1);
 +
 +                break;
 +
 +            case FLOAT:
 +                val = PortablePrimitives.readFloat(arr, fieldPos + 1);
 +
 +                break;
 +
 +            case DOUBLE:
 +                val = PortablePrimitives.readDouble(arr, fieldPos + 1);
 +
 +                break;
 +
- //            case DECIMAL:
- //                val = doReadDecimal();
- //
- //                break;
- //
- //            case STRING:
- //                val = doReadString();
- //
- //                break;
- //
- //            case UUID:
- //                val = doReadUuid();
- //
- //                break;
- //
- //            case DATE:
- //                val = doReadDate();
- //
- //                break;
- //
- //            case TIMESTAMP:
- //                val = doReadTimestamp();
- //
- //                break;
- 
 +            default: {
-                 // TODO: Pass absolute offset, not relative.
 +                BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx, arr, start, null);
 +
-                 val = reader.unmarshalFieldByOffset(fieldOffset);
++                val = reader.unmarshalFieldByAbsolutePosition(fieldPos);
 +            }
 +        }
 +
 +        return (F)val;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override protected <F> F field(PortableReaderContext rCtx, String fieldName) {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx,
 +            new PortableHeapInputStream(arr),
 +            start,
 +            null,
 +            rCtx);
 +
 +        return (F)reader.unmarshalField(fieldName);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean hasField(String fieldName) {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx, arr, start, null);
 +
 +        return reader.hasField(fieldName);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override public <T> T deserialize() throws BinaryObjectException {
 +        Object obj0 = obj;
 +
 +        if (obj0 == null)
 +            obj0 = deserializeValue();
 +
 +        return (T)obj0;
 +
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryObject clone() throws CloneNotSupportedException {
 +        return super.clone();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int hashCode() {
 +        return PortablePrimitives.readInt(arr, start + GridPortableMarshaller.HASH_CODE_POS);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override protected int schemaId() {
 +        return PortablePrimitives.readInt(arr, start + GridPortableMarshaller.SCHEMA_ID_POS);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override protected PortableSchema createSchema() {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx, arr, start, null);
 +
 +        return reader.createSchema();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryField fieldDescriptor(String fieldName) throws BinaryObjectException {
 +        int typeId = typeId();
 +
 +        PortableSchemaRegistry schemaReg = ctx.schemaRegistry(typeId);
 +
 +        int fieldId = ctx.userTypeIdMapper(typeId).fieldId(typeId, fieldName);
 +
 +        return new BinaryFieldImpl(schemaReg, fieldId);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeExternal(ObjectOutput out) throws IOException {
 +        out.writeObject(ctx);
 +
 +        if (detachAllowed) {
 +            int len = length();
 +
 +            out.writeInt(len);
 +            out.write(arr, start, len);
 +            out.writeInt(0);
 +        }
 +        else {
 +            out.writeInt(arr.length);
 +            out.write(arr);
 +            out.writeInt(start);
 +        }
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
 +        ctx = (PortableContext)in.readObject();
 +
 +        arr = new byte[in.readInt()];
 +
 +        in.readFully(arr);
 +
 +        start = in.readInt();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
 +        writer.setBuffer(buf);
 +
 +        if (!writer.isHeaderWritten()) {
 +            if (!writer.writeHeader(directType(), fieldsCount()))
 +                return false;
 +
 +            writer.onHeaderWritten();
 +        }
 +
 +        switch (writer.state()) {
 +            case 0:
 +                if (!writer.writeByteArray("arr",
 +                    arr,
 +                    detachAllowed ? start : 0,
 +                    detachAllowed ? length() : arr.length))
 +                    return false;
 +
 +                writer.incrementState();
 +
 +            case 1:
 +                if (!writer.writeInt("start", detachAllowed ? 0 : start))
 +                    return false;
 +
 +                writer.incrementState();
 +
 +        }
 +
 +        return true;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
 +        reader.setBuffer(buf);
 +
 +        if (!reader.beforeMessageRead())
 +            return false;
 +
 +        switch (reader.state()) {
 +            case 0:
 +                arr = reader.readByteArray("arr");
 +
 +                if (!reader.isLastRead())
 +                    return false;
 +
 +                reader.incrementState();
 +
 +            case 1:
 +                start = reader.readInt("start");
 +
 +                if (!reader.isLastRead())
 +                    return false;
 +
 +                reader.incrementState();
 +
 +        }
 +
 +        return true;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte directType() {
 +        return 113;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte fieldsCount() {
 +        return 3;
 +    }
 +
 +    /**
 +     * Runs value deserialization regardless of whether obj already has the deserialized value.
 +     * Will set obj if descriptor is configured to keep deserialized values.
 +     */
 +    private Object deserializeValue() {
 +        // TODO: IGNITE-1272 - Deserialize with proper class loader.
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx, arr, start, null);
 +
 +        Object obj0 = reader.deserialize();
 +
 +        PortableClassDescriptor desc = reader.descriptor();
 +
 +        assert desc != null;
 +
 +        if (desc.keepDeserialized())
 +            obj = obj0;
 +
 +        return obj0;
 +    }
 +}

http://git-wip-us.apache.org/repos/asf/ignite/blob/c050b4ce/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectOffheapImpl.java
----------------------------------------------------------------------
diff --cc modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectOffheapImpl.java
index e588a95,0000000..b543b9e
mode 100644,000000..100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectOffheapImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryObjectOffheapImpl.java
@@@ -1,304 -1,0 +1,381 @@@
 +/*
 + * 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.portable;
 +
 +import java.io.Externalizable;
 +import java.io.IOException;
 +import java.io.ObjectInput;
 +import java.io.ObjectOutput;
 +import java.nio.ByteBuffer;
 +import org.apache.ignite.IgniteCheckedException;
 +import org.apache.ignite.internal.portable.streams.PortableOffheapInputStream;
 +import org.apache.ignite.internal.processors.cache.CacheObject;
 +import org.apache.ignite.internal.processors.cache.CacheObjectContext;
 +import org.apache.ignite.internal.util.GridUnsafe;
 +import org.apache.ignite.internal.util.typedef.internal.U;
 +import org.apache.ignite.plugin.extensions.communication.MessageReader;
 +import org.apache.ignite.plugin.extensions.communication.MessageWriter;
 +import org.apache.ignite.binary.BinaryObjectException;
 +import org.apache.ignite.binary.BinaryType;
 +import org.apache.ignite.binary.BinaryObject;
 +import org.apache.ignite.binary.BinaryField;
 +import org.jetbrains.annotations.Nullable;
 +import sun.misc.Unsafe;
 +
++import static org.apache.ignite.internal.portable.GridPortableMarshaller.BOOLEAN;
++import static org.apache.ignite.internal.portable.GridPortableMarshaller.BYTE;
++import static org.apache.ignite.internal.portable.GridPortableMarshaller.CHAR;
++import static org.apache.ignite.internal.portable.GridPortableMarshaller.DOUBLE;
++import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLOAT;
++import static org.apache.ignite.internal.portable.GridPortableMarshaller.INT;
++import static org.apache.ignite.internal.portable.GridPortableMarshaller.LONG;
++import static org.apache.ignite.internal.portable.GridPortableMarshaller.SHORT;
++
 +/**
 + *  Portable object implementation over offheap memory
 + */
 +public class BinaryObjectOffheapImpl extends BinaryObjectEx implements Externalizable, CacheObject {
 +    /** */
 +    private static final long serialVersionUID = 0L;
 +
 +    /** */
 +    private static final Unsafe UNSAFE = GridUnsafe.unsafe();
 +
 +    /** */
 +    private final PortableContext ctx;
 +
 +    /** */
 +    private final long ptr;
 +
 +    /** */
 +    private final int start;
 +
 +    /** */
 +    private final int size;
 +
 +    /**
 +     * For {@link Externalizable} (not supported).
 +     */
 +    public BinaryObjectOffheapImpl() {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /**
 +     * @param ctx Context.
 +     * @param ptr Memory address.
 +     * @param start Object start.
 +     * @param size Memory size.
 +     */
 +    public BinaryObjectOffheapImpl(PortableContext ctx, long ptr, int start, int size) {
 +        this.ctx = ctx;
 +        this.ptr = ptr;
 +        this.start = start;
 +        this.size = size;
 +    }
 +
 +    /**
 +     * @return Heap-based copy.
 +     */
 +    public BinaryObject heapCopy() {
 +        return new BinaryObjectImpl(ctx, U.copyMemory(ptr, size), start);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int typeId() {
 +        return UNSAFE.getInt(ptr + start + GridPortableMarshaller.TYPE_ID_POS);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int length() {
 +        return UNSAFE.getInt(ptr + start + GridPortableMarshaller.TOTAL_LEN_POS);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int hashCode() {
 +        return UNSAFE.getInt(ptr + start + GridPortableMarshaller.HASH_CODE_POS);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override protected int schemaId() {
 +        return UNSAFE.getInt(ptr + start + GridPortableMarshaller.SCHEMA_ID_POS);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override protected PortableSchema createSchema() {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx,
 +            new PortableOffheapInputStream(ptr, size, false),
 +            start,
 +            null);
 +
 +        return reader.createSchema();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public BinaryField fieldDescriptor(String fieldName) throws BinaryObjectException {
 +        int typeId = typeId();
 +
 +        PortableSchemaRegistry schemaReg = ctx.schemaRegistry(typeId);
 +
 +        int fieldId = ctx.userTypeIdMapper(typeId).fieldId(typeId, fieldName);
 +
 +        return new BinaryFieldImpl(schemaReg, fieldId);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public int start() {
 +        return start;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte[] array() {
 +        return null;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public long offheapAddress() {
 +        return ptr;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override protected boolean hasArray() {
 +        return false;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Nullable @Override public BinaryType metaData() throws BinaryObjectException {
 +        if (ctx == null)
 +            throw new BinaryObjectException("PortableContext is not set for the object.");
 +
 +        return ctx.metaData(typeId());
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override public <F> F field(String fieldName) throws BinaryObjectException {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx,
 +            new PortableOffheapInputStream(ptr, size, false),
 +            start,
 +            null);
 +
 +        return (F)reader.unmarshalField(fieldName);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override public <F> F field(int fieldId) throws BinaryObjectException {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx,
 +            new PortableOffheapInputStream(ptr, size, false),
 +            start,
 +            null);
 +
 +        return (F)reader.unmarshalField(fieldId);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
-     @Nullable @Override protected <F> F fieldByOffset(int fieldOffset) {
-         BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx,
-             new PortableOffheapInputStream(ptr, size, false),
-             start,
-             null);
++    @Nullable @Override protected <F> F fieldByOrder(int order) {
++        Object val;
++
++        // Calculate field position.
++        int schemaOffset = PortablePrimitives.readInt(ptr, start + GridPortableMarshaller.SCHEMA_OR_RAW_OFF_POS);
++
++        short flags = PortablePrimitives.readShort(ptr, start + GridPortableMarshaller.FLAGS_POS);
++        int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
++
++        int fieldOffsetPos = start + schemaOffset + order * (4 + fieldOffsetSize) + 4;
++
++        int fieldPos;
++
++        if (fieldOffsetSize == PortableUtils.OFFSET_1)
++            fieldPos = start + (int)PortablePrimitives.readByte(ptr, fieldOffsetPos) & 0xFF;
++        else if (fieldOffsetSize == PortableUtils.OFFSET_2)
++            fieldPos = start + (int)PortablePrimitives.readShort(ptr, fieldOffsetPos) & 0xFFFF;
++        else
++            fieldPos = start + PortablePrimitives.readInt(ptr, fieldOffsetPos);
++
++        // Read header and try performing fast lookup for well-known types (the most common types go first).
++        byte hdr = PortablePrimitives.readByte(ptr, fieldPos);
++
++        switch (hdr) {
++            case INT:
++                val = PortablePrimitives.readInt(ptr, fieldPos + 1);
++
++                break;
++
++            case LONG:
++                val = PortablePrimitives.readLong(ptr, fieldPos + 1);
++
++                break;
++
++            case BOOLEAN:
++                val = PortablePrimitives.readBoolean(ptr, fieldPos + 1);
++
++                break;
++
++            case SHORT:
++                val = PortablePrimitives.readShort(ptr, fieldPos + 1);
++
++                break;
++
++            case BYTE:
++                val = PortablePrimitives.readByte(ptr, fieldPos + 1);
++
++                break;
++
++            case CHAR:
++                val = PortablePrimitives.readChar(ptr, fieldPos + 1);
++
++                break;
++
++            case FLOAT:
++                val = PortablePrimitives.readFloat(ptr, fieldPos + 1);
++
++                break;
++
++            case DOUBLE:
++                val = PortablePrimitives.readDouble(ptr, fieldPos + 1);
++
++                break;
++
++            default: {
++                PortableReaderExImpl reader = new PortableReaderExImpl(ctx,
++                    new PortableOffheapInputStream(ptr, size, false),
++                    start,
++                    null);
++
++                val = reader.unmarshalFieldByAbsolutePosition(fieldPos);
++            }
++        }
 +
-         return (F)reader.unmarshalFieldByOffset(fieldOffset);
++        return (F)val;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override protected <F> F field(PortableReaderContext rCtx, String fieldName) {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx,
 +            new PortableOffheapInputStream(ptr, size, false),
 +            start,
 +            null,
 +            rCtx);
 +
 +        return (F)reader.unmarshalField(fieldName);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean hasField(String fieldName) {
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(ctx,
 +            new PortableOffheapInputStream(ptr, size, false),
 +            start,
 +            null);
 +
 +        return reader.hasField(fieldName);
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override public <T> T deserialize() throws BinaryObjectException {
 +        return (T)deserializeValue();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("CloneDoesntCallSuperClone")
 +    @Override public BinaryObject clone() throws CloneNotSupportedException {
 +        return heapCopy();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte type() {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean isPlatformType() {
 +        return false;
 +    }
 +
 +    /** {@inheritDoc} */
 +    @SuppressWarnings("unchecked")
 +    @Nullable @Override public <T> T value(CacheObjectContext ctx, boolean cpy) {
 +        return (T)deserializeValue();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte[] valueBytes(CacheObjectContext ctx) throws IgniteCheckedException {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public CacheObject prepareForCache(CacheObjectContext ctx) {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void finishUnmarshal(CacheObjectContext ctx, ClassLoader ldr) throws IgniteCheckedException {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void prepareMarshal(CacheObjectContext ctx) throws IgniteCheckedException {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte directType() {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public byte fieldsCount() {
 +        throw new UnsupportedOperationException();
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void writeExternal(ObjectOutput out) throws IOException {
 +        throw new UnsupportedOperationException(); // To make sure it is not marshalled.
 +    }
 +
 +    /** {@inheritDoc} */
 +    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
 +        throw new UnsupportedOperationException(); // To make sure it is not marshalled.
 +    }
 +
 +    /**
 +     * @return Deserialized value.
 +     */
 +    private Object deserializeValue() {
 +        // TODO: IGNITE-1272 - Deserialize with proper class loader.
 +        BinaryReaderExImpl reader = new BinaryReaderExImpl(
 +            ctx,
 +            new PortableOffheapInputStream(ptr, size, false),
 +            start,
 +            null);
 +
 +        return reader.deserialize();
 +    }
 +}


[2/5] ignite git commit: IGNITE-1418: Implemented compact field offsets.

Posted by ag...@apache.org.
IGNITE-1418: Implemented compact field offsets.


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/845c4f27
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/845c4f27
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/845c4f27

Branch: refs/heads/ignite-950-new
Commit: 845c4f2722e69aa1f7ccd8ff619c52a013eb775a
Parents: fd640d7
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Nov 3 13:16:10 2015 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Nov 3 13:16:10 2015 +0300

----------------------------------------------------------------------
 .gitignore                                      |   7 +
 .../portable/PortableClassDescriptor.java       |  33 ++-
 .../internal/portable/PortableFieldImpl.java    |  10 +-
 .../internal/portable/PortableObjectEx.java     |   2 +-
 .../internal/portable/PortableObjectImpl.java   |  46 ++-
 .../portable/PortableObjectOffheapImpl.java     |  89 +++++-
 .../internal/portable/PortableReaderExImpl.java |  41 +--
 .../internal/portable/PortableSchema.java       | 133 ++++-----
 .../ignite/internal/portable/PortableUtils.java |  46 ++-
 .../internal/portable/PortableWriterExImpl.java |  76 ++++-
 .../portable/builder/PortableBuilderImpl.java   | 283 ++++++++++---------
 .../src/portable_reader_writer_test.cpp         | 251 +++++++++++++---
 .../ignite/impl/interop/interop_input_stream.h  |  16 ++
 .../ignite/impl/interop/interop_output_stream.h |   8 +
 .../ignite/impl/portable/portable_common.h      |   6 +
 .../ignite/impl/portable/portable_reader_impl.h |  29 +-
 .../ignite/impl/portable/portable_schema.h      |  26 +-
 .../src/impl/interop/interop_input_stream.cpp   |  20 ++
 .../src/impl/interop/interop_output_stream.cpp  |   7 +
 .../src/impl/portable/portable_reader_impl.cpp  |  45 ++-
 .../core/src/impl/portable/portable_schema.cpp  |  53 +++-
 .../src/impl/portable/portable_writer_impl.cpp  |  21 +-
 .../Portable/PortableSelfTest.cs                |  32 +++
 .../Impl/Common/ResizeableArray.cs              |  14 +-
 .../Apache.Ignite.Core/Impl/ExceptionUtils.cs   |   2 -
 .../Impl/Portable/PortableBuilderImpl.cs        |   8 +-
 .../Impl/Portable/PortableObjectHeader.cs       | 196 ++++++++++---
 .../Impl/Portable/PortableObjectSchema.cs       |   6 +-
 .../Impl/Portable/PortableObjectSchemaField.cs  |  69 +----
 .../Impl/Portable/PortableReaderImpl.cs         | 113 +++-----
 .../Impl/Portable/PortableUtils.cs              |   4 +-
 .../Impl/Portable/PortableWriterImpl.cs         |   7 +-
 .../Impl/Portable/PortablesImpl.cs              |   2 +-
 .../Impl/Unmanaged/UnmanagedCallbackHandlers.cs |   2 +-
 34 files changed, 1145 insertions(+), 558 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index 3da8e4d..22e3cc6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,3 +21,10 @@ target
 pom-installed.xml
 git-patch-prop-local.sh
 /slurp.sh
+*.vcxproj.user
+Apache.Ignite.sdf
+ignite.sdf
+ignite.opensdf
+**/cpp/**/vs/x64/
+**/cpp/**/vs/Win32/
+**/dotnet/**/obj/

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
index 9f7f0c6..aa72017 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableClassDescriptor.java
@@ -524,12 +524,17 @@ public class PortableClassDescriptor {
 
             case PORTABLE:
                 if (writeHeader(obj, writer)) {
-                    if (serializer != null)
-                        serializer.writePortable(obj, writer);
-                    else
-                        ((PortableMarshalAware)obj).writePortable(writer);
+                    try {
+                        if (serializer != null)
+                            serializer.writePortable(obj, writer);
+                        else
+                            ((PortableMarshalAware) obj).writePortable(writer);
 
-                    writer.postWrite(userType);
+                        writer.postWrite(userType);
+                    }
+                    finally {
+                        writer.popSchema();
+                    }
 
                     if (obj.getClass() != PortableMetaDataImpl.class
                         && ctx.isMetaDataChanged(typeId, writer.metaDataHashSum())) {
@@ -552,22 +557,30 @@ public class PortableClassDescriptor {
 
                     try {
                         ((Externalizable)obj).writeExternal(writer);
+
+                        writer.postWrite(userType);
                     }
                     catch (IOException e) {
                         throw new PortableException("Failed to write Externalizable object: " + obj, e);
                     }
-
-                    writer.postWrite(userType);
+                    finally {
+                        writer.popSchema();
+                    }
                 }
 
                 break;
 
             case OBJECT:
                 if (writeHeader(obj, writer)) {
-                    for (FieldInfo info : fields)
-                        info.write(obj, writer);
+                    try {
+                        for (FieldInfo info : fields)
+                            info.write(obj, writer);
 
-                    writer.postWrite(userType);
+                        writer.postWrite(userType);
+                    }
+                    finally {
+                        writer.popSchema();
+                    }
                 }
 
                 break;

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableFieldImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableFieldImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableFieldImpl.java
index 5780b76..12be55c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableFieldImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableFieldImpl.java
@@ -45,7 +45,7 @@ public class PortableFieldImpl implements PortableField {
     @Override public boolean exists(PortableObject obj) {
         PortableObjectEx obj0 = (PortableObjectEx)obj;
 
-        return fieldOffset(obj0) != 0;
+        return fieldOrder(obj0) != 0;
     }
 
     /** {@inheritDoc} */
@@ -53,9 +53,9 @@ public class PortableFieldImpl implements PortableField {
     @Override public <T> T value(PortableObject obj) {
         PortableObjectEx obj0 = (PortableObjectEx)obj;
 
-        int offset = fieldOffset(obj0);
+        int order = fieldOrder(obj0);
 
-        return offset != 0 ? (T)obj0.fieldByOffset(offset) : null;
+        return order != 0 ? (T)obj0.fieldByOrder(order) : null;
     }
 
     /**
@@ -64,7 +64,7 @@ public class PortableFieldImpl implements PortableField {
      * @param obj Object.
      * @return Field offset.
      */
-    private int fieldOffset(PortableObjectEx obj) {
+    private int fieldOrder(PortableObjectEx obj) {
         int schemaId = obj.schemaId();
 
         PortableSchema schema = schemas.schema(schemaId);
@@ -77,6 +77,6 @@ public class PortableFieldImpl implements PortableField {
 
         assert schema != null;
 
-        return schema.offset(fieldId);
+        return schema.order(fieldId);
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectEx.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectEx.java
index 42c973b..d6d7f50 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectEx.java
@@ -72,7 +72,7 @@ public abstract class PortableObjectEx implements PortableObject {
      * @param fieldOffset Field offset.
      * @return Field value.
      */
-    @Nullable protected abstract <F> F fieldByOffset(int fieldOffset);
+    @Nullable protected abstract <F> F fieldByOrder(int fieldOffset);
 
     /**
      * @param ctx Reader context.

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectImpl.java
index a1272d0..c7e01d7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectImpl.java
@@ -256,11 +256,25 @@ public final class PortableObjectImpl extends PortableObjectEx implements Extern
 
     /** {@inheritDoc} */
     @SuppressWarnings("unchecked")
-    @Nullable @Override protected <F> F fieldByOffset(int fieldOffset) {
+    @Nullable @Override protected <F> F fieldByOrder(int order) {
         Object val;
 
+        // Calculate field position.
         int schemaOffset = PortablePrimitives.readInt(arr, start + GridPortableMarshaller.SCHEMA_OR_RAW_OFF_POS);
-        int fieldPos = PortablePrimitives.readInt(arr, start + schemaOffset + fieldOffset);
+
+        short flags = PortablePrimitives.readShort(arr, start + GridPortableMarshaller.FLAGS_POS);
+        int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
+
+        int fieldOffsetPos = start + schemaOffset + order * (4 + fieldOffsetSize) + 4;
+
+        int fieldPos;
+
+        if (fieldOffsetSize == PortableUtils.OFFSET_1)
+            fieldPos = start + (int)PortablePrimitives.readByte(arr, fieldOffsetPos) & 0xFF;
+        else if (fieldOffsetSize == PortableUtils.OFFSET_2)
+            fieldPos = start + (int)PortablePrimitives.readShort(arr, fieldOffsetPos) & 0xFFFF;
+        else
+            fieldPos = start + PortablePrimitives.readInt(arr, fieldOffsetPos);
 
         // Read header and try performing fast lookup for well-known types (the most common types go first).
         byte hdr = PortablePrimitives.readByte(arr, fieldPos);
@@ -306,36 +320,10 @@ public final class PortableObjectImpl extends PortableObjectEx implements Extern
 
                 break;
 
-//            case DECIMAL:
-//                val = doReadDecimal();
-//
-//                break;
-//
-//            case STRING:
-//                val = doReadString();
-//
-//                break;
-//
-//            case UUID:
-//                val = doReadUuid();
-//
-//                break;
-//
-//            case DATE:
-//                val = doReadDate();
-//
-//                break;
-//
-//            case TIMESTAMP:
-//                val = doReadTimestamp();
-//
-//                break;
-
             default: {
-                // TODO: Pass absolute offset, not relative.
                 PortableReaderExImpl reader = new PortableReaderExImpl(ctx, arr, start, null);
 
-                val = reader.unmarshalFieldByOffset(fieldOffset);
+                val = reader.unmarshalFieldByAbsolutePosition(fieldPos);
             }
         }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectOffheapImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectOffheapImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectOffheapImpl.java
index f023f2e..7ba5553 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectOffheapImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableObjectOffheapImpl.java
@@ -37,6 +37,15 @@ import org.apache.ignite.portable.PortableObject;
 import org.jetbrains.annotations.Nullable;
 import sun.misc.Unsafe;
 
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.BOOLEAN;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.BYTE;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.CHAR;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.DOUBLE;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLOAT;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.INT;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.LONG;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.SHORT;
+
 /**
  *  Portable object implementation over offheap memory
  */
@@ -179,13 +188,81 @@ public class PortableObjectOffheapImpl extends PortableObjectEx implements Exter
 
     /** {@inheritDoc} */
     @SuppressWarnings("unchecked")
-    @Nullable @Override protected <F> F fieldByOffset(int fieldOffset) {
-        PortableReaderExImpl reader = new PortableReaderExImpl(ctx,
-            new PortableOffheapInputStream(ptr, size, false),
-            start,
-            null);
+    @Nullable @Override protected <F> F fieldByOrder(int order) {
+        Object val;
+
+        // Calculate field position.
+        int schemaOffset = PortablePrimitives.readInt(ptr, start + GridPortableMarshaller.SCHEMA_OR_RAW_OFF_POS);
+
+        short flags = PortablePrimitives.readShort(ptr, start + GridPortableMarshaller.FLAGS_POS);
+        int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
+
+        int fieldOffsetPos = start + schemaOffset + order * (4 + fieldOffsetSize) + 4;
+
+        int fieldPos;
+
+        if (fieldOffsetSize == PortableUtils.OFFSET_1)
+            fieldPos = start + (int)PortablePrimitives.readByte(ptr, fieldOffsetPos) & 0xFF;
+        else if (fieldOffsetSize == PortableUtils.OFFSET_2)
+            fieldPos = start + (int)PortablePrimitives.readShort(ptr, fieldOffsetPos) & 0xFFFF;
+        else
+            fieldPos = start + PortablePrimitives.readInt(ptr, fieldOffsetPos);
+
+        // Read header and try performing fast lookup for well-known types (the most common types go first).
+        byte hdr = PortablePrimitives.readByte(ptr, fieldPos);
+
+        switch (hdr) {
+            case INT:
+                val = PortablePrimitives.readInt(ptr, fieldPos + 1);
+
+                break;
+
+            case LONG:
+                val = PortablePrimitives.readLong(ptr, fieldPos + 1);
+
+                break;
+
+            case BOOLEAN:
+                val = PortablePrimitives.readBoolean(ptr, fieldPos + 1);
+
+                break;
+
+            case SHORT:
+                val = PortablePrimitives.readShort(ptr, fieldPos + 1);
+
+                break;
+
+            case BYTE:
+                val = PortablePrimitives.readByte(ptr, fieldPos + 1);
+
+                break;
+
+            case CHAR:
+                val = PortablePrimitives.readChar(ptr, fieldPos + 1);
+
+                break;
+
+            case FLOAT:
+                val = PortablePrimitives.readFloat(ptr, fieldPos + 1);
+
+                break;
+
+            case DOUBLE:
+                val = PortablePrimitives.readDouble(ptr, fieldPos + 1);
+
+                break;
+
+            default: {
+                PortableReaderExImpl reader = new PortableReaderExImpl(ctx,
+                    new PortableOffheapInputStream(ptr, size, false),
+                    start,
+                    null);
+
+                val = reader.unmarshalFieldByAbsolutePosition(fieldPos);
+            }
+        }
 
-        return (F)reader.unmarshalFieldByOffset(fieldOffset);
+        return (F)val;
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderExImpl.java
index aa1519d..061a9fd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableReaderExImpl.java
@@ -163,6 +163,9 @@ public class PortableReaderExImpl implements PortableReader, PortableRawReaderEx
     /** Schema Id. */
     private int schemaId;
 
+    /** Offset size in bytes. */
+    private int offsetSize;
+
     /** Object schema. */
     private PortableSchema schema;
 
@@ -221,18 +224,20 @@ public class PortableReaderExImpl implements PortableReader, PortableRawReaderEx
 
         PortableUtils.checkProtocolVersion(in.readByte());
 
-        in.position(in.position() + 2); // Skip flags.
+        short flags = in.readShort();
+
+        offsetSize = PortableUtils.fieldOffsetSize(flags);
 
         typeId = in.readIntPositioned(start + GridPortableMarshaller.TYPE_ID_POS);
 
-        IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(in, start);
+        IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(in, start, offsetSize);
 
         footerStart = footer.get1();
         footerLen = footer.get2() - footerStart;
 
         schemaId = in.readIntPositioned(start + GridPortableMarshaller.SCHEMA_ID_POS);
 
-        rawOff = PortableUtils.rawOffsetAbsolute(in, start);
+        rawOff = PortableUtils.rawOffsetAbsolute(in, start, offsetSize);
 
         if (typeId == UNREGISTERED_TYPE_ID) {
             // Skip to the class name position.
@@ -307,16 +312,16 @@ public class PortableReaderExImpl implements PortableReader, PortableRawReaderEx
     }
 
     /**
-     * @param fieldOffset Field offset.
-     * @return Unmarshalled value.
+     * Unmarshal field by absolute position.
+     *
+     * @param pos Absolute position.
+     * @return Field value.
      * @throws PortableException In case of error.
      */
-    @Nullable Object unmarshalFieldByOffset(int fieldOffset) throws PortableException {
-        assert fieldOffset != 0;
-
+    @Nullable Object unmarshalFieldByAbsolutePosition(int pos) throws PortableException {
         parseHeaderIfNeeded();
 
-        in.position(start + in.readIntPositioned(footerStart + fieldOffset));
+        in.position(pos);
 
         return unmarshal();
     }
@@ -2567,12 +2572,14 @@ public class PortableReaderExImpl implements PortableReader, PortableRawReaderEx
         int searchPos = footerStart;
         int searchEnd = searchPos + footerLen;
 
+        int idx = 0;
+
         while (searchPos < searchEnd) {
             int fieldId = in.readIntPositioned(searchPos);
 
-            fields.put(fieldId, searchPos + 4 - footerStart);
+            fields.put(fieldId, idx++);
 
-            searchPos += 8;
+            searchPos += 4 + offsetSize;
         }
 
         return new PortableSchema(fields);
@@ -2599,14 +2606,14 @@ public class PortableReaderExImpl implements PortableReader, PortableRawReaderEx
                 int id0 = in.readIntPositioned(searchPos);
 
                 if (id0 == id) {
-                    int pos = start + in.readIntPositioned(searchPos + 4);
+                    int pos = start + PortableUtils.fieldOffsetRelative(in, searchPos + 4, offsetSize);
 
                     in.position(pos);
 
                     return pos;
                 }
 
-                searchPos += 8;
+                searchPos += 4 + offsetSize;
             }
         }
         else {
@@ -2624,10 +2631,12 @@ public class PortableReaderExImpl implements PortableReader, PortableRawReaderEx
                 schema = schema0;
             }
 
-            int fieldOffsetPos = schema.offset(id);
+            int order = schema.order(id);
+
+            if (order != 0) {
+                int offsetPos = footerStart + order * (4 + offsetSize) + 4;
 
-            if (fieldOffsetPos != 0) {
-                int pos = start + in.readIntPositioned(footerStart + fieldOffsetPos);
+                int pos = start + PortableUtils.fieldOffsetRelative(in, offsetPos, offsetSize);
 
                 in.position(pos);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableSchema.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableSchema.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableSchema.java
index 09bfe35..03be319 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableSchema.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableSchema.java
@@ -36,52 +36,28 @@ public class PortableSchema {
     private final HashMap<Integer, Integer> map;
 
     /** ID 1. */
-    private final int id1;
-
-    /** Offset 1. */
-    private final int offset1;
+    private final int id0;
 
     /** ID 2. */
-    private final int id2;
-
-    /** Offset 2. */
-    private final int offset2;
+    private final int id1;
 
     /** ID 3. */
-    private final int id3;
-
-    /** Offset 3. */
-    private final int offset3;
+    private final int id2;
 
     /** ID 4. */
-    private final int id4;
-
-    /** Offset 4. */
-    private final int offset4;
+    private final int id3;
 
     /** ID 1. */
-    private final int id5;
-
-    /** Offset 1. */
-    private final int offset5;
+    private final int id4;
 
     /** ID 2. */
-    private final int id6;
-
-    /** Offset 2. */
-    private final int offset6;
+    private final int id5;
 
     /** ID 3. */
-    private final int id7;
-
-    /** Offset 3. */
-    private final int offset7;
+    private final int id6;
 
     /** ID 4. */
-    private final int id8;
-
-    /** Offset 4. */
-    private final int offset8;
+    private final int id7;
 
     /**
      * Constructor.
@@ -97,120 +73,111 @@ public class PortableSchema {
             Map.Entry<Integer, Integer> entry = iter.hasNext() ? iter.next() : null;
 
             if (entry != null) {
+                id0 = entry.getKey();
+
+                assert entry.getValue() == 0;
+            }
+            else
+                id0 = 0;
+
+            if ((entry = iter.hasNext() ? iter.next() : null) != null) {
                 id1 = entry.getKey();
-                offset1 = entry.getValue();
+
+                assert entry.getValue() == 1;
             }
-            else{
+            else
                 id1 = 0;
-                offset1 = 0;
-            }
 
             if ((entry = iter.hasNext() ? iter.next() : null) != null) {
                 id2 = entry.getKey();
-                offset2 = entry.getValue();
+
+                assert entry.getValue() == 2;
             }
-            else{
+            else
                 id2 = 0;
-                offset2 = 0;
-            }
 
             if ((entry = iter.hasNext() ? iter.next() : null) != null) {
                 id3 = entry.getKey();
-                offset3 = entry.getValue();
+
+                assert entry.getValue() == 3;
             }
-            else{
+            else
                 id3 = 0;
-                offset3 = 0;
-            }
 
             if ((entry = iter.hasNext() ? iter.next() : null) != null) {
                 id4 = entry.getKey();
-                offset4 = entry.getValue();
+
+                assert entry.getValue() == 4;
             }
-            else{
+            else
                 id4 = 0;
-                offset4 = 0;
-            }
 
             if ((entry = iter.hasNext() ? iter.next() : null) != null) {
                 id5 = entry.getKey();
-                offset5 = entry.getValue();
+
+                assert entry.getValue() == 5;
             }
-            else{
+            else
                 id5 = 0;
-                offset5 = 0;
-            }
 
             if ((entry = iter.hasNext() ? iter.next() : null) != null) {
                 id6 = entry.getKey();
-                offset6 = entry.getValue();
+
+                assert entry.getValue() == 6;
             }
-            else{
+            else
                 id6 = 0;
-                offset6 = 0;
-            }
 
             if ((entry = iter.hasNext() ? iter.next() : null) != null) {
                 id7 = entry.getKey();
-                offset7 = entry.getValue();
-            }
-            else{
-                id7 = 0;
-                offset7 = 0;
-            }
 
-            if ((entry = iter.hasNext() ? iter.next() : null) != null) {
-                id8 = entry.getKey();
-                offset8 = entry.getValue();
-            }
-            else{
-                id8 = 0;
-                offset8 = 0;
+                assert entry.getValue() == 7;
             }
+            else
+                id7 = 0;
 
             map = null;
         }
         else {
             inline = false;
 
-            id1 = id2 = id3 = id4 = id5 = id6 = id7 = id8 = 0;
-            offset1 = offset2 = offset3 = offset4 = offset5 = offset6 = offset7 = offset8 = 0;
+            id0 = id1 = id2 = id3 = id4 = id5 = id6 = id7 = 0;
 
             map = new HashMap<>(vals);
         }
     }
 
     /**
-     * Get offset for the given field ID.
+     * Get field position in footer by schema ID.
      *
      * @param id Field ID.
      * @return Offset or {@code 0} if there is no such field.
      */
-    public int offset(int id) {
+    public int order(int id) {
         if (inline) {
+            if (id == id0)
+                return 0;
+
             if (id == id1)
-                return offset1;
+                return 1;
 
             if (id == id2)
-                return offset2;
+                return 2;
 
             if (id == id3)
-                return offset3;
+                return 3;
 
             if (id == id4)
-                return offset4;
+                return 4;
 
             if (id == id5)
-                return offset5;
+                return 5;
 
             if (id == id6)
-                return offset6;
+                return 6;
 
             if (id == id7)
-                return offset7;
-
-            if (id == id8)
-                return offset8;
+                return 7;
 
             return 0;
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.java
index f57a29b..4e3538c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableUtils.java
@@ -619,14 +619,16 @@ public class PortableUtils {
      *
      * @param in Input stream.
      * @param start Start position.
+     * @param fieldOffsetSize Field offset size.
      * @return Footer.
      */
-    public static IgniteBiTuple<Integer, Integer> footerAbsolute(PortablePositionReadable in, int start) {
+    public static IgniteBiTuple<Integer, Integer> footerAbsolute(PortablePositionReadable in, int start,
+        int fieldOffsetSize) {
         int footerStart = footerStartRelative(in, start);
         int footerEnd = length(in, start);
 
         // Take in count possible raw offset.
-        if ((((footerEnd - footerStart) >> 2) & 0x1) == 0x1)
+        if ((footerEnd - footerStart) % (4 + fieldOffsetSize) != 0)
             footerEnd -= 4;
 
         return F.t(start + footerStart, start + footerEnd);
@@ -637,9 +639,10 @@ public class PortableUtils {
      *
      * @param in Input stream.
      * @param start Object start position inside the stream.
+     * @param fieldOffsetSize Field offset size.
      * @return Raw offset.
      */
-    public static int rawOffsetAbsolute(PortablePositionReadable in, int start) {
+    public static int rawOffsetAbsolute(PortablePositionReadable in, int start, int fieldOffsetSize) {
         int len = length(in, start);
 
         short flags = in.readShortPositioned(start + GridPortableMarshaller.FLAGS_POS);
@@ -651,7 +654,7 @@ public class PortableUtils {
             // Schema exists.
             int schemaOff = in.readIntPositioned(start + GridPortableMarshaller.SCHEMA_OR_RAW_OFF_POS);
 
-            if ((((len - schemaOff) >> 2) & 0x1) == 0x0)
+            if (((len - schemaOff) % (4 + fieldOffsetSize)) == 0x0)
                 // Even amount of records in schema => no raw offset.
                 return start + schemaOff;
             else
@@ -659,4 +662,39 @@ public class PortableUtils {
                 return start + in.readIntPositioned(start + len - 4);
         }
     }
+
+    /**
+     * Get offset size for the given flags.
+     * @param flags Flags.
+     * @return Offset size.
+     */
+    public static int fieldOffsetSize(short flags) {
+        if ((flags & FLAG_OFFSET_ONE_BYTE) == FLAG_OFFSET_ONE_BYTE)
+            return OFFSET_1;
+        else if ((flags & FLAG_OFFSET_TWO_BYTES) == FLAG_OFFSET_TWO_BYTES)
+            return OFFSET_2;
+        else
+            return OFFSET_4;
+    }
+
+    /**
+     * Get relative field offset.
+     *
+     * @param stream Stream.
+     * @param pos Position.
+     * @param fieldOffsetSize Field offset size.
+     * @return Relative field offset.
+     */
+    public static int fieldOffsetRelative(PortablePositionReadable stream, int pos, int fieldOffsetSize) {
+        int res;
+
+        if (fieldOffsetSize == PortableUtils.OFFSET_1)
+            res = (int)stream.readBytePositioned(pos) & 0xFF;
+        else if (fieldOffsetSize == PortableUtils.OFFSET_2)
+            res = (int)stream.readShortPositioned(pos) & 0xFFFF;
+        else
+            res = stream.readIntPositioned(pos);
+
+        return res;
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
index 227087b..ff85ecd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/PortableWriterExImpl.java
@@ -99,6 +99,12 @@ public class PortableWriterExImpl implements PortableWriter, PortableRawWriterEx
     /** FNV1 hash prime. */
     private static final int FNV1_PRIME = 0x01000193;
 
+    /** Maximum offset which fits in 1 byte. */
+    private static final int MAX_OFFSET_1 = 1 << 8;
+
+    /** Maximum offset which fits in 2 bytes. */
+    private static final int MAX_OFFSET_2 = 1 << 16;
+
     /** Thread-local schema. */
     private static final ThreadLocal<SchemaHolder> SCHEMA = new ThreadLocal<>();
 
@@ -342,11 +348,22 @@ public class PortableWriterExImpl implements PortableWriter, PortableRawWriterEx
             out.writeInt(start + SCHEMA_OR_RAW_OFF_POS, out.position() - start);
 
             // Write the schema.
-            schema.writeAndPop(this, fieldCnt);
+            int offsetByteCnt = schema.write(this, fieldCnt);
 
             // Write raw offset if needed.
             if (rawOffPos != 0)
                 out.writeInt(rawOffPos - start);
+
+            if (offsetByteCnt == PortableUtils.OFFSET_1) {
+                int flags = (userType ? PortableUtils.FLAG_USR_TYP : 0) | PortableUtils.FLAG_OFFSET_ONE_BYTE;
+
+                out.writeShort(start + FLAGS_POS, (short)flags);
+            }
+            else if (offsetByteCnt == PortableUtils.OFFSET_2) {
+                int flags = (userType ? PortableUtils.FLAG_USR_TYP : 0) | PortableUtils.FLAG_OFFSET_TWO_BYTES;
+
+                out.writeShort(start + FLAGS_POS, (short)flags);
+            }
         }
         else {
             // Write raw-only flag is needed.
@@ -363,6 +380,17 @@ public class PortableWriterExImpl implements PortableWriter, PortableRawWriterEx
     }
 
     /**
+     * Pop schema.
+     */
+    public void popSchema() {
+        if (schema != null) {
+            assert fieldCnt > 0;
+
+            schema.pop(fieldCnt);
+        }
+    }
+
+    /**
      * @param val Byte array.
      */
     public void write(byte[] val) {
@@ -1833,19 +1861,51 @@ public class PortableWriterExImpl implements PortableWriter, PortableRawWriterEx
          * Write collected frames and pop them.
          *
          * @param writer Writer.
-         * @param cnt Count.
+         * @param fieldCnt Count.
+         * @return Amount of bytes dedicated to
          */
-        public void writeAndPop(PortableWriterExImpl writer, int cnt) {
-            int startIdx = idx - cnt * 2;
+        public int write(PortableWriterExImpl writer, int fieldCnt) {
+            int startIdx = idx - fieldCnt * 2;
 
             assert startIdx >= 0;
 
-            for (int idx0 = startIdx; idx0 < idx;) {
-                writer.writeInt(data[idx0++]);
-                writer.writeInt(data[idx0++]);
+            int lastOffset = data[idx - 1];
+
+            int res;
+
+            if (lastOffset < MAX_OFFSET_1) {
+                for (int idx0 = startIdx; idx0 < idx; ) {
+                    writer.writeInt(data[idx0++]);
+                    writer.writeByte((byte) data[idx0++]);
+                }
+
+                res = PortableUtils.OFFSET_1;
             }
+            else if (lastOffset < MAX_OFFSET_2) {
+                for (int idx0 = startIdx; idx0 < idx; ) {
+                    writer.writeInt(data[idx0++]);
+                    writer.writeShort((short)data[idx0++]);
+                }
+
+                res = PortableUtils.OFFSET_2;
+            }
+            else {
+                for (int idx0 = startIdx; idx0 < idx; ) {
+                    writer.writeInt(data[idx0++]);
+                    writer.writeInt(data[idx0++]);
+                }
 
-            idx = startIdx;
+                res = PortableUtils.OFFSET_4;
+            }
+
+            return res;
+        }
+
+        /**
+         * Pop current object's frame.
+         */
+        public void pop(int fieldCnt) {
+            idx = idx - fieldCnt * 2;
 
             // Shrink data array if needed.
             if (idx == 0 && data.length > MAX_SIZE)

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/core/src/main/java/org/apache/ignite/internal/portable/builder/PortableBuilderImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/portable/builder/PortableBuilderImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/portable/builder/PortableBuilderImpl.java
index 34e1d6d..608425d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/portable/builder/PortableBuilderImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/portable/builder/PortableBuilderImpl.java
@@ -41,6 +41,7 @@ import java.util.Map;
 import java.util.Set;
 
 import static org.apache.ignite.internal.portable.GridPortableMarshaller.DFLT_HDR_LEN;
+import static org.apache.ignite.internal.portable.GridPortableMarshaller.FLAGS_POS;
 import static org.apache.ignite.internal.portable.GridPortableMarshaller.HASH_CODE_POS;
 import static org.apache.ignite.internal.portable.GridPortableMarshaller.PROTO_VER_POS;
 import static org.apache.ignite.internal.portable.GridPortableMarshaller.TYPE_ID_POS;
@@ -77,12 +78,13 @@ public class PortableBuilderImpl implements PortableBuilder {
     /** Position of object in source array, or -1 if object is not created from PortableObject. */
     private final int start;
 
+    /** Flags. */
+    private final short flags;
+
     /** Total header length */
     private final int hdrLen;
 
-    /**
-     * Context of PortableObject reading process. Or {@code null} if object is not created from PortableObject.
-     */
+    /** Context of PortableObject reading process. Or {@code null} if object is not created from PortableObject. */
     private final PortableBuilderReader reader;
 
     /** */
@@ -115,6 +117,7 @@ public class PortableBuilderImpl implements PortableBuilder {
         this.ctx = ctx;
 
         start = -1;
+        flags = -1;
         reader = null;
         hdrLen = DFLT_HDR_LEN;
 
@@ -137,6 +140,7 @@ public class PortableBuilderImpl implements PortableBuilder {
     PortableBuilderImpl(PortableBuilderReader reader, int start) {
         this.reader = reader;
         this.start = start;
+        this.flags = reader.readShortPositioned(start + FLAGS_POS);
 
         byte ver = reader.readBytePositioned(start + PROTO_VER_POS);
 
@@ -198,184 +202,188 @@ public class PortableBuilderImpl implements PortableBuilder {
      * @param serializer Serializer.
      */
     void serializeTo(PortableWriterExImpl writer, PortableBuilderSerializer serializer) {
-        PortableUtils.writeHeader(writer,
-            true,
-            registeredType ? typeId : UNREGISTERED_TYPE_ID,
-            hashCode,
-            registeredType ? null : clsNameToWrite);
+        try {
+            PortableUtils.writeHeader(writer,
+                true,
+                registeredType ? typeId : UNREGISTERED_TYPE_ID,
+                hashCode,
+                registeredType ? null : clsNameToWrite);
 
-        Set<Integer> remainsFlds = null;
+            Set<Integer> remainsFlds = null;
 
-        if (reader != null) {
-            Map<Integer, Object> assignedFldsById;
+            if (reader != null) {
+                Map<Integer, Object> assignedFldsById;
 
-            if (assignedVals != null) {
-                assignedFldsById = U.newHashMap(assignedVals.size());
+                if (assignedVals != null) {
+                    assignedFldsById = U.newHashMap(assignedVals.size());
 
-                for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
-                    int fldId = ctx.fieldId(typeId, entry.getKey());
+                    for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
+                        int fldId = ctx.fieldId(typeId, entry.getKey());
 
-                    assignedFldsById.put(fldId, entry.getValue());
-                }
+                        assignedFldsById.put(fldId, entry.getValue());
+                    }
 
-                remainsFlds = assignedFldsById.keySet();
-            }
-            else
-                assignedFldsById = Collections.emptyMap();
+                    remainsFlds = assignedFldsById.keySet();
+                } else
+                    assignedFldsById = Collections.emptyMap();
 
-            // Get footer details.
-            IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(reader, start);
+                // Get footer details.
+                int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
 
-            int footerPos = footer.get1();
-            int footerEnd = footer.get2();
+                IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(reader, start, fieldOffsetSize);
 
-            // Get raw position.
-            int rawPos = PortableUtils.rawOffsetAbsolute(reader, start);
+                int footerPos = footer.get1();
+                int footerEnd = footer.get2();
 
-            // Position reader on data.
-            reader.position(start + hdrLen);
+                // Get raw position.
+                int rawPos = PortableUtils.rawOffsetAbsolute(reader, start, fieldOffsetSize);
 
-            while (reader.position() < rawPos) {
-                int fieldId = reader.readIntPositioned(footerPos);
-                int fieldLen = fieldPositionAndLength(footerPos, footerEnd, rawPos).get2();
+                // Position reader on data.
+                reader.position(start + hdrLen);
 
-                footerPos += 8;
+                while (reader.position() + 4 < rawPos) {
+                    int fieldId = reader.readIntPositioned(footerPos);
+                    int fieldLen = fieldPositionAndLength(footerPos, footerEnd, rawPos, fieldOffsetSize).get2();
 
-                if (assignedFldsById.containsKey(fieldId)) {
-                    Object assignedVal = assignedFldsById.remove(fieldId);
+                    footerPos += 4 + fieldOffsetSize;
 
-                    reader.skip(fieldLen);
+                    if (assignedFldsById.containsKey(fieldId)) {
+                        Object assignedVal = assignedFldsById.remove(fieldId);
 
-                    if (assignedVal != REMOVED_FIELD_MARKER) {
-                        writer.writeFieldId(fieldId);
+                        reader.skip(fieldLen);
 
-                        serializer.writeValue(writer, assignedVal);
-                    }
-                }
-                else {
-                    int type = fieldLen != 0 ? reader.readByte(0) : 0;
+                        if (assignedVal != REMOVED_FIELD_MARKER) {
+                            writer.writeFieldId(fieldId);
 
-                    if (fieldLen != 0 && !PortableUtils.isPlainArrayType(type) && PortableUtils.isPlainType(type)) {
-                        writer.writeFieldId(fieldId);
-                        writer.write(reader.array(), reader.position(), fieldLen);
+                            serializer.writeValue(writer, assignedVal);
+                        }
+                    } else {
+                        int type = fieldLen != 0 ? reader.readByte(0) : 0;
 
-                        reader.skip(fieldLen);
-                    }
-                    else {
-                        writer.writeFieldId(fieldId);
+                        if (fieldLen != 0 && !PortableUtils.isPlainArrayType(type) && PortableUtils.isPlainType(type)) {
+                            writer.writeFieldId(fieldId);
+                            writer.write(reader.array(), reader.position(), fieldLen);
 
-                        Object val;
+                            reader.skip(fieldLen);
+                        } else {
+                            writer.writeFieldId(fieldId);
 
-                        if (fieldLen == 0)
-                            val = null;
-                        else if (readCache == null) {
-                            int savedPos = reader.position();
+                            Object val;
 
-                            val = reader.parseValue();
+                            if (fieldLen == 0)
+                                val = null;
+                            else if (readCache == null) {
+                                int savedPos = reader.position();
 
-                            assert reader.position() == savedPos + fieldLen;
-                        }
-                        else {
-                            val = readCache.get(fieldId);
+                                val = reader.parseValue();
 
-                            reader.skip(fieldLen);
-                        }
+                                assert reader.position() == savedPos + fieldLen;
+                            } else {
+                                val = readCache.get(fieldId);
+
+                                reader.skip(fieldLen);
+                            }
 
-                        serializer.writeValue(writer, val);
+                            serializer.writeValue(writer, val);
+                        }
                     }
                 }
             }
-        }
-
-        if (assignedVals != null && (remainsFlds == null || !remainsFlds.isEmpty())) {
-            boolean metadataEnabled = ctx.isMetaDataEnabled(typeId);
 
-            PortableMetadata metadata = null;
+            if (assignedVals != null && (remainsFlds == null || !remainsFlds.isEmpty())) {
+                boolean metadataEnabled = ctx.isMetaDataEnabled(typeId);
 
-            if (metadataEnabled)
-                metadata = ctx.metaData(typeId);
+                PortableMetadata metadata = null;
 
-            Map<String, String> newFldsMetadata = null;
+                if (metadataEnabled)
+                    metadata = ctx.metaData(typeId);
 
-            for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
-                Object val = entry.getValue();
+                Map<String, String> newFldsMetadata = null;
 
-                if (val == REMOVED_FIELD_MARKER)
-                    continue;
-
-                String name = entry.getKey();
+                for (Map.Entry<String, Object> entry : assignedVals.entrySet()) {
+                    Object val = entry.getValue();
 
-                int fldId = ctx.fieldId(typeId, name);
+                    if (val == REMOVED_FIELD_MARKER)
+                        continue;
 
-                if (remainsFlds != null && !remainsFlds.contains(fldId))
-                    continue;
+                    String name = entry.getKey();
 
-                writer.writeFieldId(fldId);
+                    int fldId = ctx.fieldId(typeId, name);
 
-                serializer.writeValue(writer, val);
+                    if (remainsFlds != null && !remainsFlds.contains(fldId))
+                        continue;
 
-                if (metadataEnabled) {
-                    String oldFldTypeName = metadata == null ? null : metadata.fieldTypeName(name);
+                    writer.writeFieldId(fldId);
 
-                    String newFldTypeName;
+                    serializer.writeValue(writer, val);
 
-                    if (val instanceof PortableValueWithType)
-                        newFldTypeName = ((PortableValueWithType)val).typeName();
-                    else {
-                        byte type = PortableUtils.typeByClass(val.getClass());
+                    if (metadataEnabled) {
+                        String oldFldTypeName = metadata == null ? null : metadata.fieldTypeName(name);
 
-                        newFldTypeName = CacheObjectPortableProcessorImpl.fieldTypeName(type);
-                    }
+                        String newFldTypeName;
 
-                    if (oldFldTypeName == null) {
-                        // It's a new field, we have to add it to metadata.
+                        if (val instanceof PortableValueWithType)
+                            newFldTypeName = ((PortableValueWithType) val).typeName();
+                        else {
+                            byte type = PortableUtils.typeByClass(val.getClass());
 
-                        if (newFldsMetadata == null)
-                            newFldsMetadata = new HashMap<>();
+                            newFldTypeName = CacheObjectPortableProcessorImpl.fieldTypeName(type);
+                        }
 
-                        newFldsMetadata.put(name, newFldTypeName);
-                    }
-                    else {
-                        if (!"Object".equals(oldFldTypeName) && !oldFldTypeName.equals(newFldTypeName)) {
-                            throw new PortableException(
-                                "Wrong value has been set [" +
-                                    "typeName=" + (typeName == null ? metadata.typeName() : typeName) +
-                                    ", fieldName=" + name +
-                                    ", fieldType=" + oldFldTypeName +
-                                    ", assignedValueType=" + newFldTypeName +
-                                    ", assignedValue=" + (((PortableValueWithType)val).value()) + ']'
-                            );
+                        if (oldFldTypeName == null) {
+                            // It's a new field, we have to add it to metadata.
+
+                            if (newFldsMetadata == null)
+                                newFldsMetadata = new HashMap<>();
+
+                            newFldsMetadata.put(name, newFldTypeName);
+                        } else {
+                            if (!"Object".equals(oldFldTypeName) && !oldFldTypeName.equals(newFldTypeName)) {
+                                throw new PortableException(
+                                    "Wrong value has been set [" +
+                                        "typeName=" + (typeName == null ? metadata.typeName() : typeName) +
+                                        ", fieldName=" + name +
+                                        ", fieldType=" + oldFldTypeName +
+                                        ", assignedValueType=" + newFldTypeName +
+                                        ", assignedValue=" + (((PortableValueWithType) val).value()) + ']'
+                                );
+                            }
                         }
                     }
                 }
-            }
 
-            if (newFldsMetadata != null) {
-                String typeName = this.typeName;
+                if (newFldsMetadata != null) {
+                    String typeName = this.typeName;
 
-                if (typeName == null)
-                    typeName = metadata.typeName();
+                    if (typeName == null)
+                        typeName = metadata.typeName();
 
-                ctx.updateMetaData(typeId, typeName, newFldsMetadata);
+                    ctx.updateMetaData(typeId, typeName, newFldsMetadata);
+                }
             }
-        }
 
-        if (reader != null) {
-            // Write raw data if any.
-            int rawOff = PortableUtils.rawOffsetAbsolute(reader, start);
-            int footerStart = PortableUtils.footerStartAbsolute(reader, start);
+            if (reader != null) {
+                // Write raw data if any.
+                int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
+
+                int rawOff = PortableUtils.rawOffsetAbsolute(reader, start, fieldOffsetSize);
+                int footerStart = PortableUtils.footerStartAbsolute(reader, start);
 
-            if (rawOff < footerStart) {
-                writer.rawWriter();
+                if (rawOff < footerStart) {
+                    writer.rawWriter();
 
-                writer.write(reader.array(), rawOff, footerStart - rawOff);
+                    writer.write(reader.array(), rawOff, footerStart - rawOff);
+                }
+
+                // Shift reader to the end of the object.
+                reader.position(start + PortableUtils.length(reader, start));
             }
 
-            // Shift reader to the end of the object.
-            reader.position(start + PortableUtils.length(reader, start));
+            writer.postWrite(true);
+        }
+        finally {
+            writer.popSchema();
         }
-
-        writer.postWrite(true);
     }
 
     /** {@inheritDoc} */
@@ -391,21 +399,25 @@ public class PortableBuilderImpl implements PortableBuilder {
      * @param footerPos Field position inside the footer (absolute).
      * @param footerEnd Footer end (absolute).
      * @param rawPos Raw data position (absolute).
+     * @param fieldOffsetSize Size of field's offset.
      * @return Tuple with field position and length.
      */
-    private IgniteBiTuple<Integer, Integer> fieldPositionAndLength(int footerPos, int footerEnd, int rawPos) {
-        int fieldOffset = reader.readIntPositioned(footerPos + 4);
+    private IgniteBiTuple<Integer, Integer> fieldPositionAndLength(int footerPos, int footerEnd, int rawPos,
+        int fieldOffsetSize) {
+        // Get field offset first.
+        int fieldOffset = PortableUtils.fieldOffsetRelative(reader, footerPos + 4, fieldOffsetSize);
         int fieldPos = start + fieldOffset;
 
         // Get field length.
         int fieldLen;
 
-        if (footerPos + 8 == footerEnd)
+        if (footerPos + 4 + fieldOffsetSize == footerEnd)
             // This is the last field, compare to raw offset.
             fieldLen = rawPos - fieldPos;
         else {
             // Field is somewhere in the middle, get difference with the next offset.
-            int nextFieldOffset = reader.readIntPositioned(footerPos + 8 + 4);
+            int nextFieldOffset = PortableUtils.fieldOffsetRelative(reader, footerPos + 4 + fieldOffsetSize + 4,
+                fieldOffsetSize);
 
             fieldLen = nextFieldOffset - fieldOffset;
         }
@@ -418,26 +430,29 @@ public class PortableBuilderImpl implements PortableBuilder {
      */
     private void ensureReadCacheInit() {
         if (readCache == null) {
+            int fieldOffsetSize = PortableUtils.fieldOffsetSize(flags);
+
             Map<Integer, Object> readCache = new HashMap<>();
 
-            IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(reader, start);
+            IgniteBiTuple<Integer, Integer> footer = PortableUtils.footerAbsolute(reader, start, fieldOffsetSize);
 
             int footerPos = footer.get1();
             int footerEnd = footer.get2();
 
-            int rawPos = PortableUtils.rawOffsetAbsolute(reader, start);
+            int rawPos = PortableUtils.rawOffsetAbsolute(reader, start, fieldOffsetSize);
 
-            while (footerPos < footerEnd) {
+            while (footerPos + 4 < footerEnd) {
                 int fieldId = reader.readIntPositioned(footerPos);
 
-                IgniteBiTuple<Integer, Integer> posAndLen = fieldPositionAndLength(footerPos, footerEnd, rawPos);
+                IgniteBiTuple<Integer, Integer> posAndLen =
+                    fieldPositionAndLength(footerPos, footerEnd, rawPos, fieldOffsetSize);
 
                 Object val = reader.getValueQuickly(posAndLen.get1(), posAndLen.get2());
 
                 readCache.put(fieldId, val);
 
                 // Shift current footer position.
-                footerPos += 8;
+                footerPos += 4 + fieldOffsetSize;
             }
 
             this.readCache = readCache;

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core-test/src/portable_reader_writer_test.cpp
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core-test/src/portable_reader_writer_test.cpp b/modules/platforms/cpp/core-test/src/portable_reader_writer_test.cpp
index baeb9e7..3ec5a15 100644
--- a/modules/platforms/cpp/core-test/src/portable_reader_writer_test.cpp
+++ b/modules/platforms/cpp/core-test/src/portable_reader_writer_test.cpp
@@ -68,9 +68,9 @@ void CheckPrimitive(T val)
     in.Synchronize();
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8;
+    int32_t footerEnd = footerBegin + 5;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     try
@@ -148,9 +148,9 @@ void CheckPrimitiveArray(T dflt, T val1, T val2)
         in.Synchronize();
 
         int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-        int32_t footerEnd = footerBegin + 8;
+        int32_t footerEnd = footerBegin + 5;
 
-        PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+        PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
         PortableReader reader(&readerImpl);
 
         in.Position(IGNITE_DFLT_HDR_LEN);
@@ -181,9 +181,9 @@ void CheckPrimitiveArray(T dflt, T val1, T val2)
         in.Synchronize();
 
         int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-        int32_t footerEnd = footerBegin + 8;
+        int32_t footerEnd = footerBegin + 5;
 
-        PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+        PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
         PortableReader reader(&readerImpl);
 
         in.Position(IGNITE_DFLT_HDR_LEN);
@@ -218,9 +218,9 @@ void CheckPrimitiveArray(T dflt, T val1, T val2)
         in.Synchronize();
 
         int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-        int32_t footerEnd = footerBegin + 8;
+        int32_t footerEnd = footerBegin + 5;
 
-        PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+        PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
         PortableReader reader(&readerImpl);
 
         in.Position(IGNITE_DFLT_HDR_LEN);
@@ -258,9 +258,9 @@ void CheckPrimitiveArray(T dflt, T val1, T val2)
         in.Synchronize();
 
         int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-        int32_t footerEnd = footerBegin + 8;
+        int32_t footerEnd = footerBegin + 5;
 
-        PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+        PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
         PortableReader reader(&readerImpl);
 
         in.Position(IGNITE_DFLT_HDR_LEN);
@@ -510,9 +510,9 @@ void CheckCollectionEmpty(CollectionType* colType)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -600,9 +600,9 @@ void CheckCollection(CollectionType* colType)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -677,9 +677,9 @@ void CheckCollectionIterators(CollectionType* colType)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -753,9 +753,9 @@ void CheckMapEmpty(MapType* mapType)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -846,9 +846,9 @@ void CheckMap(MapType* mapType)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1028,9 +1028,9 @@ BOOST_AUTO_TEST_CASE(TestGuidNull)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8;
+    int32_t footerEnd = footerBegin + 5;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
     
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1113,9 +1113,9 @@ BOOST_AUTO_TEST_CASE(TestString) {
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 5;
+    int32_t footerEnd = footerBegin + 5 * 5;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1191,9 +1191,9 @@ BOOST_AUTO_TEST_CASE(TestStringArrayNull)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1308,9 +1308,9 @@ BOOST_AUTO_TEST_CASE(TestStringArrayEmpty)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1435,9 +1435,9 @@ BOOST_AUTO_TEST_CASE(TestStringArray)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1549,14 +1549,15 @@ BOOST_AUTO_TEST_CASE(TestObject)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 3;
+    int32_t footerEnd = footerBegin + 5 * 3;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN); 
 
     PortableInner readVal1 = reader.ReadObject<PortableInner>("field1");
+
     BOOST_REQUIRE(writeVal1.GetValue() == readVal1.GetValue());
 
     PortableInner readVal2 = reader.ReadObject<PortableInner>("field2");
@@ -1592,9 +1593,9 @@ BOOST_AUTO_TEST_CASE(TestNestedObject)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 3;
+    int32_t footerEnd = footerBegin + 5 * 3;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1634,9 +1635,9 @@ BOOST_AUTO_TEST_CASE(TestArrayNull)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1710,9 +1711,9 @@ BOOST_AUTO_TEST_CASE(TestArrayEmpty)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1794,9 +1795,9 @@ BOOST_AUTO_TEST_CASE(TestArray)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1855,9 +1856,9 @@ BOOST_AUTO_TEST_CASE(TestCollectionNull)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -1941,9 +1942,9 @@ BOOST_AUTO_TEST_CASE(TestMapNull)
     InteropInputStream in(&mem);
 
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
-    int32_t footerEnd = footerBegin + 8 * 2;
+    int32_t footerEnd = footerBegin + 5 * 2;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
 
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -2034,7 +2035,7 @@ BOOST_AUTO_TEST_CASE(TestRawMode)
     int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
     int32_t footerEnd = footerBegin;
 
-    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 1000, footerBegin, footerBegin, footerEnd);
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 1000, footerBegin, footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
     PortableReader reader(&readerImpl);
     
     in.Position(IGNITE_DFLT_HDR_LEN);
@@ -2111,7 +2112,7 @@ BOOST_AUTO_TEST_CASE(TestFieldSeek)
 
     PortableReaderImpl readerImpl(&in, &idRslvr, pos, usrType, 
                                   typeId, hashCode, len, rawOff, 
-                                  footerBegin, footerEnd);
+                                  footerBegin, footerEnd, OFFSET_TYPE_1_BYTE);
 
     PortableReader reader(&readerImpl);
 
@@ -2211,4 +2212,162 @@ BOOST_AUTO_TEST_CASE(TestFieldSeek)
     BOOST_REQUIRE(mapReader.IsNull());
 }
 
+BOOST_AUTO_TEST_CASE(TestSchemaOffset2ByteFields)
+{
+    const int fieldsNum = 64;
+
+    TemplatedPortableIdResolver<PortableDummy> idRslvr;
+
+    InteropUnpooledMemory mem(4096);
+
+    InteropOutputStream out(&mem);
+    PortableWriterImpl writerImpl(&out, &idRslvr, NULL, NULL, 0);
+    PortableWriter writer(&writerImpl);
+
+    out.Position(IGNITE_DFLT_HDR_LEN);
+
+    for (int i = 0; i < fieldsNum; ++i)
+    {
+        std::stringstream tmp;
+        tmp << "field" << i;
+
+        writer.WriteInt32(tmp.str().c_str(), i * 10);
+    }
+
+    writerImpl.PostWrite();
+
+    out.Synchronize();
+
+    InteropInputStream in(&mem);
+
+    int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
+    int32_t footerEnd = footerBegin + 6 * fieldsNum;
+
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_2_BYTE);
+    PortableReader reader(&readerImpl);
+
+    in.Position(IGNITE_DFLT_HDR_LEN);
+
+    for (int i = 0; i < fieldsNum; ++i)
+    {
+        std::stringstream tmp;
+        tmp << "field" << i;
+
+        BOOST_REQUIRE(reader.ReadInt32(tmp.str().c_str()) == i * 10);
+    }
+}
+
+BOOST_AUTO_TEST_CASE(TestSchemaOffset4ByteFields)
+{
+    const int fieldsNum = 0x10000 / 4;
+
+    TemplatedPortableIdResolver<PortableDummy> idRslvr;
+
+    InteropUnpooledMemory mem(1024 * 1024);
+
+    InteropOutputStream out(&mem);
+    PortableWriterImpl writerImpl(&out, &idRslvr, NULL, NULL, 0);
+    PortableWriter writer(&writerImpl);
+
+    out.Position(IGNITE_DFLT_HDR_LEN);
+
+    for (int i = 0; i < fieldsNum; ++i)
+    {
+        std::stringstream tmp;
+        tmp << "field" << i;
+
+        writer.WriteInt32(tmp.str().c_str(), i * 10);
+    }
+
+    writerImpl.PostWrite();
+
+    out.Synchronize();
+
+    InteropInputStream in(&mem);
+
+    int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
+    int32_t footerEnd = footerBegin + 8 * fieldsNum;
+
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_4_BYTE);
+    PortableReader reader(&readerImpl);
+
+    in.Position(IGNITE_DFLT_HDR_LEN);
+
+    for (int i = 0; i < fieldsNum; ++i)
+    {
+        std::stringstream tmp;
+        tmp << "field" << i;
+
+        BOOST_REQUIRE(reader.ReadInt32(tmp.str().c_str()) == i * 10);
+    }
+}
+
+BOOST_AUTO_TEST_CASE(TestSchemaOffset2ByteArray)
+{
+    TemplatedPortableIdResolver<PortableDummy> idRslvr;
+
+    InteropUnpooledMemory mem(4096);
+
+    InteropOutputStream out(&mem);
+    PortableWriterImpl writerImpl(&out, &idRslvr, NULL, NULL, 0);
+    PortableWriter writer(&writerImpl);
+
+    out.Position(IGNITE_DFLT_HDR_LEN);
+
+    int8_t dummyArray[256] = {};
+
+    writer.WriteInt8Array("field1", dummyArray, sizeof(dummyArray));
+    writer.WriteInt32("field2", 42);
+
+    writerImpl.PostWrite();
+
+    out.Synchronize();
+
+    InteropInputStream in(&mem);
+
+    int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
+    int32_t footerEnd = footerBegin + 6 * 2;
+
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_2_BYTE);
+    PortableReader reader(&readerImpl);
+
+    in.Position(IGNITE_DFLT_HDR_LEN);
+
+    BOOST_REQUIRE(reader.ReadInt32("field2") == 42);
+}
+
+BOOST_AUTO_TEST_CASE(TestSchemaOffset4ByteArray)
+{
+    TemplatedPortableIdResolver<PortableDummy> idRslvr;
+
+    InteropUnpooledMemory mem(1024 * 1024);
+
+    InteropOutputStream out(&mem);
+    PortableWriterImpl writerImpl(&out, &idRslvr, NULL, NULL, 0);
+    PortableWriter writer(&writerImpl);
+
+    out.Position(IGNITE_DFLT_HDR_LEN);
+
+    int8_t dummyArray[0x10000] = {};
+
+    writer.WriteInt8Array("field1", dummyArray, sizeof(dummyArray));
+    writer.WriteInt32("field2", 42);
+
+    writerImpl.PostWrite();
+
+    out.Synchronize();
+
+    InteropInputStream in(&mem);
+
+    int32_t footerBegin = in.ReadInt32(IGNITE_OFFSET_SCHEMA_OR_RAW_OFF);
+    int32_t footerEnd = footerBegin + 8 * 2;
+
+    PortableReaderImpl readerImpl(&in, &idRslvr, 0, true, idRslvr.GetTypeId(), 0, 100, 100, footerBegin, footerEnd, OFFSET_TYPE_4_BYTE);
+    PortableReader reader(&readerImpl);
+
+    in.Position(IGNITE_DFLT_HDR_LEN);
+
+    BOOST_REQUIRE(reader.ReadInt32("field2") == 42);
+}
+
 BOOST_AUTO_TEST_SUITE_END()
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/include/ignite/impl/interop/interop_input_stream.h
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/include/ignite/impl/interop/interop_input_stream.h b/modules/platforms/cpp/core/include/ignite/impl/interop/interop_input_stream.h
index f23cec6..6842990 100644
--- a/modules/platforms/cpp/core/include/ignite/impl/interop/interop_input_stream.h
+++ b/modules/platforms/cpp/core/include/ignite/impl/interop/interop_input_stream.h
@@ -44,6 +44,14 @@ namespace ignite
                  * @return Value.
                  */
                 int8_t ReadInt8();
+
+                /**
+                 * Read signed 8-byte int at the given position.
+                 *
+                 * @param pos Position.
+                 * @return Value.
+                 */
+                int32_t ReadInt8(int32_t pos);
                     
                 /**
                  * Read signed 8-byte int array.
@@ -76,6 +84,14 @@ namespace ignite
                 int16_t ReadInt16();
 
                 /**
+                 * Read signed 16-byte int at the given position.
+                 *
+                 * @param pos Position.
+                 * @return Value.
+                 */
+                int32_t ReadInt16(int32_t pos);
+
+                /**
                  * Read signed 16-byte int array.
                  *
                  * @param res Allocated array.

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/include/ignite/impl/interop/interop_output_stream.h
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/include/ignite/impl/interop/interop_output_stream.h b/modules/platforms/cpp/core/include/ignite/impl/interop/interop_output_stream.h
index 211ac6d..0814c01 100644
--- a/modules/platforms/cpp/core/include/ignite/impl/interop/interop_output_stream.h
+++ b/modules/platforms/cpp/core/include/ignite/impl/interop/interop_output_stream.h
@@ -83,6 +83,14 @@ namespace ignite
                 void WriteInt16(const int16_t val);
 
                 /**
+                 * Write signed 16-byte integer at the given position.
+                 *
+                 * @param pos Position.
+                 * @param val Value.
+                 */
+                void WriteInt16(const int32_t pos, const int16_t val);
+
+                /**
                  * Write signed 16-byte integer array.
                  *
                  * @param val Value.

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/include/ignite/impl/portable/portable_common.h
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/include/ignite/impl/portable/portable_common.h b/modules/platforms/cpp/core/include/ignite/impl/portable/portable_common.h
index c6dad50..f08c49b 100644
--- a/modules/platforms/cpp/core/include/ignite/impl/portable/portable_common.h
+++ b/modules/platforms/cpp/core/include/ignite/impl/portable/portable_common.h
@@ -169,6 +169,12 @@ namespace ignite
 
             /** Raw only flag. */
             const int16_t IGNITE_PORTABLE_FLAG_RAW_ONLY = 0x0002;
+
+            /** Flag indicating that schema field offset is one byte long. */
+            const int16_t IGNITE_PORTABLE_FLAG_OFFSET_1_BYTE = 0x0004;
+
+            /** Flag indicating that schema field offset is two byte long. */
+            const int16_t IGNITE_PORTABLE_FLAG_OFFSET_2_BYTE = 0x0008;
         }
     }    
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/include/ignite/impl/portable/portable_reader_impl.h
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/include/ignite/impl/portable/portable_reader_impl.h b/modules/platforms/cpp/core/include/ignite/impl/portable/portable_reader_impl.h
index fe25c87..4762fff 100644
--- a/modules/platforms/cpp/core/include/ignite/impl/portable/portable_reader_impl.h
+++ b/modules/platforms/cpp/core/include/ignite/impl/portable/portable_reader_impl.h
@@ -59,7 +59,7 @@ namespace ignite
                  */
                 PortableReaderImpl(interop::InteropInputStream* stream, PortableIdResolver* idRslvr,
                     int32_t pos, bool usrType, int32_t typeId, int32_t hashCode, int32_t len, int32_t rawOff,
-                    int32_t footerBegin, int32_t footerEnd);
+                    int32_t footerBegin, int32_t footerEnd, PortableOffsetType schemaType);
 
                 /**
                  * Constructor used to construct light-weight reader allowing only raw operations 
@@ -788,7 +788,27 @@ namespace ignite
                             else
                                 footerBegin = schemaOrRawOff;
 
-                            int32_t trailingBytes = (len - footerBegin) % 8;
+                            PortableOffsetType schemaType;
+                            int32_t trailingBytes;
+
+                            if (flags & IGNITE_PORTABLE_FLAG_OFFSET_1_BYTE)
+                            {
+                                schemaType = OFFSET_TYPE_1_BYTE;
+
+                                trailingBytes = (len - footerBegin) % 5;
+                            }
+                            else if (flags & IGNITE_PORTABLE_FLAG_OFFSET_2_BYTE)
+                            {
+                                schemaType = OFFSET_TYPE_2_BYTE;
+
+                                trailingBytes = (len - footerBegin) % 6;
+                            }
+                            else
+                            {
+                                schemaType = OFFSET_TYPE_4_BYTE;
+
+                                trailingBytes = (len - footerBegin) % 8;
+                            }
 
                             int32_t footerEnd = len - trailingBytes;
 
@@ -806,7 +826,7 @@ namespace ignite
                             TemplatedPortableIdResolver<T> idRslvr(type);
                             PortableReaderImpl readerImpl(stream, &idRslvr, pos, usrType,
                                                           typeId, hashCode, len, rawOff,
-                                                          footerBegin, footerEnd);
+                                                          footerBegin, footerEnd, schemaType);
                             ignite::portable::PortableReader reader(&readerImpl);
 
                             T val = type.Read(reader);
@@ -887,6 +907,9 @@ namespace ignite
                 /** Footer ending position. */
                 int32_t footerEnd;
 
+                /** Object schema type. */
+                PortableOffsetType schemaType;
+
                 IGNITE_NO_COPY_ASSIGNMENT(PortableReaderImpl)
                     
                 /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/include/ignite/impl/portable/portable_schema.h
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/include/ignite/impl/portable/portable_schema.h b/modules/platforms/cpp/core/include/ignite/impl/portable/portable_schema.h
index 1795fd1..4919e2a 100644
--- a/modules/platforms/cpp/core/include/ignite/impl/portable/portable_schema.h
+++ b/modules/platforms/cpp/core/include/ignite/impl/portable/portable_schema.h
@@ -34,6 +34,21 @@ namespace ignite
             class PortableWriterImpl;
 
             /**
+             * Schema size variants.
+             */
+            enum PortableOffsetType
+            {
+                /** Means all field offsets can be fit in one byte. */
+                OFFSET_TYPE_1_BYTE,
+
+                /** Means all field offsets can be fit in two bytes. */
+                OFFSET_TYPE_2_BYTE,
+
+                /** Means field offsets should be stored in four bytes. */
+                OFFSET_TYPE_4_BYTE
+            };
+
+            /**
              * Portable schema.
              */
             class IGNITE_IMPORT_EXPORT PortableSchema
@@ -86,10 +101,17 @@ namespace ignite
                  */
                 void Clear();
 
+                /**
+                 * Get type of schema.
+                 *
+                 * @return Type of schema.
+                 */
+                PortableOffsetType GetType() const;
+
             private:
                 /**
-                * Single schema field info.
-                */
+                 * Single schema field info.
+                 */
                 struct PortableSchemaFieldInfo
                 {
                     int32_t id;

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/src/impl/interop/interop_input_stream.cpp
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/src/impl/interop/interop_input_stream.cpp b/modules/platforms/cpp/core/src/impl/interop/interop_input_stream.cpp
index 02e894c..fed7871 100644
--- a/modules/platforms/cpp/core/src/impl/interop/interop_input_stream.cpp
+++ b/modules/platforms/cpp/core/src/impl/interop/interop_input_stream.cpp
@@ -69,6 +69,16 @@ namespace ignite
                 IGNITE_INTEROP_IN_READ(int8_t, 1);
             }
 
+            int32_t InteropInputStream::ReadInt8(int32_t pos)
+            {
+                int delta = pos + 1 - this->pos;
+
+                if (delta > 0)
+                    EnsureEnoughData(delta);
+
+                return *reinterpret_cast<int8_t*>(data + pos);
+            }
+
             void InteropInputStream::ReadInt8Array(int8_t* const res, const int32_t len)
             {
                 IGNITE_INTEROP_IN_READ_ARRAY(len, 0);
@@ -90,6 +100,16 @@ namespace ignite
                 IGNITE_INTEROP_IN_READ(int16_t, 2);
             }
 
+            int32_t InteropInputStream::ReadInt16(int32_t pos)
+            {
+                int delta = pos + 2 - this->pos;
+
+                if (delta > 0)
+                    EnsureEnoughData(delta);
+
+                return *reinterpret_cast<int16_t*>(data + pos);
+            }
+
             void InteropInputStream::ReadInt16Array(int16_t* const res, const int32_t len)
             {
                 IGNITE_INTEROP_IN_READ_ARRAY(len, 1);

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/src/impl/interop/interop_output_stream.cpp
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/src/impl/interop/interop_output_stream.cpp b/modules/platforms/cpp/core/src/impl/interop/interop_output_stream.cpp
index 1fd400b..acfd3ec 100644
--- a/modules/platforms/cpp/core/src/impl/interop/interop_output_stream.cpp
+++ b/modules/platforms/cpp/core/src/impl/interop/interop_output_stream.cpp
@@ -96,6 +96,13 @@ namespace ignite
                 IGNITE_INTEROP_OUT_WRITE(val, int16_t, 2);
             }
 
+            void InteropOutputStream::WriteInt16(const int32_t pos, const int16_t val)
+            {
+                EnsureCapacity(pos + 2);
+
+                *reinterpret_cast<int16_t*>(data + pos) = val;
+            }
+
             void InteropOutputStream::WriteInt16Array(const int16_t* val, const int32_t len)
             {
                 IGNITE_INTEROP_OUT_WRITE_ARRAY(val, len << 1);

http://git-wip-us.apache.org/repos/asf/ignite/blob/845c4f27/modules/platforms/cpp/core/src/impl/portable/portable_reader_impl.cpp
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/core/src/impl/portable/portable_reader_impl.cpp b/modules/platforms/cpp/core/src/impl/portable/portable_reader_impl.cpp
index 96378e0..fd2cc18 100644
--- a/modules/platforms/cpp/core/src/impl/portable/portable_reader_impl.cpp
+++ b/modules/platforms/cpp/core/src/impl/portable/portable_reader_impl.cpp
@@ -36,10 +36,10 @@ namespace ignite
         {
             PortableReaderImpl::PortableReaderImpl(InteropInputStream* stream, PortableIdResolver* idRslvr,
                 int32_t pos, bool usrType, int32_t typeId, int32_t hashCode, int32_t len, int32_t rawOff,
-                int32_t footerBegin, int32_t footerEnd) :
+                int32_t footerBegin, int32_t footerEnd, PortableOffsetType schemaType) :
                 stream(stream), idRslvr(idRslvr), pos(pos), usrType(usrType), typeId(typeId), 
                 hashCode(hashCode), len(len), rawOff(rawOff), rawMode(false), elemIdGen(0), elemId(0),
-                elemCnt(-1), elemRead(0), footerBegin(footerBegin), footerEnd(footerEnd)
+                elemCnt(-1), elemRead(0), footerBegin(footerBegin), footerEnd(footerEnd), schemaType(schemaType)
             {
                 // No-op.
             }
@@ -47,7 +47,7 @@ namespace ignite
             PortableReaderImpl::PortableReaderImpl(InteropInputStream* stream) :
                 stream(stream), idRslvr(NULL), pos(0), usrType(false), typeId(0), hashCode(0), len(0),
                 rawOff(0), rawMode(true), elemIdGen(0), elemId(0), elemCnt(-1), elemRead(0), footerBegin(-1),
-                footerEnd(-1)
+                footerEnd(-1), schemaType(OFFSET_TYPE_4_BYTE)
             {
                 // No-op.
             }
@@ -648,12 +648,43 @@ namespace ignite
 
                 stream->Position(footerBegin);
 
-                for (int32_t schemaPos = footerBegin; schemaPos < footerEnd; schemaPos += 8)
+                switch (schemaType)
                 {
-                    int32_t currentFieldId = stream->ReadInt32(schemaPos);
+                    case OFFSET_TYPE_1_BYTE:
+                    {
+                        for (int32_t schemaPos = footerBegin; schemaPos < footerEnd; schemaPos += 5)
+                        {
+                            int32_t currentFieldId = stream->ReadInt32(schemaPos);
+
+                            if (fieldId == currentFieldId)
+                                return static_cast<uint8_t>(stream->ReadInt8(schemaPos + 4)) + pos;
+                        }
+                        break;
+                    }
+
+                    case OFFSET_TYPE_2_BYTE:
+                    {
+                        for (int32_t schemaPos = footerBegin; schemaPos < footerEnd; schemaPos += 6)
+                        {
+                            int32_t currentFieldId = stream->ReadInt32(schemaPos);
 
-                    if (fieldId == currentFieldId)
-                        return stream->ReadInt32(schemaPos + 4) + pos;
+                            if (fieldId == currentFieldId)
+                                return static_cast<uint16_t>(stream->ReadInt16(schemaPos + 4)) + pos;
+                        }
+                        break;
+                    }
+
+                    case OFFSET_TYPE_4_BYTE:
+                    {
+                        for (int32_t schemaPos = footerBegin; schemaPos < footerEnd; schemaPos += 8)
+                        {
+                            int32_t currentFieldId = stream->ReadInt32(schemaPos);
+
+                            if (fieldId == currentFieldId)
+                                return stream->ReadInt32(schemaPos + 4) + pos;
+                        }
+                        break;
+                    }
                 }
 
                 return -1;