From 21a69a8385d0d23504892d2af51af2271b2675f9 Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Tue, 7 Jul 2020 20:00:51 +0700 Subject: Rewrite enumeration of BEROctetString --- crypto/src/asn1/BerOctetString.cs | 69 ++++++++++++++++++++++++++++----------- 1 file changed, 50 insertions(+), 19 deletions(-) (limited to 'crypto/src/asn1') diff --git a/crypto/src/asn1/BerOctetString.cs b/crypto/src/asn1/BerOctetString.cs index fb4291612..f41aaf6a5 100644 --- a/crypto/src/asn1/BerOctetString.cs +++ b/crypto/src/asn1/BerOctetString.cs @@ -88,9 +88,7 @@ namespace Org.BouncyCastle.Asn1 public IEnumerator GetEnumerator() { if (octs == null) - { - return GenerateOcts().GetEnumerator(); - } + return new ChunkEnumerator(str, chunkSize); return octs.GetEnumerator(); } @@ -101,22 +99,6 @@ namespace Org.BouncyCastle.Asn1 return GetEnumerator(); } - private IList GenerateOcts() - { - IList vec = Platform.CreateArrayList(); - for (int i = 0; i < str.Length; i += chunkSize) - { - int end = System.Math.Min(str.Length, i + chunkSize); - - byte[] nStr = new byte[end - i]; - - Array.Copy(str, i, nStr, 0, nStr.Length); - - vec.Add(new DerOctetString(nStr)); - } - return vec; - } - internal override void Encode( DerOutputStream derOut) { @@ -142,5 +124,54 @@ namespace Org.BouncyCastle.Asn1 base.Encode(derOut); } } + + private class ChunkEnumerator + : IEnumerator + { + private readonly byte[] octets; + private readonly int chunkSize; + + private DerOctetString currentChunk = null; + private int nextChunkPos = 0; + + internal ChunkEnumerator(byte[] octets, int chunkSize) + { + this.octets = octets; + this.chunkSize = chunkSize; + } + + public object Current + { + get + { + if (null == currentChunk) + throw new InvalidOperationException(); + + return currentChunk; + } + } + + public bool MoveNext() + { + if (nextChunkPos >= octets.Length) + { + this.currentChunk = null; + return false; + } + + int length = System.Math.Min(octets.Length - nextChunkPos, chunkSize); + byte[] chunk = new byte[length]; + Array.Copy(octets, nextChunkPos, chunk, 0, length); + this.currentChunk = new DerOctetString(chunk); + this.nextChunkPos += length; + return true; + } + + public void Reset() + { + this.currentChunk = null; + this.nextChunkPos = 0; + } + } } } -- cgit 1.4.1