Remove some files I meant to delete, and some useless code cleanups

This commit is contained in:
adelikat 2013-11-04 03:12:50 +00:00
parent bc5807a07c
commit 3f88ece3db
30 changed files with 141 additions and 1070 deletions

View File

@ -54,7 +54,6 @@
<Compile Include="Types.cs" />
<Compile Include="UndoHistory.cs" />
<Compile Include="Util.cs" />
<Compile Include="Util.String.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.

View File

@ -1,8 +1,5 @@
using System;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
@ -133,7 +130,7 @@ namespace BizHawk.Common
pos += src.Read(dest.GetBuffer(), pos, length - pos);
}
else
src.CopyTo((Stream)dest);
src.CopyTo(dest);
}
@ -196,7 +193,7 @@ namespace BizHawk.Common
{
foreach (T opt in options)
{
if (eval(opt, str) == true)
if (eval(opt, str))
return true;
}
return false;

View File

@ -21,7 +21,7 @@ namespace BizHawk.Common
// ============== Logging Domain Configuration ==============
private static List<string> EnabledLogDomains = new List<string>();
private static readonly List<string> EnabledLogDomains = new List<string>();
public static void EnableDomain(string domain)
{
@ -57,10 +57,10 @@ namespace BizHawk.Common
public static Stream HACK_LOG_STREAM;
private static bool LogToConsole = false;
private static readonly bool LogToConsole = false;
private static bool LogToFile = false;
private static string LogFilename = "bizhawk.txt";
private const string LogFilename = "bizhawk.txt";
private static StreamWriter writer;
private static void DefaultLogger(string message)

View File

@ -113,7 +113,7 @@ namespace BizHawk.Common
// .net has no built-in read only dictionary
public sealed class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
IDictionary<TKey, TValue> dict;
private readonly IDictionary<TKey, TValue> dict;
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
{

View File

@ -3,7 +3,6 @@ using System.Diagnostics;
namespace BizHawk.Common
{
//I think this is a little faster with uint than with byte
public struct Bit
{

View File

@ -1,8 +0,0 @@
namespace BizHawk.Common
{
//TODO: delete me
public unsafe static partial class Util
{
}
}

View File

@ -1,7 +1,5 @@
using System;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
@ -28,7 +26,7 @@ namespace BizHawk.Common
}
}
public unsafe static partial class Util
public unsafe static class Util
{
static readonly char[] HexConvArr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static System.Runtime.InteropServices.GCHandle HexConvHandle;
@ -236,7 +234,7 @@ namespace BizHawk.Common
public static unsafe int memcmp(void* a, string b, int len)
{
fixed (byte* bp = System.Text.Encoding.ASCII.GetBytes(b))
fixed (byte* bp = Encoding.ASCII.GetBytes(b))
return memcmp(a, bp, len);
}
@ -350,11 +348,11 @@ namespace BizHawk.Common
public static Serializer CreateBinaryReader(BinaryReader _br) { return new Serializer(_br); }
public static Serializer CreateTextWriter(TextWriter _tw) { return new Serializer(_tw); }
public static Serializer CreateTextReader(TextReader _tr) { return new Serializer(_tr); }
public void StartWrite(BinaryWriter _bw) { this.bw = _bw; isReader = false; }
public void StartRead(BinaryReader _br) { this.br = _br; isReader = true; }
public void StartWrite(TextWriter _tw) { this.tw = _tw; isReader = false; isText = true; }
public void StartWrite(BinaryWriter _bw) { bw = _bw; isReader = false; }
public void StartRead(BinaryReader _br) { br = _br; isReader = true; }
public void StartWrite(TextWriter _tw) { tw = _tw; isReader = false; isText = true; }
public void StartRead(TextReader _tr) {
this.tr = _tr;
tr = _tr;
isReader = true;
isText = true;
BeginTextBlock();
@ -366,12 +364,12 @@ namespace BizHawk.Common
bool isText;
bool isReader;
Stack<string> sections = new Stack<string>();
readonly Stack<string> sections = new Stack<string>();
class Section : Dictionary<string, Section>
{
public string Name;
public Dictionary<string, string> Items = new Dictionary<string, string>();
public readonly Dictionary<string, string> Items = new Dictionary<string, string>();
}
Section ReaderSection, CurrSection;

View File

@ -6,7 +6,7 @@ namespace BizHawk.Emulation.Common
public static class CRC32
{
// Lookup table for speed.
private static uint[] CRC32Table;
private static readonly uint[] CRC32Table;
static CRC32()
{

View File

@ -18,7 +18,7 @@ namespace BizHawk.Emulation.Common
public static class Database
{
private static Dictionary<string, CompactGameInfo> db = new Dictionary<string, CompactGameInfo>();
private static readonly Dictionary<string, CompactGameInfo> db = new Dictionary<string, CompactGameInfo>();
static string RemoveHashType(string hash)
{
@ -73,9 +73,11 @@ namespace BizHawk.Emulation.Common
if (line.Trim().Length == 0) continue;
string[] items = line.Split('\t');
var Game = new CompactGameInfo();
var Game = new CompactGameInfo
{
Hash = RemoveHashType(items[0].ToUpper())
};
//remove a hash type identifier. well don't really need them for indexing (theyre just there for human purposes)
Game.Hash = RemoveHashType(items[0].ToUpper());
switch (items[1].Trim())
{
case "B": Game.Status = RomStatus.BadDump; break;

View File

@ -84,21 +84,25 @@ namespace BizHawk.Emulation.Common
//adds a defined firmware ID to the database
static void Firmware(string systemId, string id, string descr)
{
var fr = new FirmwareRecord();
fr.systemId = systemId;
fr.firmwareId = id;
var fr = new FirmwareRecord
{
systemId = systemId,
firmwareId = id,
descr = descr
};
fr.descr = descr;
FirmwareRecords.Add(fr);
}
//adds an acceptable option for a firmware ID to the database
static void Option(string hash, string systemId, string id)
{
var fo = new FirmwareOption();
fo.systemId = systemId;
fo.firmwareId = id;
fo.hash = hash;
var fo = new FirmwareOption
{
systemId = systemId,
firmwareId = id,
hash = hash
};
FirmwareOptions.Add(fo);
}
@ -112,10 +116,12 @@ namespace BizHawk.Emulation.Common
//defines a firmware file
static FirmwareFile File(string hash, string recommendedName, string descr)
{
var ff = new FirmwareFile();
ff.hash = hash;
ff.recommendedName = recommendedName;
ff.descr = descr;
var ff = new FirmwareFile
{
hash = hash,
recommendedName = recommendedName,
descr = descr
};
FirmwareFiles.Add(ff);
FirmwareFilesByHash[hash] = ff;
return ff;

View File

@ -33,13 +33,13 @@ namespace BizHawk.Emulation.Common
public bool NotInDatabase = true;
public string FirmwareHash;
Dictionary<string, string> Options = new Dictionary<string, string>();
readonly Dictionary<string, string> Options = new Dictionary<string, string>();
public GameInfo() { }
public static GameInfo GetNullGame()
{
return new GameInfo()
return new GameInfo
{
Name = "Null",
System = "NULL",
@ -61,7 +61,7 @@ namespace BizHawk.Emulation.Common
public void AddOption(string option)
{
Options[option] = "";
Options[option] = string.Empty;
}
public void AddOption(string option, string param)

View File

@ -13,7 +13,7 @@
public void SetSticky(string button, bool sticky) { }
public bool IsSticky(string button) { return false; }
private static NullController nullController = new NullController();
private static readonly NullController nullController = new NullController();
public static NullController GetNullController() { return nullController; }
}
}

View File

@ -12,8 +12,8 @@ namespace BizHawk.Emulation.Common
public string BoardName { get { return null; } }
private int[] frameBuffer = new int[256 * 192];
private Random rand = new Random();
private readonly int[] frameBuffer = new int[256 * 192];
private readonly Random rand = new Random();
public CoreComm CoreComm { get; private set; }
public IVideoProvider VideoProvider { get { return this; } }
public ISoundProvider SoundProvider { get { return this; } }
@ -24,8 +24,10 @@ namespace BizHawk.Emulation.Common
public NullEmulator(CoreComm comm)
{
CoreComm = comm;
var domains = new List<MemoryDomain>(1);
domains.Add(new MemoryDomain("Main RAM", 1, MemoryDomain.Endian.Little, addr => 0, (a, v) => { }));
var domains = new List<MemoryDomain>(1)
{
new MemoryDomain("Main RAM", 1, MemoryDomain.Endian.Little, addr => 0, (a, v) => { })
};
memoryDomains = domains.AsReadOnly();
}
public void ResetCounters()
@ -37,8 +39,10 @@ namespace BizHawk.Emulation.Common
public void FrameAdvance(bool render, bool rendersound)
{
if (render == false) return;
for (int i = 0; i < 256 * 192; i++)
frameBuffer[i] = Colors.Luminosity((byte)rand.Next());
for (int i = 0; i < 256*192; i++)
{
frameBuffer[i] = Colors.Luminosity((byte) rand.Next());
}
}
public ControllerDefinition ControllerDefinition { get { return NullController; } }
public IController Controller { get; set; }
@ -66,7 +70,7 @@ namespace BizHawk.Emulation.Common
public void GetSamples(short[] samples) { }
public void DiscardSamples() { }
public int MaxVolume { get; set; }
private IList<MemoryDomain> memoryDomains;
private readonly IList<MemoryDomain> memoryDomains;
public IList<MemoryDomain> MemoryDomains { get { return memoryDomains; } }
public MemoryDomain MainMemory { get { return memoryDomains[0]; } }
public void Dispose() { }

View File

@ -1,5 +1,4 @@
using System;
using System.IO;
using System.Text;
namespace BizHawk.Emulation.Common
@ -39,7 +38,7 @@ namespace BizHawk.Emulation.Common
/// <summary>
/// for emu.on_snoop()
/// </summary>
public System.Action InputCallback;
public Action InputCallback;
public MemoryCallbackSystem MemoryCallbackSystem = new MemoryCallbackSystem();
@ -115,15 +114,15 @@ namespace BizHawk.Emulation.Common
}
}
private StringBuilder buffer;
private bool logging = false;
private readonly StringBuilder buffer;
private bool logging;
}
public class MemoryCallbackSystem
{
public int? ReadAddr = null;
private System.Action<uint> ReadCallback = null;
public void SetReadCallback(System.Action<uint> func)
private Action<uint> ReadCallback;
public void SetReadCallback(Action<uint> func)
{
ReadCallback = func;
}
@ -155,8 +154,8 @@ namespace BizHawk.Emulation.Common
}
public int? WriteAddr = null;
private System.Action<uint> WriteCallback = null;
public void SetWriteCallback(System.Action<uint> func)
private Action<uint> WriteCallback;
public void SetWriteCallback(Action<uint> func)
{
WriteCallback = func;
}

View File

@ -50,11 +50,11 @@ namespace BizHawk.Emulation.Common
/// <param name="source"></param>
public ControllerDefinition(ControllerDefinition source)
{
this.Name = source.Name;
Name = source.Name;
foreach (var s in source.BoolButtons)
this.BoolButtons.Add(s);
BoolButtons.Add(s);
foreach (var s in source.FloatControls)
this.FloatControls.Add(s);
FloatControls.Add(s);
}
public ControllerDefinition() { }
}

View File

@ -19,8 +19,8 @@
/// </summary>
public class FakeSyncSound : ISyncSoundProvider
{
ISoundProvider source;
int spf;
private readonly ISoundProvider source;
private readonly int spf;
/// <summary>
///
/// </summary>

View File

@ -64,7 +64,6 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Subcode.cs" />
<Compile Include="TOC_format.cs" />
<Compile Include="Util.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BizHawk.Common\BizHawk.Common.csproj">

View File

@ -56,7 +56,7 @@ namespace BizHawk.Emulation.DiscSystem
/// an index of blocks within the ECM file, for random-access.
/// itll be sorted by logical ordering, so you can binary search for the address you want
/// </summary>
List<IndexEntry> Index = new List<IndexEntry>();
private readonly List<IndexEntry> Index = new List<IndexEntry>();
/// <summary>
/// the ECMfile-provided EDC integrity checksum. not being used right now
@ -102,11 +102,14 @@ namespace BizHawk.Emulation.DiscSystem
uint todo = (uint)N + 1;
IndexEntry ie = new IndexEntry();
ie.Number = todo;
ie.ECMOffset = stream.Position;
ie.LogicalOffset = logOffset;
ie.Type = T;
IndexEntry ie = new IndexEntry
{
Number = todo,
ECMOffset = stream.Position,
LogicalOffset = logOffset,
Type = T
};
Index.Add(ie);
if (T == 0)
@ -246,7 +249,7 @@ namespace BizHawk.Emulation.DiscSystem
}
//we dont want to keep churning through this many big byte arrays while reading stuff, so we save a sector cache.
byte[] Read_SectorBuf = new byte[2352];
readonly byte[] Read_SectorBuf = new byte[2352];
int Read_LastIndex = 0;
public int Read(long byte_pos, byte[] buffer, int offset, int _count)

View File

@ -46,13 +46,13 @@ namespace BizHawk.Emulation.DiscSystem
throw new Blob_WaveFile_Exception("Not a RIFF WAVE file");
}
var fmt = rm.riff.subchunks.FirstOrDefault((chunk) => chunk.tag == "fmt ") as RiffMaster.RiffSubchunk_fmt;
var fmt = rm.riff.subchunks.FirstOrDefault(chunk => chunk.tag == "fmt ") as RiffMaster.RiffSubchunk_fmt;
if (fmt == null)
{
throw new Blob_WaveFile_Exception("Not a valid RIFF WAVE file (missing fmt chunk");
}
if (1 != rm.riff.subchunks.Count((chunk) => chunk.tag == "data"))
if (1 != rm.riff.subchunks.Count(chunk => chunk.tag == "data"))
{
//later, we could make a Stream which would make an index of data chunks and walk around them
throw new Blob_WaveFile_Exception("Multi-data-chunk WAVE files not supported");
@ -69,7 +69,7 @@ namespace BizHawk.Emulation.DiscSystem
}
//acquire the start of the data chunk
var dataChunk = rm.riff.subchunks.FirstOrDefault((chunk) => chunk.tag == "data") as RiffMaster.RiffSubchunk;
var dataChunk = rm.riff.subchunks.FirstOrDefault(chunk => chunk.tag == "data") as RiffMaster.RiffSubchunk;
waveDataStreamPos = dataChunk.Position;
mDataLength = dataChunk.Length;
}

View File

@ -2,15 +2,14 @@
using System.IO;
using System.Collections.Generic;
/// <summary>
/// Parses a RIFF file into a live data structure.
/// References to large blobs remain mostly on disk in the file which RiffMaster keeps a reference too. Dispose it to close the file.
/// You can modify blobs however you want and write the file back out to a new path, if youre careful (that was the original point of this)
/// Please be sure to test round-tripping when you make any changes. This architecture is a bit tricky to use, but it works if youre careful.
/// </summary>
namespace BizHawk.Emulation.DiscSystem
{
/// <summary>
/// Parses a RIFF file into a live data structure.
/// References to large blobs remain mostly on disk in the file which RiffMaster keeps a reference too. Dispose it to close the file.
/// You can modify blobs however you want and write the file back out to a new path, if youre careful (that was the original point of this)
/// Please be sure to test round-tripping when you make any changes. This architecture is a bit tricky to use, but it works if youre careful.
/// </summary>
class RiffMaster : IDisposable
{
public RiffMaster() { }
@ -18,14 +17,18 @@ namespace BizHawk.Emulation.DiscSystem
public void WriteFile(string fname)
{
using (FileStream fs = new FileStream(fname, FileMode.Create, FileAccess.Write, FileShare.Read))
{
WriteStream(fs);
}
}
public Stream BaseStream;
public void LoadFile(string fname)
{
var fs = new FileStream(fname, FileMode.Open, FileAccess.Read, FileShare.Read);
LoadStream(fs);
LoadStream(
new FileStream(fname, FileMode.Open, FileAccess.Read, FileShare.Read)
);
}
public void Dispose()
@ -265,10 +268,12 @@ namespace BizHawk.Emulation.DiscSystem
subchunks.Clear();
foreach (KeyValuePair<string, string> kvp in dictionary)
{
RiffSubchunk rs = new RiffSubchunk();
rs.tag = kvp.Key;
rs.Source = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(kvp.Value));
rs.Position = 0;
RiffSubchunk rs = new RiffSubchunk
{
tag = kvp.Key,
Source = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(kvp.Value)),
Position = 0
};
rs.Length = (uint)rs.Source.Length;
subchunks.Add(rs);
}
@ -299,9 +304,13 @@ namespace BizHawk.Emulation.DiscSystem
throw new FormatException("chunk too big");
if (tag == "RIFF" || tag == "LIST")
{
RiffContainer rc = new RiffContainer();
rc.tag = tag;
rc.type = ReadTag(br); readCounter += 4;
RiffContainer rc = new RiffContainer
{
tag = tag,
type = ReadTag(br)
};
readCounter += 4;
long readEnd = readCounter - 4 + size;
while (readEnd > readCounter)
rc.subchunks.Add(ReadChunk(br));
@ -309,11 +318,13 @@ namespace BizHawk.Emulation.DiscSystem
}
else
{
RiffSubchunk rsc = new RiffSubchunk();
rsc.tag = tag;
rsc.Source = br.BaseStream;
rsc.Position = br.BaseStream.Position;
rsc.Length = size;
RiffSubchunk rsc = new RiffSubchunk
{
tag = tag,
Source = br.BaseStream,
Position = br.BaseStream.Position,
Length = size
};
readCounter += size;
ret = rsc.Morph();
}

View File

@ -47,7 +47,7 @@ namespace BizHawk.Emulation.DiscSystem
}
//cue files can get their data from other sources using this
Dictionary<string, string> CueFileResolver = new Dictionary<string, string>();
readonly Dictionary<string, string> CueFileResolver = new Dictionary<string, string>();
void FromCueInternal(Cue cue, string cueDir, CueBinPrefs prefs)
{
@ -73,7 +73,7 @@ namespace BizHawk.Emulation.DiscSystem
int blob_sectorsize = Cue.BINSectorSizeForTrackType(cue_file.Tracks[0].TrackType);
int blob_length_aba;
long blob_length_bytes;
IBlob cue_blob = null;
IBlob cue_blob;
//try any way we can to acquire a file
if (!File.Exists(blobPath) && prefs.ExtensionAware)
@ -95,8 +95,7 @@ namespace BizHawk.Emulation.DiscSystem
if (cue_file.FileType == Cue.CueFileType.Binary || cue_file.FileType == Cue.CueFileType.Unspecified)
{
//make a blob for the file
Blob_RawFile blob = new Blob_RawFile();
blob.PhysicalPath = blobPath;
Blob_RawFile blob = new Blob_RawFile {PhysicalPath = blobPath};
Blobs.Add(blob);
blob_length_aba = (int)(blob.Length / blob_sectorsize);
@ -286,9 +285,11 @@ namespace BizHawk.Emulation.DiscSystem
//these cases are all 2352 bytes
//in all these cases, either no ECM is present or ECM is provided.
//so we just emit a Sector_Raw
Sector_RawBlob sector_rawblob = new Sector_RawBlob();
sector_rawblob.Blob = cue_blob;
sector_rawblob.Offset = blob_cursor;
Sector_RawBlob sector_rawblob = new Sector_RawBlob
{
Blob = cue_blob,
Offset = blob_cursor
};
blob_cursor += 2352;
Sector_Mode1_or_Mode2_2352 sector_raw;
if(cue_track.TrackType == ETrackType.Mode1_2352)
@ -613,7 +614,7 @@ namespace BizHawk.Emulation.DiscSystem
public bool EOF;
public CueLineParser(string line)
{
this.str = line;
str = line;
}
public string ReadPath() { return ReadToken(true); }

View File

@ -4,7 +4,6 @@ using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
namespace BizHawk.Emulation.DiscSystem
{
@ -63,7 +62,7 @@ namespace BizHawk.Emulation.DiscSystem
oInfo.RedirectStandardOutput = true;
oInfo.RedirectStandardError = true;
Process proc = System.Diagnostics.Process.Start(oInfo);
Process proc = Process.Start(oInfo);
string result = proc.StandardError.ReadToEnd();
proc.WaitForExit();

View File

@ -85,7 +85,7 @@ namespace BizHawk.Emulation.DiscSystem
void _Open_LBA_2048(Disc disc)
{
SectorSize = 2048;
this.Disc = disc;
Disc = disc;
NumSectors = disc.LBACount;
currPosition = 0;
@ -172,7 +172,7 @@ namespace BizHawk.Emulation.DiscSystem
/// </summary>
public void ReadLBA_2352_Flat(long disc_offset, byte[] buffer, int offset, int length)
{
int secsize = 2352;
const int secsize = 2352;
byte[] lba_buf = new byte[secsize];
int sectorHint = -1;
READLBA_Flat_Implementation(disc_offset, buffer, offset, length, (a, b, c) => ReadLBA_2352(a, b, c), secsize, lba_buf, ref sectorHint);
@ -184,7 +184,7 @@ namespace BizHawk.Emulation.DiscSystem
/// </summary>
public void ReadLBA_2048_Flat(long disc_offset, byte[] buffer, int offset, int length)
{
int secsize = 2048;
const int secsize = 2048;
byte[] lba_buf = new byte[secsize];
int sectorHint = -1;
READLBA_Flat_Implementation(disc_offset, buffer, offset, length, (a, b, c) => ReadLBA_2048(a, b, c), secsize, lba_buf, ref sectorHint);

View File

@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
//disc type identification logic

View File

@ -419,7 +419,7 @@ namespace BizHawk.Emulation.DiscSystem
//this is a physical 2352 byte sector.
public class SectorEntry
{
public SectorEntry(ISector sec) { this.Sector = sec; }
public SectorEntry(ISector sec) { Sector = sec; }
public ISector Sector;
//todo - add some PARAMETER fields to this, so that the ISector can use them (so that each ISector doesnt have to be constructed also)
@ -947,7 +947,7 @@ FILE ""xarp.barp.marp.farp"" BINARY
progress.Message = "Writing bin(s)";
progress.TaskCurrent = 1;
progress.ProgressEstimate = bins.Sum((bfd) => bfd.abas.Count);
progress.ProgressEstimate = bins.Sum(bfd => bfd.abas.Count);
progress.ProgressCurrent = 0;
if(!prefs.ReallyDumpBin) return;

View File

@ -81,12 +81,14 @@ namespace BizHawk.Emulation.DiscSystem
foreach (var track in ses.Tracks)
foreach (var index in track.Indexes)
{
var tp = new TOCPoint();
tp.Num = num++;
tp.ABA = index.aba;
tp.TrackNum = track.num;
tp.IndexNum = index.num;
tp.Track = track;
var tp = new TOCPoint
{
Num = num++,
ABA = index.aba,
TrackNum = track.num,
IndexNum = index.num,
Track = track
};
Points.Add(tp);
}

View File

@ -35,11 +35,11 @@ namespace BizHawk.Emulation.DiscSystem
static class ECM
{
//EDC (crc) acceleration table
static uint[] edc_table = new uint[256];
static readonly uint[] edc_table = new uint[256];
//math acceleration tables over GF(2^8) with yellowbook specified primitive polynomial 0x11D
static byte[] mul2tab = new byte[256];
static byte[] div3tab = new byte[256];
static readonly byte[] mul2tab = new byte[256];
static readonly byte[] div3tab = new byte[256];
static ECM()
{

View File

@ -1,10 +1,4 @@
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
//a decent little subcode reference
//a decent little subcode reference
//http://www.jbum.com/cdg_revealed.html
namespace BizHawk.Emulation.DiscSystem
@ -14,16 +8,14 @@ namespace BizHawk.Emulation.DiscSystem
//this table is backwards or something. at any rate its tailored to the needs of the Q subchannel
internal static class CRC16_CCITT
{
private static ushort[] table = new ushort[256];
private static readonly ushort[] table = new ushort[256];
static CRC16_CCITT()
{
ushort value;
ushort temp;
for (ushort i = 0; i < 256; ++i)
{
value = 0;
temp = (ushort)(i << 8);
ushort value = 0;
ushort temp = (ushort)(i << 8);
for (byte j = 0; j < 8; ++j)
{
if (((value ^ temp) & 0x8000) != 0)
@ -47,10 +39,8 @@ namespace BizHawk.Emulation.DiscSystem
}
return Result;
}
}
public class SubcodeDataDecoder
{
public static void Unpack_Q(byte[] output, int out_ofs, byte[] input, int in_ofs)
@ -68,7 +58,4 @@ namespace BizHawk.Emulation.DiscSystem
}
}
}
}

View File

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
namespace BizHawk.Emulation.DiscSystem
namespace BizHawk.Emulation.DiscSystem
{
//TBD TOC format
public class TOCFormat

View File

@ -1,923 +0,0 @@
using System;
using System.Linq;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using BizHawk.Common;
/*
namespace BizHawk.Emulation.DiscSystem
{
//TODO: QUICK FIX, this is the same file as BizHawk.Emulation, move to BizHawk.Common and get rid of this
internal static class Colors
{
public static int ARGB(byte red, byte green, byte blue)
{
return (int)((uint)((red << 0x10) | (green << 8) | blue | (0xFF << 0x18)));
}
public static int ARGB(byte red, byte green, byte blue, byte alpha)
{
return (int)((uint)((red << 0x10) | (green << 8) | blue | (alpha << 0x18)));
}
public static int Luminosity(byte lum)
{
return (int)((uint)((lum << 0x10) | (lum << 8) | lum | (0xFF << 0x18)));
}
}
internal unsafe static class Util
{
static readonly char[] HexConvArr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static System.Runtime.InteropServices.GCHandle HexConvHandle;
public static char* HexConvPtr;
static unsafe Util()
{
HexConvHandle = System.Runtime.InteropServices.GCHandle.Alloc(HexConvArr, System.Runtime.InteropServices.GCHandleType.Pinned);
HexConvPtr = (char*)HexConvHandle.AddrOfPinnedObject().ToPointer();
}
public static string Hash_MD5(byte[] data, int offset, int len)
{
using (var md5 = System.Security.Cryptography.MD5.Create())
{
md5.TransformFinalBlock(data, offset, len);
return Util.BytesToHexString(md5.Hash);
}
}
public static string Hash_SHA1(byte[] data, int offset, int len)
{
using (var sha1 = System.Security.Cryptography.SHA1.Create())
{
sha1.TransformFinalBlock(data, offset, len);
return Util.BytesToHexString(sha1.Hash);
}
}
public static bool IsPowerOfTwo(int x)
{
if (x == 0) return true;
if (x == 1) return true;
return (x & (x - 1)) == 0;
}
public static int SaveRamBytesUsed(byte[] SaveRAM)
{
for (int j = SaveRAM.Length - 1; j >= 0; j--)
if (SaveRAM[j] != 0)
return j + 1;
return 0;
}
// Read bytes from a BinaryReader and translate them into the UTF-8 string they represent.
public static string ReadStringFixedAscii(this BinaryReader r, int bytes)
{
byte[] read = new byte[bytes];
for (int b = 0; b < bytes; b++)
read[b] = r.ReadByte();
return System.Text.Encoding.UTF8.GetString(read);
}
public static string ReadStringAsciiZ(this BinaryReader r)
{
StringBuilder sb = new StringBuilder();
for(;;)
{
int b = r.ReadByte();
if(b <= 0) break;
sb.Append((char)b);
}
return sb.ToString();
}
/// <summary>
/// conerts bytes to an uppercase string of hex numbers in upper case without any spacing or anything
/// //could be extension method
/// </summary>
public static string BytesToHexString(byte[] bytes)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in bytes)
sb.AppendFormat("{0:X2}", b);
return sb.ToString();
}
//could be extension method
public static byte[] HexStringToBytes(string str)
{
MemoryStream ms = new MemoryStream();
if (str.Length % 2 != 0) throw new ArgumentException();
int len = str.Length / 2;
for (int i = 0; i < len; i++)
{
int d = 0;
for (int j = 0; j < 2; j++)
{
char c = char.ToLower(str[i * 2 + j]);
if (c >= '0' && c <= '9')
d += (c - '0');
else if (c >= 'a' && c <= 'f')
d += (c - 'a') + 10;
else throw new ArgumentException();
if (j == 0) d <<= 4;
}
ms.WriteByte((byte)d);
}
return ms.ToArray();
}
//could be extension method
public static void WriteByteBuffer(BinaryWriter bw, byte[] data)
{
if (data == null) bw.Write(0);
else
{
bw.Write(data.Length);
bw.Write(data);
}
}
public static short[] ByteBufferToShortBuffer(byte[] buf)
{
int num = buf.Length / 2;
short[] ret = new short[num];
for (int i = 0; i < num; i++)
{
ret[i] = (short)(buf[i * 2] | (buf[i * 2 + 1] << 8));
}
return ret;
}
public static byte[] ShortBufferToByteBuffer(short[] buf)
{
int num = buf.Length;
byte[] ret = new byte[num * 2];
for (int i = 0; i < num; i++)
{
ret[i * 2 + 0] = (byte)(buf[i] & 0xFF);
ret[i * 2 + 1] = (byte)((buf[i] >> 8) & 0xFF);
}
return ret;
}
public static uint[] ByteBufferToUintBuffer(byte[] buf)
{
int num = buf.Length / 4;
uint[] ret = new uint[num];
for (int i = 0; i < num; i++)
{
ret[i] = (uint)(buf[i * 4] | (buf[i * 4 + 1] << 8) | (buf[i * 4 + 2] << 16) | (buf[i * 4 + 3] << 24));
}
return ret;
}
public static byte[] UintBufferToByteBuffer(uint[] buf)
{
int num = buf.Length;
byte[] ret = new byte[num * 4];
for (int i = 0; i < num; i++)
{
ret[i * 4 + 0] = (byte)(buf[i] & 0xFF);
ret[i * 4 + 1] = (byte)((buf[i] >> 8) & 0xFF);
ret[i * 4 + 2] = (byte)((buf[i] >> 16) & 0xFF);
ret[i * 4 + 3] = (byte)((buf[i] >> 24) & 0xFF);
}
return ret;
}
public static int[] ByteBufferToIntBuffer(byte[] buf)
{
int num = buf.Length / 4;
int[] ret = new int[num];
for (int i = 0; i < num; i++)
{
ret[i] = buf[(i * 4) + 3];
ret[i] <<= 8;
ret[i] |= buf[(i * 4) + 2];
ret[i] <<= 8;
ret[i] |= buf[(i * 4) + 1];
ret[i] <<= 8;
ret[i] |= buf[(i * 4)];
}
return ret;
}
public static byte[] IntBufferToByteBuffer(int[] buf)
{
int num = buf.Length;
byte[] ret = new byte[num * 4];
for (int i = 0; i < num; i++)
{
ret[i * 4 + 0] = (byte)(buf[i] & 0xFF);
ret[i * 4 + 1] = (byte)((buf[i] >> 8) & 0xFF);
ret[i * 4 + 2] = (byte)((buf[i] >> 16) & 0xFF);
ret[i * 4 + 3] = (byte)((buf[i] >> 24) & 0xFF);
}
return ret;
}
public static byte[] ReadByteBuffer(BinaryReader br, bool return_null)
{
int len = br.ReadInt32();
if (len == 0 && return_null) return null;
byte[] ret = new byte[len];
int ofs = 0;
while (len > 0)
{
int done = br.Read(ret, ofs, len);
ofs += done;
len -= done;
}
return ret;
}
public static unsafe int memcmp(void* a, string b, int len)
{
fixed (byte* bp = System.Text.Encoding.ASCII.GetBytes(b))
return memcmp(a, bp, len);
}
public static unsafe int memcmp(void* a, void* b, int len)
{
byte* ba = (byte*)a;
byte* bb = (byte*)b;
for (int i = 0; i < len; i++)
{
byte _a = ba[i];
byte _b = bb[i];
int c = _a - _b;
if (c != 0) return c;
}
return 0;
}
public static unsafe void memset(void* ptr, int val, int len)
{
byte* bptr = (byte*)ptr;
for (int i = 0; i < len; i++)
bptr[i] = (byte)val;
}
public static unsafe void memset32(void* ptr, int val, int len)
{
System.Diagnostics.Debug.Assert(len % 4 == 0);
int dwords = len / 4;
int* dwptr = (int*)ptr;
for (int i = 0; i < dwords; i++)
dwptr[i] = val;
}
public static byte[] ReadAllBytes(Stream stream)
{
const int BUFF_SIZE = 4096;
byte[] buffer = new byte[BUFF_SIZE];
int bytesRead = 0;
var inStream = new BufferedStream(stream);
var outStream = new MemoryStream();
while ((bytesRead = inStream.Read(buffer, 0, BUFF_SIZE)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
}
return outStream.ToArray();
}
public static byte BinToBCD(this byte v)
{
return (byte) (((v / 10) * 16) + (v % 10));
}
public static byte BCDtoBin(this byte v)
{
return (byte) (((v / 16) * 10) + (v % 16));
}
public static string FormatFileSize(long filesize)
{
Decimal size = (Decimal)filesize;
Decimal OneKiloByte = 1024M;
Decimal OneMegaByte = OneKiloByte * 1024M;
Decimal OneGigaByte = OneMegaByte * 1024M;
string suffix;
if (size > 1024 * 1024 * 1024)
{
size /= 1024 * 1024 * 1024;
suffix = "GB";
}
else if (size > 1024 * 1024)
{
size /= 1024 * 1024;
suffix = "MB";
}
else if (size > 1024)
{
size /= 1024;
suffix = "KB";
}
else
{
suffix = " B";
}
string precision = "2";
return String.Format("{0:N" + precision + "}{1}", size, suffix);
}
}
public unsafe class Serializer
{
BinaryReader br;
BinaryWriter bw;
TextReader tr;
TextWriter tw;
public BinaryReader BinaryReader { get { return br; } }
public BinaryWriter BinaryWriter { get { return bw; } }
public TextReader TextReader { get { return tr; } }
public TextWriter TextWriter { get { return tw; } }
public Serializer() { }
public Serializer(BinaryWriter _bw) { StartWrite(_bw); }
public Serializer(BinaryReader _br) { StartRead(_br); }
public Serializer(TextWriter _tw) { StartWrite(_tw); }
public Serializer(TextReader _tr) { StartRead(_tr); }
public static Serializer CreateBinaryWriter(BinaryWriter _bw) { return new Serializer(_bw); }
public static Serializer CreateBinaryReader(BinaryReader _br) { return new Serializer(_br); }
public static Serializer CreateTextWriter(TextWriter _tw) { return new Serializer(_tw); }
public static Serializer CreateTextReader(TextReader _tr) { return new Serializer(_tr); }
public void StartWrite(BinaryWriter _bw) { this.bw = _bw; isReader = false; }
public void StartRead(BinaryReader _br) { this.br = _br; isReader = true; }
public void StartWrite(TextWriter _tw) { this.tw = _tw; isReader = false; isText = true; }
public void StartRead(TextReader _tr) {
this.tr = _tr;
isReader = true;
isText = true;
BeginTextBlock();
}
public bool IsReader { get { return isReader; } }
public bool IsWriter { get { return !IsReader; } }
public bool IsText { get { return isText; } }
bool isText;
bool isReader;
Stack<string> sections = new Stack<string>();
class Section : Dictionary<string, Section>
{
public string Name;
public Dictionary<string, string> Items = new Dictionary<string, string>();
}
Section ReaderSection, CurrSection;
Stack<Section> SectionStack = new Stack<Section>();
void BeginTextBlock()
{
if (!IsText) return;
if (IsWriter) return;
ReaderSection = new Section();
ReaderSection.Name = "";
Stack<Section> ss = new Stack<Section>();
ss.Push(ReaderSection);
Section curs = ReaderSection;
var rxEnd = new System.Text.RegularExpressions.Regex(@"\[/(.*?)\]",System.Text.RegularExpressions.RegexOptions.Compiled);
var rxBegin = new System.Text.RegularExpressions.Regex(@"\[(.*?)\]",System.Text.RegularExpressions.RegexOptions.Compiled);
//read the entire file into a data structure for flexi-parsing
string str;
while ((str = tr.ReadLine()) != null)
{
var end = rxEnd.Match(str);
var begin = rxBegin.Match(str);
if (end.Success)
{
string name = end.Groups[1].Value;
if (name != curs.Name) throw new InvalidOperationException("Mis-formed savestate blob");
curs = ss.Pop();
// consume no data past the end of the last proper section
if (curs == ReaderSection)
{
CurrSection = curs;
return;
}
}
else if (begin.Success)
{
string name = begin.Groups[1].Value;
ss.Push(curs);
var news = new Section();
news.Name = name;
if (!curs.ContainsKey(name))
curs[name] = news;
else
throw new Exception(string.Format("Duplicate key \"{0}\" in serializer savestate!", name));
curs = news;
}
else
{
//add to current section
if (str.Trim().Length == 0) continue;
var parts = str.Split(' ');
var key = parts[0];
//UGLY: adds whole string instead of splitting the key. later, split the key, and have the individual Sync methods give up that responsibility
if (!curs.Items.ContainsKey(key))
curs.Items[key] = parts[1];
else
throw new Exception(string.Format("Duplicate key \"{0}\" in serializer savestate!", key));
}
}
CurrSection = ReaderSection;
}
public void BeginSection(string name)
{
sections.Push(name);
if (IsText)
if (IsWriter) { tw.WriteLine("[{0}]", name); }
else
{
SectionStack.Push(CurrSection);
CurrSection = CurrSection[name];
}
}
public void EndSection()
{
string name = sections.Pop();
if (IsText)
if (IsWriter) tw.WriteLine("[/{0}]", name);
else
{
CurrSection = SectionStack.Pop();
}
}
string Item(string key)
{
return CurrSection.Items[key];
}
bool Present(string key)
{
return CurrSection.Items.ContainsKey(key);
}
public void SyncEnum<T>(string name, ref T val) where T : struct
{
if (typeof(T).BaseType != typeof(System.Enum))
throw new InvalidOperationException();
if (isText) SyncEnumText<T>(name, ref val);
else if (IsReader) val = (T)Enum.ToObject(typeof(T), br.ReadInt32());
else bw.Write(Convert.ToInt32(val));
}
public void SyncEnumText<T>(string name, ref T val) where T : struct
{
if (IsReader) { if (Present(name)) val = (T)Enum.Parse(typeof(T), Item(name)); }
else tw.WriteLine("{0} {1}", name, val.ToString());
}
void SyncBuffer(string name, int elemsize, int len, void* ptr)
{
if (IsReader)
{
byte[] temp = null;
Sync(name, ref temp, false);
int todo = Math.Min(temp.Length, len * elemsize);
System.Runtime.InteropServices.Marshal.Copy(temp, 0, new IntPtr(ptr), todo);
}
else
{
int todo = len * elemsize;
byte[] temp = new byte[todo];
System.Runtime.InteropServices.Marshal.Copy(new IntPtr(ptr), temp, 0, todo);
Sync(name, ref temp, false);
}
}
public void Sync(string name, ref ByteBuffer byteBuf)
{
SyncBuffer(name, 1, byteBuf.len, byteBuf.ptr);
}
public void Sync(string name, ref IntBuffer byteBuf)
{
SyncBuffer(name, 4, byteBuf.len, byteBuf.ptr);
}
public void Sync(string name, ref byte[] val, bool use_null)
{
if (IsText) SyncText(name, ref val, use_null);
else if (IsReader) val = Util.ReadByteBuffer(br, use_null);
else Util.WriteByteBuffer(bw, val);
}
public void SyncText(string name, ref byte[] val, bool use_null)
{
if (IsReader)
{
if(Present(name)) val = Util.HexStringToBytes(Item(name));
if (val != null && val.Length == 0 && use_null) val = null;
}
else
{
byte[] temp = val;
if (temp == null) temp = new byte[0];
tw.WriteLine("{0} {1}", name, Util.BytesToHexString(temp));
}
}
public void Sync(string name, ref short[] val, bool use_null)
{
if (IsText) SyncText(name, ref val, use_null);
else if (IsReader)
{
val = Util.ByteBufferToShortBuffer(Util.ReadByteBuffer(br, false));
if (val == null && !use_null) val = new short[0];
}
else Util.WriteByteBuffer(bw, Util.ShortBufferToByteBuffer(val));
}
public void SyncText(string name, ref short[] val, bool use_null)
{
if (IsReader)
{
if (Present(name))
{
byte[] bytes = Util.HexStringToBytes(Item(name));
val = Util.ByteBufferToShortBuffer(bytes);
}
if (val != null && val.Length == 0 && use_null) val = null;
}
else
{
short[] temp = val;
if (temp == null) temp = new short[0];
tw.WriteLine("{0} {1}", name, Util.BytesToHexString(Util.ShortBufferToByteBuffer(temp)));
}
}
public void Sync(string name, ref int[] val, bool use_null)
{
if (IsText) SyncText(name, ref val, use_null);
else if (IsReader)
{
val = Util.ByteBufferToIntBuffer(Util.ReadByteBuffer(br, false));
if (val == null && !use_null) val = new int[0];
}
else Util.WriteByteBuffer(bw, Util.IntBufferToByteBuffer(val));
}
public void SyncText(string name, ref int[] val, bool use_null)
{
if (IsReader)
{
if (Present(name))
{
byte[] bytes = Util.HexStringToBytes(Item(name));
val = Util.ByteBufferToIntBuffer(bytes);
}
if (val != null && val.Length == 0 && use_null) val = null;
}
else
{
int[] temp = val;
if (temp == null) temp = new int[0];
tw.WriteLine("{0} {1}", name, Util.BytesToHexString(Util.IntBufferToByteBuffer(temp)));
}
}
public void Sync(string name, ref uint[] val, bool use_null)
{
if (IsText) SyncText(name, ref val, use_null);
else if (IsReader)
{
val = Util.ByteBufferToUintBuffer(Util.ReadByteBuffer(br, false));
if (val == null && !use_null) val = new uint[0];
}
else Util.WriteByteBuffer(bw, Util.UintBufferToByteBuffer(val));
}
public void SyncText(string name, ref uint[] val, bool use_null)
{
if (IsReader)
{
if(Present(name))
{
byte[] bytes = Util.HexStringToBytes(Item(name));
val = Util.ByteBufferToUintBuffer(bytes);
}
if (val != null && val.Length == 0 && use_null) val = null;
}
else
{
uint[] temp = val;
if (temp == null) temp = new uint[0];
tw.WriteLine("{0} {1}", name, Util.BytesToHexString(Util.UintBufferToByteBuffer(temp)));
}
}
public void Sync(string name, ref Bit val)
{
if (IsText) SyncText(name, ref val);
else if (IsReader) Read(ref val);
else Write(ref val);
}
public void SyncText(string name, ref Bit val)
{
if (IsReader) ReadText(name, ref val);
else WriteText(name, ref val);
}
public void Sync(string name, ref byte val)
{
if (IsText) SyncText(name, ref val);
else if (IsReader) Read(ref val);
else Write(ref val);
}
void SyncText(string name, ref byte val)
{
if (IsReader) ReadText(name, ref val);
else WriteText(name, ref val);
}
public void Sync(string name, ref ushort val)
{
if (IsText) SyncText(name, ref val);
else if (IsReader) Read(ref val);
else Write(ref val);
}
void SyncText(string name, ref ushort val)
{
if (IsReader) ReadText(name, ref val);
else WriteText(name, ref val);
}
public void Sync(string name, ref uint val)
{
if (IsText) SyncText(name, ref val);
else if (IsReader) Read(ref val);
else Write(ref val);
}
void SyncText(string name, ref uint val)
{
if (IsReader) ReadText(name, ref val);
else WriteText(name, ref val);
}
public void Sync(string name, ref sbyte val)
{
if (IsText) SyncText(name, ref val);
else if (IsReader) Read(ref val);
else Write(ref val);
}
void SyncText(string name, ref sbyte val)
{
if (IsReader) ReadText(name, ref val);
else WriteText(name, ref val);
}
public void Sync(string name, ref short val)
{
if (IsText) SyncText(name, ref val);
else if (IsReader) Read(ref val);
else Write(ref val);
}
void SyncText(string name, ref short val)
{
if (IsReader) ReadText(name, ref val);
else WriteText(name, ref val);
}
public void Sync(string name, ref int val)
{
if (IsText) SyncText(name, ref val);
else if (IsReader) Read(ref val);
else Write(ref val);
}
void SyncText(string name, ref int val)
{
if (IsReader) ReadText(name, ref val);
else WriteText(name, ref val);
}
public void Sync(string name, ref bool val)
{
if (IsText) SyncText(name, ref val);
else if (IsReader) Read(ref val);
else Write(ref val);
}
void SyncText(string name, ref bool val)
{
if (IsReader) ReadText(name, ref val);
else WriteText(name, ref val);
}
public void SyncFixedString(string name, ref string val, int length)
{
//TODO - this could be made more efficient perhaps just by writing values right out of the string..
if (IsReader)
{
char[] buf = new char[length];
if (isText)
{
tr.Read(buf, 0, length);
}
else
{
br.Read(buf, 0, length);
}
int len = 0;
for (; len < length; len++)
{
if (buf[len] == 0) break;
}
val = new string(buf, 0, len);
}
else
{
if (name.Length > length) throw new InvalidOperationException("SyncFixedString too long");
char[] buf = val.ToCharArray();
char[] remainder = new char[length - buf.Length];
if (IsText)
{
tw.Write(buf);
tw.Write(remainder);
}
else
{
bw.Write(buf);
bw.Write(remainder);
}
}
}
void Read(ref Bit val) { val = br.ReadBit(); }
void Write(ref Bit val) { bw.WriteBit(val); }
void ReadText(string name, ref Bit val) { if(Present(name)) val = (Bit)int.Parse(Item(name)); }
void WriteText(string name, ref Bit val) { tw.WriteLine("{0} {1}", name, (int)val); }
void Read(ref byte val) { val = br.ReadByte(); }
void Write(ref byte val) { bw.Write(val); }
void ReadText(string name, ref byte val) { if (Present(name)) val = byte.Parse(Item(name).Replace("0x", ""), NumberStyles.HexNumber); }
void WriteText(string name, ref byte val) { tw.WriteLine("{0} 0x{1:X2}", name, val); }
void Read(ref ushort val) { val = br.ReadUInt16(); }
void Write(ref ushort val) { bw.Write(val); }
void ReadText(string name, ref ushort val) { if (Present(name)) val = ushort.Parse(Item(name).Replace("0x", ""), NumberStyles.HexNumber); }
void WriteText(string name, ref ushort val) { tw.WriteLine("{0} 0x{1:X4}", name, val); }
void Read(ref uint val) { val = br.ReadUInt32(); }
void Write(ref uint val) { bw.Write(val); }
void ReadText(string name, ref uint val) { if (Present(name)) val = uint.Parse(Item(name).Replace("0x", ""), NumberStyles.HexNumber); }
void WriteText(string name, ref uint val) { tw.WriteLine("{0} 0x{1:X8}", name, val); }
void Read(ref sbyte val) { val = br.ReadSByte(); }
void Write(ref sbyte val) { bw.Write(val); }
void ReadText(string name, ref sbyte val) { if (Present(name)) val = sbyte.Parse(Item(name).Replace("0x", ""), NumberStyles.HexNumber); }
void WriteText(string name, ref sbyte val) { tw.WriteLine("{0} 0x{1:X2}", name, val); }
void Read(ref short val) { val = br.ReadInt16(); }
void Write(ref short val) { bw.Write(val); }
void ReadText(string name, ref short val) { if (Present(name)) val = short.Parse(Item(name).Replace("0x", ""), NumberStyles.HexNumber); }
void WriteText(string name, ref short val) { tw.WriteLine("{0} 0x{1:X4}", name, val); }
void Read(ref int val) { val = br.ReadInt32(); }
void Write(ref int val) { bw.Write(val); }
void ReadText(string name, ref int val) { if (Present(name)) val = int.Parse(Item(name).Replace("0x", ""), NumberStyles.HexNumber); }
void WriteText(string name, ref int val) { tw.WriteLine("{0} 0x{1:X8}", name, val); }
void Read(ref bool val) { val = br.ReadBoolean(); }
void Write(ref bool val) { bw.Write(val); }
void ReadText(string name, ref bool val) { if (Present(name)) val = bool.Parse(Item(name)); }
void WriteText(string name, ref bool val) { tw.WriteLine("{0} {1}", name, val); }
}
public static class BITREV
{
public static byte[] byte_8;
static BITREV()
{
make_byte_8();
}
static void make_byte_8()
{
int bits = 8;
int n = 1 << 8;
byte_8 = new byte[n];
int m = 1;
int a = n >> 1;
int j = 2;
byte_8[0] = 0;
byte_8[1] = (byte)a;
while ((--bits) != 0)
{
m <<= 1;
a >>= 1;
for (int i = 0; i < m; i++)
byte_8[j++] = (byte)(byte_8[i] + a);
}
}
public static uint reverse_32(uint v)
{
return (uint)((byte_8[v & 0xff] << 24) |
(byte_8[(v >> 8) & 0xff] << 16) |
(byte_8[(v >> 16) & 0xff] << 8) |
(byte_8[(v >> 24) & 0xff]));
}
}
/// <summary>
/// a Dictionary-of-lists with key K and values List&lt;V&gt;
/// </summary>
[Serializable]
public class Bag<K, V> : BagBase<K, V, Dictionary<K, List<V>>, List<V>> { }
/// <summary>
/// a Dictionary-of-lists with key K and values List&lt;V&gt;
/// </summary>
[Serializable]
public class SortedBag<K, V> : BagBase<K, V, SortedDictionary<K, List<V>>, List<V>> { }
/// <summary>
/// A dictionary that creates new values on the fly as necessary so that any key you need will be defined.
/// </summary>
/// <typeparam name="K">dictionary keys</typeparam>
/// <typeparam name="V">dictionary values</typeparam>
public class WorkingDictionary<K, V> : Dictionary<K, V> where V : new()
{
public new V this[K key]
{
get
{
V temp;
if (!TryGetValue(key, out temp))
temp = this[key] = new V();
return temp;
}
set { base[key] = value; }
}
}
/// <summary>
/// base class for Bag and SortedBag
/// </summary>
/// <typeparam name="K">dictionary keys</typeparam>
/// <typeparam name="V">list values</typeparam>
/// <typeparam name="D">dictionary type</typeparam>
/// <typeparam name="L">list type</typeparam>
[Serializable]
public class BagBase<K, V, D, L> : IEnumerable<V>
where D : IDictionary<K, L>, new()
where L : IList<V>, IEnumerable<V>, new()
{
D dictionary = new D();
public void Add(K key, V val)
{
this[key].Add(val);
}
public bool ContainsKey(K key) { return dictionary.ContainsKey(key); }
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public IEnumerator<V> GetEnumerator()
{
foreach (L lv in dictionary.Values)
foreach (V v in lv)
yield return v;
}
public IEnumerable KeyValuePairEnumerator { get { return dictionary; } }
/// <summary>
/// the list of keys contained herein
/// </summary>
public IList<K> Keys { get { return new List<K>(dictionary.Keys); } }
public L this[K key]
{
get
{
L slot;
if (!dictionary.TryGetValue(key, out slot))
dictionary[key] = slot = new L();
return slot;
}
set
{
dictionary[key] = value;
}
}
}
public class NotTestedException : Exception
{
}
}
*/