Skip to content

Commit

Permalink
Use string interpolation and clean up redundant code.
Browse files Browse the repository at this point in the history
  • Loading branch information
pluskal committed Dec 12, 2019
1 parent d634aab commit aa93ab7
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 29 deletions.
2 changes: 1 addition & 1 deletion Exception/KaitaiStructError.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class KaitaiStructError : Exception
protected string srcPath;

public KaitaiStructError(string msg, string srcPath)
: base(srcPath + ": " + msg)
: base($"srcPath: {msg}")
{
this.srcPath = srcPath;
}
Expand Down
4 changes: 2 additions & 2 deletions Exception/ValidationFailedError.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class ValidationFailedError : KaitaiStructError
protected KaitaiStream io;

public ValidationFailedError(string msg, KaitaiStream io, string srcPath)
: base("at pos " + io.Pos + ": validation failed: " + msg, srcPath)
: base($"at pos {io.Pos}: validation failed: {msg}", srcPath)
{
this.io = io;
}
Expand All @@ -26,7 +26,7 @@ protected static string ByteArrayToHex(byte[] arr)
sb.Append(' ');
}

sb.Append(string.Format("{0:X2}", arr[i]));
sb.Append($"{arr[i]:X2}");
}

sb.Append(']');
Expand Down
4 changes: 2 additions & 2 deletions Exception/ValidationNotEqualError.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ public class ValidationNotEqualError : ValidationFailedError
protected Object expected;

public ValidationNotEqualError(byte[] expected, byte[] actual, KaitaiStream io, string srcPath)
: base("not equal, expected " + ByteArrayToHex(expected) + ", but got " + ByteArrayToHex(actual), io,
: base($"not equal, expected {ByteArrayToHex(expected)}, but got {ByteArrayToHex(actual)}", io,
srcPath)
{
this.expected = expected;
this.actual = actual;
}

public ValidationNotEqualError(Object expected, Object actual, KaitaiStream io, string srcPath)
: base("not equal, expected " + expected + ", but got " + actual, io, srcPath)
: base($"not equal, expected {expected}, but got {actual}", io, srcPath)
{
this.expected = expected;
this.actual = actual;
Expand Down
59 changes: 35 additions & 24 deletions KaitaiStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;

namespace Kaitai
{
Expand All @@ -16,8 +15,8 @@ public partial class KaitaiStream : IKaitaiStream

static readonly bool IsLittleEndian = BitConverter.IsLittleEndian;

private ulong Bits = 0;
private int BitsLeft = 0;
private ulong Bits;
private int BitsLeft;
private BinaryReader m_binaryReader;

protected Stream BaseStream;
Expand All @@ -40,7 +39,7 @@ public KaitaiStream(string file) : this(File.Open(file, FileMode.Open, FileAcces
public KaitaiStream(byte[] bytes) : this(new MemoryStream(bytes))
{
}

protected BinaryReader BinaryReader
{
get => m_binaryReader ?? (BinaryReader = new BinaryReader(BaseStream));
Expand Down Expand Up @@ -304,7 +303,7 @@ public ulong ReadBitsInt(int n)
// 1 bit => 1 byte
// 8 bits => 1 byte
// 9 bits => 2 bytes
int bytesNeeded = ((bitsNeeded - 1) / 8) + 1;
int bytesNeeded = (bitsNeeded - 1) / 8 + 1;
byte[] buf = ReadBytes(bytesNeeded);
for (int i = 0; i < buf.Length; i++)
{
Expand Down Expand Up @@ -339,11 +338,11 @@ public ulong ReadBitsIntLe(int n)
// 1 bit => 1 byte
// 8 bits => 1 byte
// 9 bits => 2 bytes
int bytesNeeded = ((bitsNeeded - 1) / 8) + 1;
int bytesNeeded = (bitsNeeded - 1) / 8 + 1;
byte[] buf = ReadBytes(bytesNeeded);
for (int i = 0; i < buf.Length; i++)
{
ulong v = (ulong)((ulong)buf[i] << BitsLeft);
ulong v = (ulong)buf[i] << BitsLeft;
Bits |= v;
BitsLeft += 8;
}
Expand All @@ -353,7 +352,7 @@ public ulong ReadBitsIntLe(int n)
ulong mask = GetMaskOnes(n);

// derive reading result
ulong res = (Bits & mask);
ulong res = Bits & mask;

// remove bottom bits that we've just read by shifting
Bits >>= n;
Expand All @@ -379,10 +378,10 @@ private static ulong GetMaskOnes(int n)
public byte[] ReadBytes(long count)
{
if (count < 0 || count > Int32.MaxValue)
throw new ArgumentOutOfRangeException("requested " + count + " bytes, while only non-negative int32 amount of bytes possible");
byte[] bytes = BinaryReader.ReadBytes((int) count);
throw new ArgumentOutOfRangeException($"requested {count} bytes, while only non-negative int32 amount of bytes possible");
byte[] bytes = BinaryReader.ReadBytes((int)count);
if (bytes.Length < count)
throw new EndOfStreamException("requested " + count + " bytes, but got only " + bytes.Length + " bytes");
throw new EndOfStreamException($"requested {count} bytes, but got only {bytes.Length} bytes");
return bytes;
}

Expand All @@ -394,10 +393,10 @@ public byte[] ReadBytes(long count)
public byte[] ReadBytes(ulong count)
{
if (count > Int32.MaxValue)
throw new ArgumentOutOfRangeException("requested " + count + " bytes, while only non-negative int32 amount of bytes possible");
throw new ArgumentOutOfRangeException($"requested {count} bytes, while only non-negative int32 amount of bytes possible");
byte[] bytes = BinaryReader.ReadBytes((int)count);
if (bytes.Length < (int)count)
throw new EndOfStreamException("requested " + count + " bytes, but got only " + bytes.Length + " bytes");
throw new EndOfStreamException($"requested {count} bytes, but got only {bytes.Length} bytes");
return bytes;
}

Expand Down Expand Up @@ -449,7 +448,8 @@ public byte[] ReadBytesTerm(byte terminator, bool includeTerminator, bool consum
{
if (IsEof)
{
if (eosError) throw new EndOfStreamException(string.Format("End of stream reached, but no terminator `{0}` found", terminator));
if (eosError)
throw new EndOfStreamException($"End of stream reached, but no terminator `{terminator}` found");
break;
}

Expand All @@ -460,8 +460,10 @@ public byte[] ReadBytesTerm(byte terminator, bool includeTerminator, bool consum
if (!consumeTerminator) Seek(Pos - 1);
break;
}

bytes.Add(b);
}

return bytes.ToArray();
}

Expand All @@ -476,13 +478,14 @@ public byte[] EnsureFixedContents(byte[] expected)

if (bytes.Length != expected.Length)
{
throw new Exception(string.Format("Expected bytes: {0} ({1} bytes), Instead got: {2} ({3} bytes)", Convert.ToBase64String(expected), expected.Length, Convert.ToBase64String(bytes), bytes.Length));
throw new Exception($"Expected bytes: {Convert.ToBase64String(expected)} ({expected.Length} bytes), Instead got: {Convert.ToBase64String(bytes)} ({bytes.Length} bytes)");
}

for (int i = 0; i < bytes.Length; i++)
{
if (bytes[i] != expected[i])
{
throw new Exception(string.Format("Expected bytes: {0} ({1} bytes), Instead got: {2} ({3} bytes)", Convert.ToBase64String(expected), expected.Length, Convert.ToBase64String(bytes), bytes.Length));
throw new Exception($"Expected bytes: {Convert.ToBase64String(expected)} ({expected.Length} bytes), Instead got: {Convert.ToBase64String(bytes)} ({bytes.Length} bytes)");
}
}

Expand Down Expand Up @@ -533,6 +536,7 @@ public byte[] ProcessXor(byte[] value, int key)
{
result[i] = (byte)(value[i] ^ key);
}

return result;
}

Expand All @@ -551,6 +555,7 @@ public byte[] ProcessXor(byte[] value, byte[] key)
{
result[i] = (byte)(value[i] ^ key[j]);
}

return result;
}

Expand All @@ -564,7 +569,8 @@ public byte[] ProcessXor(byte[] value, byte[] key)
/// <returns></returns>
public byte[] ProcessRotateLeft(byte[] data, int amount, int groupSize)
{
if (amount > 7 || amount < -7) throw new ArgumentException("Rotation of more than 7 cannot be performed.", "amount");
if (amount > 7 || amount < -7)
throw new ArgumentException("Rotation of more than 7 cannot be performed.", "amount");
if (amount < 0) amount += 8; // Rotation of -2 is the same as rotation of +6

byte[] r = new byte[data.Length];
Expand All @@ -575,12 +581,14 @@ public byte[] ProcessRotateLeft(byte[] data, int amount, int groupSize)
{
byte bits = data[i];
// http://stackoverflow.com/a/812039
r[i] = (byte) ((bits << amount) | (bits >> (8 - amount)));
r[i] = (byte)((bits << amount) | (bits >> (8 - amount)));
}

break;
default:
throw new NotImplementedException(string.Format("Unable to rotate a group of {0} bytes yet", groupSize));
throw new NotImplementedException($"Unable to rotate a group of {groupSize} bytes yet");
}

return r;
}

Expand All @@ -597,7 +605,8 @@ public byte[] ProcessZlib(byte[] data)
// There's also 4 checksum bytes at the end of the stream.

byte zlibCmf = data[0];
if ((zlibCmf & 0x0F) != 0x08) throw new NotSupportedException("Only the DEFLATE algorithm is supported for zlib data.");
if ((zlibCmf & 0x0F) != 0x08)
throw new NotSupportedException("Only the DEFLATE algorithm is supported for zlib data.");

const int zlibFooter = 4;
int zlibHeader = 2;
Expand Down Expand Up @@ -674,18 +683,20 @@ public static int ByteArrayCompare(byte[] a, byte[] b)
int al = a.Length;
int bl = b.Length;
int minLen = al < bl ? al : bl;
for (int i = 0; i < minLen; i++) {
for (int i = 0; i < minLen; i++)
{
int cmp = a[i] - b[i];
if (cmp != 0)
return cmp;
}

// Reached the end of at least one of the arrays
if (al == bl) {
if (al == bl)
{
return 0;
} else {
return al - bl;
}

return al - bl;
}

#endregion
Expand Down

0 comments on commit aa93ab7

Please sign in to comment.