diff --git a/projects/RabbitMQ.Client/client/impl/WireFormatting.cs b/projects/RabbitMQ.Client/client/impl/WireFormatting.cs index 1ade155571..bcde4bf165 100644 --- a/projects/RabbitMQ.Client/client/impl/WireFormatting.cs +++ b/projects/RabbitMQ.Client/client/impl/WireFormatting.cs @@ -432,8 +432,13 @@ public static int WriteShortstr(Memory memory, string val) if (MemoryMarshal.TryGetArray(memory, out ArraySegment segment)) { int bytesWritten = Encoding.UTF8.GetBytes(val, 0, val.Length, segment.Array, segment.Offset + 1); - memory.Span[0] = (byte)bytesWritten; - return bytesWritten + 1; + if (bytesWritten <= byte.MaxValue) + { + memory.Span[0] = (byte)bytesWritten; + return bytesWritten + 1; + } + + throw new ArgumentOutOfRangeException(nameof(val), val, "Value exceeds the maximum allowed length of 255 bytes."); } throw new WireFormattingException("Unable to get array segment from memory."); diff --git a/projects/Unit/TestFieldTableFormatting.cs b/projects/Unit/TestFieldTableFormatting.cs index 7f26c0e743..1025adb7a4 100644 --- a/projects/Unit/TestFieldTableFormatting.cs +++ b/projects/Unit/TestFieldTableFormatting.cs @@ -38,6 +38,7 @@ // Copyright (c) 2007-2020 VMware, Inc. All rights reserved. //--------------------------------------------------------------------------- +using System; using System.Collections; using System.Text; @@ -127,6 +128,20 @@ public void TestTableEncoding_x() }); } + [Test] + public void TestTableEncoding_LongKey() + { + const int TooLarge = 256; + Hashtable t = new Hashtable + { + [new string('A', TooLarge)] = null + }; + int bytesNeeded = WireFormatting.GetTableByteCount(t); + byte[] bytes = new byte[bytesNeeded]; + + Assert.Throws(() => WireFormatting.WriteTable(bytes, t)); + } + [Test] public void TestQpidJmsTypes() {