Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
manuelbl committed Jul 3, 2022
1 parent 816624d commit f429968
Show file tree
Hide file tree
Showing 12 changed files with 208 additions and 206 deletions.
14 changes: 7 additions & 7 deletions QrCodeGenerator/BitArrayExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,20 @@ public static class BitArrayExtensions
/// <exception cref="ArgumentOutOfRangeException">Value or number of bits is out of range.</exception>
public static void AppendBits(this BitArray bitArray, uint val, int len)
{
if (len < 0 || len > 31 || val >> len != 0)
if (len < 0 || len > 31)
{
throw new ArgumentOutOfRangeException(nameof(len), "'len' out of range");
}

if (len < 0 || len > 31 || val >> len != 0)
if (val >> len != 0)
{
throw new ArgumentOutOfRangeException(nameof(val), "'val' out of range");
}

int bitLength = bitArray.Length;
var bitLength = bitArray.Length;
bitArray.Length = bitLength + len;
uint mask = 1U << (len - 1);
for (int i = bitLength; i < bitLength + len; i++) // Append bit by bit
var mask = 1U << (len - 1);
for (var i = bitLength; i < bitLength + len; i++) // Append bit by bit
{
if ((val & mask) != 0)
{
Expand All @@ -87,9 +87,9 @@ public static void AppendBits(this BitArray bitArray, uint val, int len)
public static void AppendData(this BitArray bitArray, BitArray otherArray)
{
Objects.RequireNonNull(otherArray);
int bitLength = bitArray.Length;
var bitLength = bitArray.Length;
bitArray.Length = bitLength + otherArray.Length;
for (int i = 0; i < otherArray.Length; i++, bitLength++) // Append bit by bit
for (var i = 0; i < otherArray.Length; i++, bitLength++) // Append bit by bit
{
if (otherArray[i])
{
Expand Down
2 changes: 1 addition & 1 deletion QrCodeGenerator/Objects.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ namespace Net.Codecrete.QrCodeGenerator
/// <summary>
/// Helper functions to check for valid arguments.
/// </summary>
internal class Objects
internal static class Objects
{
/// <summary>
/// Ensures that the specified argument is <i>not null</i>.
Expand Down
226 changes: 114 additions & 112 deletions QrCodeGenerator/QrCode.cs

Large diffs are not rendered by default.

34 changes: 17 additions & 17 deletions QrCodeGenerator/QrSegment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ public class QrSegment
public static QrSegment MakeBytes(byte[] data)
{
Objects.RequireNonNull(data);
BitArray ba = new BitArray(0);
foreach (byte b in data)
var ba = new BitArray(0);
foreach (var b in data)
{
ba.AppendBits(b, 8);
}
Expand All @@ -103,11 +103,11 @@ public static QrSegment MakeNumeric(string digits)
throw new ArgumentOutOfRangeException(nameof(digits), "String contains non-numeric characters");
}

BitArray ba = new BitArray(0);
for (int i = 0; i < digits.Length;)
var ba = new BitArray(0);
for (var i = 0; i < digits.Length;)
{
// Consume up to 3 digits per iteration
int n = Math.Min(digits.Length - i, 3);
var n = Math.Min(digits.Length - i, 3);
ba.AppendBits(uint.Parse(digits.Substring(i, n)), n * 3 + 1);
i += n;
}
Expand Down Expand Up @@ -135,12 +135,12 @@ public static QrSegment MakeAlphanumeric(string text)
throw new ArgumentOutOfRangeException(nameof(text), "String contains unencodable characters in alphanumeric mode");
}

BitArray ba = new BitArray(0);
var 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;
var temp = (uint)AlphanumericCharset.IndexOf(text[i]) * 45;
temp += (uint)AlphanumericCharset.IndexOf(text[i + 1]);
ba.AppendBits(temp, 11);
}
Expand Down Expand Up @@ -204,7 +204,7 @@ public static List<QrSegment> MakeSegments(string text)
/// <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);
var ba = new BitArray(0);
if (assignVal < 0)
{
throw new ArgumentOutOfRangeException(nameof(assignVal), "ECI assignment value out of range");
Expand Down Expand Up @@ -336,20 +336,20 @@ public BitArray GetData()
// 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)
internal static int GetTotalBits(List<QrSegment> segments, int version)
{
Objects.RequireNonNull(segs);
Objects.RequireNonNull(segments);
long result = 0;
foreach (QrSegment seg in segs)
foreach (var seg in segments)
{
Objects.RequireNonNull(seg);
int ccbits = seg.EncodingMode.NumCharCountBits(version);
if (seg.NumChars >= 1 << ccbits)
var 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;
result += 4L + ccBits + seg._data.Length;
if (result > int.MaxValue)
{
return -1; // The sum will overflow an int type
Expand All @@ -372,7 +372,7 @@ internal static int GetTotalBits(List<QrSegment> segs, int version)

// 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 $%*+-./:";
internal const string AlphanumericCharset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";

#endregion

Expand Down Expand Up @@ -437,11 +437,11 @@ public sealed class Mode
/// </para>
/// </summary>
/// <value>Array of character count bit length</value>
internal int[] NumBitsCharCount { get; }
private int[] NumBitsCharCount { get; }


/// <summary>
/// Returns the bith length of the character count in the QR segment header
/// Returns the bit 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>
Expand Down
48 changes: 22 additions & 26 deletions QrCodeGenerator/QrSegmentAdvanced.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using static Net.Codecrete.QrCodeGenerator.QrSegment;

Expand Down Expand Up @@ -79,19 +80,19 @@ public static List<QrSegment> MakeSegmentsOptimally(string text, QrCode.Ecc ecl,
}

// Iterate through version numbers, and make tentative segments
List<QrSegment> segs = null;
List<QrSegment> segments = null;
var codePoints = ToCodePoints(text);
for (int version = minVersion; ; version++)
for (var version = minVersion; ; version++)
{
if (version == minVersion || version == 10 || version == 27)
segs = MakeSegmentsOptimally(codePoints, version);
Debug.Assert(segs != null);
segments = MakeSegmentsOptimally(codePoints, version);
Debug.Assert(segments != null);

// Check if the segments fit
int dataCapacityBits = QrCode.GetNumDataCodewords(version, ecl) * 8;
int dataUsedBits = GetTotalBits(segs, version);
var dataCapacityBits = QrCode.GetNumDataCodewords(version, ecl) * 8;
var dataUsedBits = GetTotalBits(segments, version);
if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits)
return segs; // This version number is found to be suitable
return segments; // This version number is found to be suitable

if (version < maxVersion) continue;

Expand Down Expand Up @@ -123,7 +124,7 @@ private static Mode[] ComputeCharacterModes(int[] codePoints, int version)
}

Mode[] modeTypes = { Mode.Byte, Mode.Alphanumeric, Mode.Numeric, Mode.Kanji }; // Do not modify
int numModes = modeTypes.Length;
var numModes = modeTypes.Length;

// Segment header sizes, measured in 1/6 bits
var headCosts = new int[numModes];
Expand All @@ -145,7 +146,7 @@ private static Mode[] ComputeCharacterModes(int[] codePoints, int version)
// Calculate costs using dynamic programming
for (var i = 0; i < codePoints.Length; i++)
{
int c = codePoints[i];
var c = codePoints[i];
var curCosts = new int[numModes];
{
// Always extend a byte mode segment
Expand Down Expand Up @@ -180,7 +181,7 @@ private static Mode[] ComputeCharacterModes(int[] codePoints, int version)
for (var k = 0; k < numModes; k++)
{
// From mode
int newCost = (curCosts[k] + 5) / 6 * 6 + headCosts[j];
var newCost = (curCosts[k] + 5) / 6 * 6 + headCosts[j];
if (charModes[i, k] == null || charModes[i, j] != null && newCost >= curCosts[j])
continue;
curCosts[j] = newCost;
Expand All @@ -202,7 +203,7 @@ private static Mode[] ComputeCharacterModes(int[] codePoints, int version)

// Get optimal mode for each code point by tracing backwards
var result = new Mode[codePoints.Length];
for (int i = result.Length - 1; i >= 0; i--)
for (var i = result.Length - 1; i >= 0; i--)
{
for (var j = 0; j < numModes; j++)
{
Expand All @@ -219,7 +220,7 @@ private static Mode[] ComputeCharacterModes(int[] codePoints, int version)

// Returns a new list of segments based on the given text and modes, such that
// consecutive code points in the same mode are put into the same segment.
private static List<QrSegment> SplitIntoSegments(int[] codePoints, Mode[] charModes)
private static List<QrSegment> SplitIntoSegments(int[] codePoints, IReadOnlyList<Mode> charModes)
{
if (codePoints.Length == 0)
throw new ArgumentOutOfRangeException(nameof(codePoints));
Expand All @@ -233,7 +234,7 @@ private static List<QrSegment> SplitIntoSegments(int[] codePoints, Mode[] charMo
if (i < codePoints.Length && charModes[i] == curMode)
continue;

string s = FromCodePoints(codePoints, start, i - start);
var s = FromCodePoints(codePoints, start, i - start);
if (curMode == Mode.Byte)
{
result.Add(MakeBytes(Encoding.UTF8.GetBytes(s)));
Expand Down Expand Up @@ -266,9 +267,9 @@ private static List<QrSegment> SplitIntoSegments(int[] codePoints, Mode[] charMo
}


private static string FromCodePoints(int[] codepoints, int startIndex, int count)
private static string FromCodePoints(IReadOnlyList<int> codepoints, int startIndex, int count)
{
bool useBigEndian = !BitConverter.IsLittleEndian;
var useBigEndian = !BitConverter.IsLittleEndian;
Encoding utf32 = new UTF32Encoding(useBigEndian, false, true);

var octets = new byte[count * 4];
Expand All @@ -289,7 +290,7 @@ private static string FromCodePoints(int[] codepoints, int startIndex, int count
// UTF-32 / UCS-4) representing the given UTF-16 string.
private static int[] ToCodePoints(string s)
{
bool useBigEndian = !BitConverter.IsLittleEndian;
var useBigEndian = !BitConverter.IsLittleEndian;
Encoding utf32 = new UTF32Encoding(useBigEndian, false, true);
var octets = utf32.GetBytes(s);

Expand Down Expand Up @@ -330,7 +331,7 @@ private static int CountUtf8Bytes(int cp)
/// </para>
/// </summary>
/// <param name="text">The text to encoding, containing only characters allowed by the Kanji encoding.</param>
/// <returns>The created segment respresenting the specified text.</returns>
/// <returns>The created segment representing the specified text.</returns>
/// <exception cref="ArgumentNullException"><paramref name="text"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="text"/> contains non-encodable characters.</exception>
/// <seealso cref="IsEncodableAsKanji"/>
Expand All @@ -339,9 +340,8 @@ public static QrSegment MakeKanji(string text)
Objects.RequireNonNull(text);
var ba = new BitArray(0);

foreach (char t in text)
foreach (var val in text.Select(t => UnicodeToQrKanji[t]))
{
ushort val = UnicodeToQrKanji[t];
if (val == 0xffff)
{
throw new ArgumentOutOfRangeException(nameof(text), "String contains non-kanji-mode characters");
Expand Down Expand Up @@ -369,11 +369,7 @@ public static QrSegment MakeKanji(string text)
public static bool IsEncodableAsKanji(string text)
{
Objects.RequireNonNull(text);
foreach (char t in text)
if (!IsKanji(t))
return false;

return true;
return text.All(t => IsKanji(t));
}


Expand Down Expand Up @@ -505,10 +501,10 @@ static QrSegmentAdvanced()
for (var i = 0; i < UnicodeToQrKanji.Length; i++)
UnicodeToQrKanji[i] = 0xffff;

byte[] bytes = Convert.FromBase64String(PackedQrKanjiToUnicode);
var bytes = Convert.FromBase64String(PackedQrKanjiToUnicode);
for (var i = 0; i < bytes.Length; i += 2)
{
int c = (bytes[i] << 8) | bytes[i + 1];
var c = (bytes[i] << 8) | bytes[i + 1];
if (c == 0xFFFF)
continue;
Debug.Assert(UnicodeToQrKanji[c] == 0xffff);
Expand Down
14 changes: 7 additions & 7 deletions QrCodeGenerator/ReedSolomonGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ internal ReedSolomonGenerator(int degree)
// drop the highest term, and store the rest of the coefficients in order of descending powers.
// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
uint root = 1;
for (int i = 0; i < degree; i++)
for (var i = 0; i < degree; i++)
{
// Multiply the current product by (x - r^i)
for (int j = 0; j < _coefficients.Length; j++)
for (var j = 0; j < _coefficients.Length; j++)
{
_coefficients[j] = Multiply(_coefficients[j], root);
if (j + 1 < _coefficients.Length)
Expand Down Expand Up @@ -108,13 +108,13 @@ internal byte[] GetRemainder(byte[] data)
Objects.RequireNonNull(data);

// Compute the remainder by performing polynomial division
byte[] result = new byte[_coefficients.Length];
foreach (byte b in data)
var result = new byte[_coefficients.Length];
foreach (var b in data)
{
uint factor = (uint)(b ^ result[0]);
var factor = (uint)(b ^ result[0]);
Array.Copy(result, 1, result, 0, result.Length - 1);
result[result.Length - 1] = 0;
for (int i = 0; i < result.Length; i++)
for (var i = 0; i < result.Length; i++)
{
result[i] ^= Multiply(_coefficients[i], factor);
}
Expand All @@ -134,7 +134,7 @@ private static byte Multiply(uint x, uint y)
Debug.Assert(x >> 8 == 0 && y >> 8 == 0);
// Russian peasant multiplication
uint z = 0;
for (int i = 7; i >= 0; i--)
for (var i = 7; i >= 0; i--)
{
z = (z << 1) ^ ((z >> 7) * 0x11D);
z ^= ((y >> i) & 1) * x;
Expand Down
2 changes: 2 additions & 0 deletions QrCodeGeneratorTest/KanjiTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
using System.Collections.Generic;
using Xunit;

// ReSharper disable StringLiteralTypo

namespace Net.Codecrete.QrCodeGenerator.Test
{
public class KanjiTest
Expand Down
2 changes: 2 additions & 0 deletions QrCodeGeneratorTest/OptimalSegmentTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@

using Xunit;

// ReSharper disable StringLiteralTypo

namespace Net.Codecrete.QrCodeGenerator.Test
{
public class OptimalSegmentTest
Expand Down
2 changes: 2 additions & 0 deletions QrCodeGeneratorTest/QrCodeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
using Xunit;
using static Net.Codecrete.QrCodeGenerator.QrCode;

// ReSharper disable StringLiteralTypo

namespace Net.Codecrete.QrCodeGenerator.Test
{
public class QrCodeTest
Expand Down
Loading

0 comments on commit f429968

Please sign in to comment.