summary refs log tree commit diff
path: root/crypto/src/asn1/Asn1OutputStream.cs
diff options
context:
space:
mode:
authorPeter Dettman <peter.dettman@bouncycastle.org>2022-11-01 14:39:54 +0700
committerPeter Dettman <peter.dettman@bouncycastle.org>2022-11-01 14:39:54 +0700
commit716a491e3ed312da6c80a74e327d62dd4388b11e (patch)
tree0adabea28431857f372256233ddd4b2e0982190b /crypto/src/asn1/Asn1OutputStream.cs
parentPackage with LICENSE.md file (diff)
downloadBouncyCastle.NET-ed25519-716a491e3ed312da6c80a74e327d62dd4388b11e.tar.xz
More Span-based Stream methods
Diffstat (limited to 'crypto/src/asn1/Asn1OutputStream.cs')
-rw-r--r--crypto/src/asn1/Asn1OutputStream.cs16
1 files changed, 11 insertions, 5 deletions
diff --git a/crypto/src/asn1/Asn1OutputStream.cs b/crypto/src/asn1/Asn1OutputStream.cs
index 59178ea31..163e3848c 100644
--- a/crypto/src/asn1/Asn1OutputStream.cs
+++ b/crypto/src/asn1/Asn1OutputStream.cs
@@ -1,5 +1,10 @@
 using System;
 using System.IO;
+using System.Diagnostics;
+#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
+using System.Buffers.Binary;
+using System.Numerics;
+#endif
 
 using Org.BouncyCastle.Utilities.IO;
 
@@ -73,15 +78,19 @@ namespace Org.BouncyCastle.Asn1
         {
             if (dl < 128)
             {
+                Debug.Assert(dl >= 0);
                 WriteByte((byte)dl);
                 return;
             }
 
 #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
-            Span<byte> stack = stackalloc byte[5];
+            Span<byte> encoding = stackalloc byte[5];
+            BinaryPrimitives.WriteUInt32BigEndian(encoding[1..], (uint)dl);
+            int leadingZeroBytes = BitOperations.LeadingZeroCount((uint)dl) / 8;
+            encoding[leadingZeroBytes] = (byte)(0x84 - leadingZeroBytes);
+            Write(encoding[leadingZeroBytes..]);
 #else
             byte[] stack = new byte[5];
-#endif
             int pos = stack.Length;
 
             do
@@ -94,9 +103,6 @@ namespace Org.BouncyCastle.Asn1
             int count = stack.Length - pos;
             stack[--pos] = (byte)(0x80 | count);
 
-#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
-            Write(stack[pos..]);
-#else
             Write(stack, pos, count + 1);
 #endif
         }