Repository navigation
Expand file tree
/
Copy pathbinascii.cs
More file actions
470 lines (404 loc) · 18.5 KB
/
Copy pathbinascii.cs
File metadata and controls
470 lines (404 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("binascii", typeof(IronPython.Modules.PythonBinaryAscii))]
namespace IronPython.Modules {
public static class PythonBinaryAscii {
public const string __doc__ = "Provides functions for converting between binary data encoded in various formats and ASCII.";
private static readonly object _ErrorKey = new object();
private static readonly object _IncompleteKey = new object();
private static Exception Error(CodeContext/*!*/ context, params object[] args) {
return PythonExceptions.CreateThrowable((PythonType)PythonContext.GetContext(context).GetModuleState(_ErrorKey), args);
}
private static Exception Incomplete(CodeContext/*!*/ context, params object[] args) {
return PythonExceptions.CreateThrowable((PythonType)PythonContext.GetContext(context).GetModuleState(_IncompleteKey), args);
}
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.EnsureModuleException(_ErrorKey, dict, "Error", "binascii");
context.EnsureModuleException(_IncompleteKey, dict, "Incomplete", "binascii");
}
private static int UuDecFunc(char val) {
if (val > 32 && val < 96) return val - 32;
switch (val) {
case '\n':
case '\r':
case (char)32:
case (char)96:
return EmptyByte;
default:
return InvalidByte;
}
}
public static string a2b_uu(CodeContext/*!*/ context, string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
if (data.Length < 1) return new string(Char.MinValue, 32);
int lenDec = (data[0] + 32) % 64; // decoded length in bytes
int lenEnc = (lenDec * 4 + 2) / 3; // encoded length in 6-bit chunks
string suffix = null;
if (data.Length - 1 > lenEnc) {
suffix = data.Substring(1 + lenEnc);
data = data.Substring(1, lenEnc);
} else {
data = data.Substring(1);
}
StringBuilder res = DecodeWorker(context, data, true, UuDecFunc);
if (suffix == null) {
res.Append((char)0, lenDec - res.Length);
} else {
ProcessSuffix(context, suffix, UuDecFunc);
}
return res.ToString();
}
public static string b2a_uu(CodeContext/*!*/ context, string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
if (data.Length > 45) throw Error(context, "At most 45 bytes at once");
StringBuilder res = EncodeWorker(data, ' ', delegate(int val) {
return (char)(32 + (val % 64));
});
res.Insert(0, ((char)(32 + data.Length)).ToString());
res.Append('\n');
return res.ToString();
}
private static int Base64DecFunc(char val) {
if (val >= 'A' && val <= 'Z') return val - 'A';
if (val >= 'a' && val <= 'z') return val - 'a' + 26;
if (val >= '0' && val <= '9') return val - '0' + 52;
switch (val) {
case '+':
return 62;
case '/':
return 63;
case '=':
return PadByte;
default:
return IgnoreByte;
}
}
public static object a2b_base64(CodeContext/*!*/ context, [BytesConversion]string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
data = RemovePrefix(context, data, Base64DecFunc);
if (data.Length == 0) return String.Empty;
StringBuilder res = DecodeWorker(context, data, false, Base64DecFunc);
return res.ToString();
}
public static object b2a_base64([BytesConversion]string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
if (data.Length == 0) return String.Empty;
StringBuilder res = EncodeWorker(data, '=', EncodeValue);
res.Append('\n');
return res.ToString();
}
private static char EncodeValue(int val) {
if (val < 26) return (char)('A' + val);
if (val < 52) return (char)('a' + val - 26);
if (val < 62) return (char)('0' + val - 52);
switch (val) {
case 62:
return '+';
case 63:
return '/';
default:
throw new InvalidOperationException(String.Format("Bad int val: {0}", val));
}
}
public static object a2b_qp(object data) {
throw new NotImplementedException();
}
[LightThrowing]
public static object a2b_qp(object data, object header) {
return LightExceptions.Throw(new NotImplementedException());
}
public static object b2a_qp(object data) {
throw new NotImplementedException();
}
public static object b2a_qp(object data, object quotetabs) {
throw new NotImplementedException();
}
public static object b2a_qp(object data, object quotetabs, object istext) {
throw new NotImplementedException();
}
public static object b2a_qp(object data, object quotetabs, object istext, object header) {
throw new NotImplementedException();
}
public static object a2b_hqx(object data) {
throw new NotImplementedException();
}
public static object rledecode_hqx(object data) {
throw new NotImplementedException();
}
public static object rlecode_hqx(object data) {
throw new NotImplementedException();
}
public static object b2a_hqx(object data) {
throw new NotImplementedException();
}
public static object crc_hqx(object data, object crc) {
throw new NotImplementedException();
}
[Documentation("crc32(string[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of string.")]
public static int crc32(string buffer, [DefaultParameterValue(0)] int baseValue) {
byte[] data = buffer.MakeByteArray();
uint result = crc32(data, 0, data.Length, unchecked((uint)baseValue));
return unchecked((int)result);
}
[Documentation("crc32(string[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of string.")]
public static int crc32(string buffer, uint baseValue) {
byte[] data = buffer.MakeByteArray();
uint result = crc32(data, 0, data.Length, baseValue);
return unchecked((int)result);
}
[Documentation("crc32(byte_array[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of byte_array.")]
public static int crc32(byte[] buffer, [DefaultParameterValue(0)] int baseValue) {
uint result = crc32(buffer, 0, buffer.Length, unchecked((uint)baseValue));
return unchecked((int)result);
}
[Documentation("crc32(byte_array[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of byte_array.")]
public static int crc32(byte[] buffer, uint baseValue) {
uint result = crc32(buffer, 0, buffer.Length, baseValue);
return unchecked((int)result);
}
internal static uint crc32(byte[] buffer, int offset, int count, uint baseValue) {
uint remainder = (baseValue ^ 0xffffffff);
for (int i = offset; i < offset + count; i++) {
remainder = remainder ^ buffer[i];
for (int j = 0; j < 8; j++) {
if ((remainder & 0x01) != 0) {
remainder = (remainder >> 1) ^ 0xEDB88320;
} else {
remainder = (remainder >> 1);
}
}
}
return (remainder ^ 0xffffffff);
}
public static string b2a_hex(string data) {
StringBuilder sb = new StringBuilder(data.Length * 2);
for (int i = 0; i < data.Length; i++) {
sb.AppendFormat("{0:x2}", (int)data[i]);
}
return sb.ToString();
}
public static string hexlify(string data) {
return b2a_hex(data);
}
public static Bytes hexlify(MemoryView data) {
return hexlify(data.tobytes());
}
public static Bytes hexlify(Bytes data) {
byte[] res = new byte[data.Count * 2];
for (int i = 0; i < data.Count; i++) {
res[i * 2] = ToHex(data._bytes[i] >> 4);
res[(i * 2) + 1] = ToHex(data._bytes[i] & 0x0F);
}
return Bytes.Make(res);
}
private static byte ToHex(int p) {
if (p >= 10) {
return (byte)('a' + p - 10);
}
return (byte)('0' + p);
}
public static string hexlify([NotNull]PythonBuffer data) {
return hexlify(data.ToString());
}
public static object a2b_hex(CodeContext/*!*/ context, string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
if ((data.Length & 0x01) != 0) throw Error(context, "string must be even lengthed");
StringBuilder res = new StringBuilder(data.Length / 2);
for (int i = 0; i < data.Length; i += 2) {
byte b1, b2;
if (Char.IsDigit(data[i])) b1 = (byte)(data[i] - '0');
else b1 = (byte)(Char.ToUpper(data[i]) - 'A' + 10);
if (Char.IsDigit(data[i + 1])) b2 = (byte)(data[i + 1] - '0');
else b2 = (byte)(Char.ToUpper(data[i + 1]) - 'A' + 10);
res.Append((char)(b1 * 16 + b2));
}
return res.ToString();
}
public static object unhexlify(CodeContext/*!*/ context, string hexstr) {
return a2b_hex(context, hexstr);
}
#region Private implementation
private delegate char EncodeChar(int val);
private delegate int DecodeByte(char val);
private static StringBuilder EncodeWorker(string data, char empty, EncodeChar encFunc) {
StringBuilder res = new StringBuilder();
int bits;
for (int i = 0; i < data.Length; i += 3) {
switch (data.Length - i) {
case 1:
// only one char, emit 2 bytes &
// padding
bits = (data[i] & 0xff) << 16;
res.Append(encFunc((bits >> 18) & 0x3f));
res.Append(encFunc((bits >> 12) & 0x3f));
res.Append(empty);
res.Append(empty);
break;
case 2:
// only two chars, emit 3 bytes &
// padding
bits = ((data[i] & 0xff) << 16) | ((data[i + 1] & 0xff) << 8);
res.Append(encFunc((bits >> 18) & 0x3f));
res.Append(encFunc((bits >> 12) & 0x3f));
res.Append(encFunc((bits >> 6) & 0x3f));
res.Append(empty);
break;
default:
// got all 3 bytes, just emit it.
bits = ((data[i] & 0xff) << 16) |
((data[i + 1] & 0xff) << 8) |
((data[i + 2] & 0xff));
res.Append(encFunc((bits >> 18) & 0x3f));
res.Append(encFunc((bits >> 12) & 0x3f));
res.Append(encFunc((bits >> 6) & 0x3f));
res.Append(encFunc(bits & 0x3f));
break;
}
}
return res;
}
private const int IgnoreByte = -1; // skip this byte
private const int EmptyByte = -2; // byte evaluates to 0 and may appear off the end of the stream
private const int PadByte = -3; // pad bytes signal the end of the stream, unless there are too few to properly align
private const int InvalidByte = -4; // raise exception for illegal byte
private const int NoMoreBytes = -5; // signals end of stream
private static int NextVal(CodeContext/*!*/ context, string data, ref int index, DecodeByte decFunc) {
int res;
while (index < data.Length) {
res = decFunc(data[index++]);
switch (res) {
case EmptyByte:
return 0;
case InvalidByte:
throw Error(context, "Illegal char");
case IgnoreByte:
break;
default:
return res;
}
}
return NoMoreBytes;
}
private static int CountPadBytes(CodeContext/*!*/ context, string data, int bound, ref int index, DecodeByte decFunc) {
int res = PadByte;
int count = 0;
while ((bound < 0 || count < bound) &&
(res = NextVal(context, data, ref index, decFunc)) == PadByte) {
count++;
}
// we only want NextVal() to eat PadBytes - not real data
if (res != PadByte && res != NoMoreBytes) index--;
return count;
}
private static int GetVal(CodeContext/*!*/ context, string data, int align, bool bounded, ref int index, DecodeByte decFunc) {
int res;
while (true) {
res = NextVal(context, data, ref index, decFunc);
switch (res) {
case PadByte:
switch (align) {
case 0:
case 1:
CountPadBytes(context, data, -1, ref index, decFunc);
continue;
case 2:
if (CountPadBytes(context, data, 1, ref index, decFunc) > 0) {
return NoMoreBytes;
} else {
continue;
}
default:
return NoMoreBytes;
}
case NoMoreBytes:
if (bounded || align == 0) {
return NoMoreBytes;
} else {
throw Error(context, "Incorrect padding");
}
case EmptyByte:
return 0;
default:
return res;
}
}
}
private static StringBuilder DecodeWorker(CodeContext/*!*/ context, string data, bool bounded, DecodeByte decFunc) {
StringBuilder res = new StringBuilder();
int i = 0;
while (i < data.Length) {
int intVal;
int val0 = GetVal(context, data, 0, bounded, ref i, decFunc);
if (val0 < 0) break; // no more bytes...
int val1 = GetVal(context, data, 1, bounded, ref i, decFunc);
if (val1 < 0) break; // no more bytes...
int val2 = GetVal(context, data, 2, bounded, ref i, decFunc);
if (val2 < 0) {
// 2 byte partial
intVal = (val0 << 18) | (val1 << 12);
res.Append((char)((intVal >> 16) & 0xff));
break;
}
int val3 = GetVal(context, data, 3, bounded, ref i, decFunc);
if (val3 < 0) {
// 3 byte partial
intVal = (val0 << 18) | (val1 << 12) | (val2 << 6);
res.Append((char)((intVal >> 16) & 0xff));
res.Append((char)((intVal >> 8) & 0xff));
break;
}
// full 4-bytes
intVal = (val0 << 18) | (val1 << 12) | (val2 << 6) | (val3);
res.Append((char)((intVal >> 16) & 0xff));
res.Append((char)((intVal >> 8) & 0xff));
res.Append((char)(intVal & 0xff));
}
return res;
}
private static string RemovePrefix(CodeContext/*!*/ context, string data, DecodeByte decFunc) {
int count = 0;
while (count < data.Length) {
int current = decFunc(data[count]);
if (current == InvalidByte) {
throw Error(context, "Illegal char");
}
if (current >= 0) break;
count++;
}
return count == 0 ? data : data.Substring(count);
}
private static void ProcessSuffix(CodeContext/*!*/ context, string data, DecodeByte decFunc) {
for (int i = 0; i < data.Length; i++) {
int current = decFunc(data[i]);
if (current >= 0 || current == InvalidByte) {
throw Error(context, "Trailing garbage");
}
}
}
#endregion
}
}