Пример #1
0
        public int EndObject(Span <byte> buffer, SpanWriter writer, int tableLength)
        {
            checked
            {
                // TODO: Include some sort of hash function here so we don't have to do a linear traversal each time?
                Debug.Assert(this.isNested);

                this.isNested = false;
                int vtableLength = 4 + 2 * (this.maxIndexWithValue + 1);

                Span <byte> currentVTable = this.vTableBuffer.AsSpan().Slice(0, vtableLength);

                var context = this.context;
                writer.WriteUShort(currentVTable, (ushort)vtableLength, 0, context);
                writer.WriteUShort(currentVTable, (ushort)tableLength, sizeof(ushort), context);

                var offsets     = this.vtableOffsets;
                int offsetCount = offsets.Count;

                for (int i = 0; i < offsetCount; ++i)
                {
                    int offset = offsets[i];
                    ReadOnlySpan <byte> existingVTable = buffer.Slice(offset);
                    existingVTable = existingVTable.Slice(0, BinaryPrimitives.ReadUInt16LittleEndian(existingVTable));

                    if (existingVTable.SequenceEqual(currentVTable))
                    {
                        // We already have a vtable that matches this specification. Return that offset.
                        return(offset);
                    }
                }

                // Oh, well. Write the new table.
                int newVTableOffset = context.AllocateSpace(vtableLength, sizeof(ushort));
                currentVTable.CopyTo(buffer.Slice(newVTableOffset, vtableLength));
                offsets.Add(newVTableOffset);

                return(newVTableOffset);
            }
        }
Пример #2
0
 /// <summary>
 /// Writes the given object to the given memory block.
 /// </summary>
 /// <returns>The length of data that was written to the memory block.</returns>
 public int Serialize <T>(T item, Span <byte> destination, SpanWriter writer) where T : class
 {
     return(this.GetOrCreateSerializer <T>().Write(writer, destination, item));
 }