From 88d4a5630250ab0a2effdec63a8bddf4c74ff332 Mon Sep 17 00:00:00 2001 From: Justin Masters Date: Thu, 12 Dec 2024 21:53:12 +1100 Subject: [PATCH] Add CappedMemoryStream --- jose-jwt/compression/CappedMemoryStream.cs | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 jose-jwt/compression/CappedMemoryStream.cs 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