private static Pooled <ByteBuffer> ToBuffer(this Stream stream) { // TODO .Net 4.6 //var ms = stream as MemoryStream; //if (ms != null) //{ // ArraySegment<byte> msBuffer; // if (ms.TryGetBuffer(out msBuffer)) // { // return new PooledBuffer(msBuffer.Array, msBuffer.Offset, msBuffer.Count); // } //} int count; Pooled <ByteBuffer> pooled; bool hasLength; if (stream.CanSeek) { hasLength = true; count = (int)(stream.Length - stream.Position); pooled = SerializerBuffers.Get(count); } else { hasLength = false; pooled = SerializerBuffers.Get(DefaultBufferSize); count = pooled.Item.BufferLength; } var buf = pooled.Item; var offset = 0; while (true) { var read = stream.Read(buf.Buffer, offset, count); // exit on EOF if (read == 0) { break; } offset += read; count -= read; // we have more to read if (count != 0) { continue; } // if length was known - just break if (hasLength) { break; } // grow buffer and set new count buf.Grow(); count = buf.BufferLength - offset; } // set actual bytes read buf.SetView(0, offset); return(pooled); }
public static Pooled <ByteBuffer> SerializePooled <T>(T item) where T : IMessage { var calcSize = new ProtoSizeCalc(item); var result = SerializerBuffers.Get(calcSize.Size); var buf = result.Item; var stream = new ProtoOutputStream(calcSize, buf.Buffer); item.WriteTo(stream); buf.SetView(0, calcSize.Size); return(result); }