Skip to content

Commit 0635621

Browse files
committed
significantly simplified Asn1Utils.Encode method.
1 parent a151d26 commit 0635621

1 file changed

Lines changed: 14 additions & 39 deletions

File tree

Asn1Parser/Asn1Utils.cs

Lines changed: 14 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -114,48 +114,23 @@ public static Byte[] Encode(Byte[] rawData, Byte enclosingTag) {
114114
/// <returns>Wrapped encoded byte array.</returns>
115115
/// <remarks>If <strong>rawData</strong> is null, an empty tag is encoded.</remarks>
116116
public static ReadOnlyMemory<Byte> Encode(ReadOnlySpan<Byte> rawData, Byte enclosingTag) {
117-
Byte[] retValue;
118117
if (rawData.Length == 0) {
119-
retValue = [enclosingTag, 0];
120-
121-
return retValue;
118+
return new Byte[] { enclosingTag, 0 };
119+
}
120+
ReadOnlySpan<Byte> pbHeader = GetLengthBytesAsMemory(rawData.Length).Span;
121+
// copy T component to destination array.
122+
Byte[] retValue = new Byte[1 + pbHeader.Length + rawData.Length];
123+
// copy L component to destination array
124+
retValue[0] = enclosingTag;
125+
for (Int32 i = 0; i < pbHeader.Length; i++) {
126+
retValue[i + 1] = pbHeader[i];
122127
}
123-
if (rawData.Length < 128) {
124-
// pre-create destination array of fixed size.
125-
retValue = new Byte[rawData.Length + 2];
126-
// populate TL components of TLV
127-
retValue[0] = enclosingTag;
128-
retValue[1] = (Byte)rawData.Length;
129-
// copy input buffer to V component
130-
for (Int32 index = 0; index < rawData.Length; index++) {
131-
retValue[index + 2] = rawData[index];
132-
}
133-
} else {
134-
Byte[] lenBytes = new Byte[4];
135-
Int32 num = rawData.Length;
136-
Int32 counter = 0;
137-
while (num >= 256) {
138-
lenBytes[counter] = (Byte)(num & 255);
139-
num >>= 8;
140-
counter++;
141-
}
142-
// 3 is: len byte and enclosing tag
143-
// pre-create destination array of fixed size.
144-
retValue = new Byte[rawData.Length + 3 + counter];
145-
// copy input buffer to V component
146-
for (Int32 index = 0; index < rawData.Length; index++) {
147-
retValue[index + 3 + counter] = rawData[index];
148-
}
149-
// populate TL components of TLV
150-
retValue[0] = enclosingTag;
151-
retValue[1] = (Byte)(129 + counter);
152-
retValue[2] = (Byte)num;
153-
Int32 n = 3;
154-
for (Int32 i = counter - 1; i >= 0; i--) {
155-
retValue[n] = lenBytes[i];
156-
n++;
157-
}
128+
Int32 shift = 1 + pbHeader.Length;
129+
// copy V component to destination array
130+
for (Int32 i = 0; i < rawData.Length; i++) {
131+
retValue[i + shift] = rawData[i];
158132
}
133+
159134
return retValue;
160135
}
161136
/// <summary>

0 commit comments

Comments
 (0)