diff --git a/jose-jwt/compression/CappedMemoryStream.cs b/jose-jwt/compression/CappedMemoryStream.cs new file mode 100644 index 00000000..2d7fb9ea --- /dev/null +++ b/jose-jwt/compression/CappedMemoryStream.cs @@ -0,0 +1,34 @@ +using System; +using System.IO; + +namespace Jose; + +public class CappedMemoryStream : MemoryStream +{ + private readonly long maxCapacity; + + public CappedMemoryStream(long maxCapacity) + { + this.maxCapacity = maxCapacity; + } + + public override void Write(byte[] buffer, int offset, int count) + { + if (Length + Math.Min(count, buffer.Length - offset) > maxCapacity) + { + throw new NotSupportedException("Exceeding maximum memory stream size."); + } + + base.Write(buffer, offset, count); + } + + public override void WriteByte(byte value) + { + if (Length + 1 > maxCapacity) + { + throw new NotSupportedException("Exceeding maximum memory stream size."); + } + + base.WriteByte(value); + } +} \ No newline at end of file