public static T FromStream <T>(Stream stream, int version) where T : MessageBase <T> { if (stream == null) { throw new ArgumentException("stream", nameof(stream)); } try { return(MessageBase <T> .Import(Decompress(RemoveVersion(stream, version)), _bufferManager)); } catch (Exception e) { Log.Debug(e); return(null); } }
private static T FromStream <T>(int version, Stream stream) where T : MessageBase <T> { try { stream.Seek(0, SeekOrigin.Begin); // Check { var verifyCrc = Crc32_Castagnoli.Compute(new RangeStream(stream, 0, stream.Length - 4, true)); var orignalCrc = new byte[4]; using (var crcStream = new RangeStream(stream, stream.Length - 4, 4, true)) { crcStream.Read(orignalCrc, 0, orignalCrc.Length); } if (!Unsafe.Equals(verifyCrc, orignalCrc)) { throw new ArgumentException("Crc Error"); } } stream.Seek(0, SeekOrigin.Begin); if (version != (int)Varint.GetUInt64(stream)) { throw new ArgumentException("version"); } int type = (int)Varint.GetUInt64(stream); using (var dataStream = new RangeStream(stream, stream.Position, stream.Length - stream.Position - 4, true)) { if (type == (int)ConvertCompressionAlgorithm.None) { return(MessageBase <T> .Import(dataStream, _bufferManager)); } else if (type == (int)ConvertCompressionAlgorithm.Deflate) { using (var deflateBufferStream = new RecyclableMemoryStream(_bufferManager)) { using (var deflateStream = new DeflateStream(dataStream, CompressionMode.Decompress, true)) using (var safeBuffer = _bufferManager.CreateSafeBuffer(1024 * 4)) { int length; while ((length = deflateStream.Read(safeBuffer.Value, 0, safeBuffer.Value.Length)) > 0) { deflateBufferStream.Write(safeBuffer.Value, 0, length); if (deflateBufferStream.Length > 1024 * 1024 * 32) { throw new Exception("too large"); } } } deflateBufferStream.Seek(0, SeekOrigin.Begin); return(MessageBase <T> .Import(deflateBufferStream, _bufferManager)); } } else { throw new ArgumentException("ArgumentException"); } } } catch (Exception e) { throw new ArgumentException(e.Message, e); } finally { if (stream != null) { stream.Dispose(); } } }