1 #region Copyright notice and license 2 // Protocol Buffers - Google's data interchange format 3 // Copyright 2015 Google Inc. All rights reserved. 4 // 5 // Use of this source code is governed by a BSD-style 6 // license that can be found in the LICENSE file or at 7 // https://developers.google.com/open-source/licenses/bsd 8 #endregion 9 10 using System; 11 using System.IO; 12 13 namespace Google.Protobuf 14 { 15 /// <summary> 16 /// Stream implementation which proxies another stream, only allowing a certain amount 17 /// of data to be read. Note that this is only used to read delimited streams, so it 18 /// doesn't attempt to implement everything. 19 /// </summary> 20 internal sealed class LimitedInputStream : Stream 21 { 22 private readonly Stream proxied; 23 private int bytesLeft; 24 LimitedInputStream(Stream proxied, int size)25 internal LimitedInputStream(Stream proxied, int size) 26 { 27 this.proxied = proxied; 28 bytesLeft = size; 29 } 30 31 public override bool CanRead => true; 32 public override bool CanSeek => false; 33 public override bool CanWrite => false; 34 Flush()35 public override void Flush() 36 { 37 } 38 39 public override long Length => throw new NotSupportedException(); 40 41 public override long Position 42 { 43 get => throw new NotSupportedException(); 44 set => throw new NotSupportedException(); 45 } 46 Read(byte[] buffer, int offset, int count)47 public override int Read(byte[] buffer, int offset, int count) 48 { 49 if (bytesLeft > 0) 50 { 51 int bytesRead = proxied.Read(buffer, offset, Math.Min(bytesLeft, count)); 52 bytesLeft -= bytesRead; 53 return bytesRead; 54 } 55 return 0; 56 } 57 Seek(long offset, SeekOrigin origin)58 public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); 59 SetLength(long value)60 public override void SetLength(long value) => throw new NotSupportedException(); 61 Write(byte[] buffer, int offset, int count)62 public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); 63 } 64 } 65