-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQrSegment.cs
475 lines (412 loc) · 18.6 KB
/
QrSegment.cs
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
471
472
473
474
475
/*
* QR code generator library (.NET)
*
* Copyright (c) Manuel Bleichenbacher (MIT License)
* https://github.com/manuelbl/QrCodeGenerator
* Copyright (c) Project Nayuki (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
* Copyright (c) [email protected] (MIT License)
* https://ardeshirv.github.io/ArdeshirV.Utility.QrCode/
* Downgrade to C# 2.0 by ArdeshirV
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
using System;
using System.Text;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ArdeshirV.Tools.QrCode
{
/// <summary>
/// Represents a segment of character/binary/control data in a QR code symbol.
/// </summary>
/// <remarks>
/// <para>
/// The easiest way to deal with QR code segments is to call
/// <see cref="QrCode.EncodeText"/> or <see cref="QrCode.EncodeBinary"/>, and not
/// to use instances of this class directly. The mid-level way is to take the payload
/// data and call a static factory function such as <see cref="MakeNumeric(string)"/>.
/// The low-level way is to custom-make the bit array and call the
/// <see cref="QrSegment(Mode, int, BitArray)"/> constructor with appropriate values.
/// </para>
/// <para>
/// This segment class imposes no length restrictions, but QR codes have restrictions.
/// Even in the most favorable conditions, a QR code can only hold 7089 characters of data.
/// Any segment longer than this is meaningless for the purpose of generating QR codes.
/// </para>
/// <para>
/// This class can represent kanji mode segments, but provides no help in encoding them
/// - see <see cref="QrSegmentAdvanced"/> for full kanji support.
/// </para>
/// <para>
/// Instances of this class are immutable.
/// </para>
/// </remarks>
public class QrSegment
{
#region Static factory functions (mid level)
/// <summary>
/// Creates a segment representing the specified binary data
/// encoded in byte mode. All input byte arrays are acceptable.
/// <para>
/// Any text string can be converted to UTF-8 bytes (using <c>Encoding.UTF8.GetBytes(str)</c>)
/// and encoded as a byte mode segment.
/// </para>
/// </summary>
/// <param name="data">The binary data to encode.</param>
/// <returns>The created segment containing the specified data.</returns>
/// <exception cref="ArgumentNullException"><c>data</c> is <c>null</c>.</exception>
public static QrSegment MakeBytes(byte[] data)
{
Objects.RequireNonNull(data);
BitArray ba = new BitArray(0);
foreach (byte b in data)
{
BitArrayExtensions.AppendBits(ba, b, 8);
}
return new QrSegment(Mode.Byte, data.Length, ba);
}
/// <summary>
/// Creates a segment representing the specified string of decimal digits.
/// The segment is encoded in numeric mode.
/// </summary>
/// <param name="digits">The text to encode, consisting of digits from 0 to 9 only.</param>
/// <returns>The created segment containing the text.</returns>
/// <exception cref="ArgumentNullException"><c>digits</c> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><c>digits</c> contains non-digit characters</exception>
public static QrSegment MakeNumeric(string digits)
{
Objects.RequireNonNull(digits);
if (!NumericRegex.IsMatch(digits))
{
throw new ArgumentOutOfRangeException(nameof(digits), "String contains non-numeric characters");
}
BitArray ba = new BitArray(0);
for (int i = 0; i < digits.Length;)
{
// Consume up to 3 digits per iteration
int n = Math.Min(digits.Length - i, 3);
BitArrayExtensions.AppendBits(ba, uint.Parse(digits.Substring(i, n)), n * 3 + 1);
i += n;
}
return new QrSegment(Mode.Numeric, digits.Length, ba);
}
private static string nameof(object obj) {
return obj.GetType().Name;
}
/// <summary>
/// Creates a segment representing the specified text string.
/// The segment is encoded in alphanumeric mode.
/// <para>
/// Allowed characters are: 0 to 9, A to Z (uppercase only), space,
/// dollar, percent, asterisk, plus, hyphen, period, slash, colon.
/// </para>
/// </summary>
/// <param name="text">The text to encode, consisting of allowed characters only.</param>
/// <returns>The created segment containing the text.</returns>
/// <exception cref="ArgumentNullException"><c>text</c> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><c>text</c> contains non-encodable characters.</exception>
public static QrSegment MakeAlphanumeric(string text)
{
Objects.RequireNonNull(text);
if (!AlphanumericRegex.IsMatch(text))
{
throw new ArgumentOutOfRangeException(nameof(text), "String contains unencodable characters in alphanumeric mode");
}
BitArray ba = new BitArray(0);
int i;
for (i = 0; i <= text.Length - 2; i += 2)
{
// Process groups of 2
uint temp = (uint)AlphanumericCharset.IndexOf(text[i]) * 45;
temp += (uint)AlphanumericCharset.IndexOf(text[i + 1]);
BitArrayExtensions.AppendBits(ba, temp, 11);
}
if (i < text.Length) // 1 character remaining
{
BitArrayExtensions.AppendBits(ba, (uint)AlphanumericCharset.IndexOf(text[i]), 6);
}
return new QrSegment(Mode.Alphanumeric, text.Length, ba);
}
/// <summary>
/// Creates a list of zero or more segments representing the specified text string.
/// <para>
/// The text may contain the full range of Unicode characters.
/// </para>
/// <para>
/// The result may multiple segments with various encoding modes in order to minimize the length of the bit stream.
/// </para>
/// </summary>
/// <param name="text">The text to be encoded.</param>
/// <returns>The created mutable list of segments representing the specified text.</returns>
/// <exception cref="ArgumentNullException"><c>text</c> is <c>null</c>.</exception>
/// <remarks>
/// The current implementation does not use multiple segments.
/// </remarks>
public static List<QrSegment> MakeSegments(string text)
{
Objects.RequireNonNull(text);
// Select the most efficient segment encoding automatically
List<QrSegment> result = new List<QrSegment>();
if (text == "")
{
// Leave result empty
}
else if (NumericRegex.IsMatch(text))
{
result.Add(MakeNumeric(text));
}
else if (AlphanumericRegex.IsMatch(text))
{
result.Add(MakeAlphanumeric(text));
}
else
{
result.Add(MakeBytes(Encoding.UTF8.GetBytes(text)));
}
return result;
}
/// <summary>
/// Creates a segment representing an Extended Channel Interpretation
/// (ECI) designator with the specified assignment value.
/// </summary>
/// <param name="assignVal">The ECI assignment number (see the AIM ECI specification).</param>
/// <returns>The created segment containing the data.</returns>
/// <exception cref="ArgumentOutOfRangeException"><c>assignVal</c>is outside the range [0, 10<sup>6</sup>).</exception>
public static QrSegment MakeEci(int assignVal)
{
BitArray ba = new BitArray(0);
if (assignVal < 0)
{
throw new ArgumentOutOfRangeException(nameof(assignVal), "ECI assignment value out of range");
}
if (assignVal < 1 << 7)
{
BitArrayExtensions.AppendBits(ba, (uint)assignVal, 8);
}
else if (assignVal < 1 << 14)
{
BitArrayExtensions.AppendBits(ba, 2, 2);
BitArrayExtensions.AppendBits(ba, (uint)assignVal, 14);
}
else if (assignVal < 1000000)
{
BitArrayExtensions.AppendBits(ba, 6, 3);
BitArrayExtensions.AppendBits(ba, (uint)assignVal, 21);
}
else
{
throw new ArgumentOutOfRangeException(nameof(assignVal), "ECI assignment value out of range");
}
return new QrSegment(Mode.Eci, 0, ba);
}
#endregion
#region Instance fields
/// <summary>The encoding mode of this segment.</summary>
/// <value>Encoding mode.</value>
public Mode EncodingMode { get{return _EncodingMode;} private set{_EncodingMode = value;} }
private Mode _EncodingMode;
/// <summary>
/// The length of this segment's unencoded data.
/// <para>
/// Measured in characters for numeric/alphanumeric/kanji mode,
/// bytes for byte mode, and 0 for ECI mode.
/// </para>
/// <para>
/// Different from the data's bit length.
/// </para>
/// </summary>
/// <value>Length of the segment's unencoded data.</value>
public int NumChars { get{return _NumChars;} private set{_NumChars = value;} }
private int _NumChars;
// The data bits of this segment. Not null. Accessed through GetData().
private readonly BitArray _data;
#endregion
#region Constructor (low level)
/// <summary>
/// Initializes a QR code segment with the specified attributes and data.
/// <para>
/// The character count <paramref name="numChars"/> must agree with the mode and the bit array length,
/// but the constraint isn't checked. The specified bit array is cloned.
/// </para>
/// </summary>
/// <param name="mode">The segment mode used to encode this segment.</param>
/// <param name="numChars">The data length in characters or bytes (depending on the segment mode).</param>
/// <param name="data">The data bits.</param>
/// <exception cref="ArgumentNullException"><paramref name="mode"/> or <paramref name="data"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="numChars"/> is negative.</exception>
public QrSegment(Mode mode, int numChars, BitArray data)
{
EncodingMode = Objects.RequireNonNull(mode);
Objects.RequireNonNull(data);
if (numChars < 0)
{
throw new ArgumentOutOfRangeException(nameof(numChars), "Invalid value");
}
NumChars = numChars;
_data = (BitArray)data.Clone(); // Make defensive copy
}
#endregion
#region Methods
/// <summary>
/// Returns a copy of this segment's data bits.
/// </summary>
/// <returns>A copy of the data bits.</returns>
public BitArray GetData()
{
return (BitArray)_data.Clone(); // Make defensive copy
}
// Calculates the number of bits needed to encode the given segments at the given version.
// Returns a non-negative number if successful. Otherwise returns -1 if a segment has too
// many characters to fit its length field, or the total bits exceeds int.MaxValue.
internal static int GetTotalBits(List<QrSegment> segs, int version)
{
Objects.RequireNonNull(segs);
long result = 0;
foreach (QrSegment seg in segs)
{
Objects.RequireNonNull(seg);
int ccbits = seg.EncodingMode.NumCharCountBits(version);
if (seg.NumChars >= 1 << ccbits)
{
return -1; // The segment's length doesn't fit the field's bit width
}
result += 4L + ccbits + seg._data.Length;
if (result > int.MaxValue)
{
return -1; // The sum will overflow an int type
}
}
return (int)result;
}
#endregion
#region Constants
/// <summary>
/// Immutable regular expression describing all strings encodable in <i>numeric mode</i>.
/// <para>
/// A string is encodable iff each character is in the range 0 to 9.
/// </para>
/// </summary>
/// <remarks>
/// To test whether a string <c>s</c> is encodable:
/// <code>
/// bool ok = NumericRegex.IsMatch(s);
/// </code>
/// </remarks>
/// <value>Regular exprression describing strings encodable in numeric mode.</value>
/// <seealso cref="MakeNumeric(string)"/>
public static readonly Regex NumericRegex = new Regex("^[0-9]*$", RegexOptions.Compiled);
/// <summary>
/// Immutable regular expression describing all strings that are encodable in <i>alphanumeric mode</i>.
/// <para>
/// A string is encodable iff each character is in the following set: 0 to 9, A to Z
/// (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
/// </para>
/// </summary>
/// <remarks>
/// To test whether a string <c>s</c> is encodable:
/// <code>
/// bool ok = AlphanumericRegex.IsMatch(s);
/// </code>
/// </remarks>
/// <value>Regular exprression describing strings encodable in alphanumeric mode.</value>
/// <seealso cref="MakeAlphanumeric(string)"/>
public static readonly Regex AlphanumericRegex = new Regex("^[A-Z0-9 $%*+./:-]*$", RegexOptions.Compiled);
// The set of all legal characters in alphanumeric mode, where
// each character value maps to the index in the string.
internal static readonly string AlphanumericCharset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
#endregion
#region Public helper enumeration
/// <summary>
/// Segment encoding mode.
/// <para>
/// Describes how text or binary data is encoded into bits.
/// </para>
/// </summary>
public sealed class Mode
{
/// <summary>
/// Numeric encoding mode.
/// </summary>
/// <value>Numeric encoding mode.</value>
public static readonly Mode Numeric = new Mode(0x1, 10, 12, 14);
/// <summary>
/// Alphanumeric encoding mode.
/// </summary>
/// <value>Alphanumeric encoding mode.</value>
public static readonly Mode Alphanumeric = new Mode(0x2, 9, 11, 13);
/// <summary>
/// Byte encoding mode.
/// </summary>
/// <value>Byte encoding mode.</value>
public static readonly Mode Byte = new Mode(0x4, 8, 16, 16);
/// <summary>
/// Kanji encoding mode.
/// </summary>
/// <value>Kanji encoding mode.</value>
public static readonly Mode Kanji = new Mode(0x8, 8, 10, 12);
/// <summary>
/// ECI encoding mode.
/// </summary>
/// <value>ECI encoding mode.</value>
public static readonly Mode Eci = new Mode(0x7, 0, 0, 0);
/// <summary>
/// Mode indicator value.
/// <para>
/// 4 bit value in the QR segment header indicating the encoding mode.
/// </para>
/// </summary>
/// <value>Mode indicator value</value>
internal uint ModeBits { get{return _ModeBits;} private set{_ModeBits = value;} }
private uint _ModeBits;
/// <summary>
/// Array of character count bit length.
/// <para>
/// Number of bits for character count in QR segment header.
/// The three array values apply to versions 0 to 9, 10 to 26 and 27 to 40
/// respectively. All array values are in the range [0, 16].
/// </para>
/// </summary>
/// <value>Array of character count bit length</value>
internal int[] NumBitsCharCount { get{return _NumBitsCharCount;}
private set{_NumBitsCharCount = value;} }
private int[] _NumBitsCharCount;
/// <summary>
/// Returns the bith length of the character count in the QR segment header
/// for the specified QR code version. The result is in the range [0, 16].
/// </summary>
/// <param name="ver">the QR code version (between 1 and 40)</param>
/// <returns></returns>
internal int NumCharCountBits(int ver)
{
Debug.Assert(QrCode.MinVersion <= ver && ver <= QrCode.MaxVersion);
return NumBitsCharCount[(ver + 7) / 17];
}
// private constructor to initializes the constants
private Mode(uint modeBits, params int[] numBitsCharCount)
{
ModeBits = modeBits;
NumBitsCharCount = numBitsCharCount;
}
}
#endregion
}
}