summary refs log tree commit diff
path: root/crypto/src/util/encoders/HexEncoder.cs
diff options
context:
space:
mode:
authorPeter Dettman <peter.dettman@bouncycastle.org>2023-04-11 18:33:01 +0700
committerPeter Dettman <peter.dettman@bouncycastle.org>2023-04-11 18:33:01 +0700
commitdb4e4f5a6ff5348cb6279baa997e361b6c47fcbb (patch)
treeac84d5387f10063922cdcf273b11d5bd5b7d07ca /crypto/src/util/encoders/HexEncoder.cs
parentAdd Memory/Span accessors to avoid some copies (diff)
downloadBouncyCastle.NET-ed25519-db4e4f5a6ff5348cb6279baa997e361b6c47fcbb.tar.xz
Reduce allocations in hex encoding
Diffstat (limited to '')
-rw-r--r--crypto/src/util/encoders/HexEncoder.cs39
1 files changed, 39 insertions, 0 deletions
diff --git a/crypto/src/util/encoders/HexEncoder.cs b/crypto/src/util/encoders/HexEncoder.cs
index a36f31dbd..05933af05 100644
--- a/crypto/src/util/encoders/HexEncoder.cs
+++ b/crypto/src/util/encoders/HexEncoder.cs
@@ -6,6 +6,45 @@ namespace Org.BouncyCastle.Utilities.Encoders
     public class HexEncoder
         : IEncoder
     {
+        private static readonly char[] CharsLower = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+        private static readonly char[] CharsUpper = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+
+#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
+        internal static int EncodeLower(ReadOnlySpan<byte> input, Span<char> output)
+        {
+            int inPos = 0;
+            int inEnd = input.Length;
+            int outPos = 0;
+
+            while (inPos < inEnd)
+            {
+                uint b = input[inPos++];
+
+                output[outPos++] = CharsLower[b >> 4];
+                output[outPos++] = CharsLower[b & 0xF];
+            }
+
+            return outPos;
+        }
+
+        internal static int EncodeUpper(ReadOnlySpan<byte> input, Span<char> output)
+        {
+            int inPos = 0;
+            int inEnd = input.Length;
+            int outPos = 0;
+
+            while (inPos < inEnd)
+            {
+                uint b = input[inPos++];
+
+                output[outPos++] = CharsUpper[b >> 4];
+                output[outPos++] = CharsUpper[b & 0xF];
+            }
+
+            return outPos;
+        }
+#endif
+
         protected readonly byte[] encodingTable =
         {
             (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',