From 56e22f34a53834a53893d9d7cc0b038983500e3d Mon Sep 17 00:00:00 2001 From: YoshiRulz Date: Tue, 9 Nov 2021 20:22:21 +1000 Subject: [PATCH] Use `TryGetValue` instead of `ContainsKey` + indexer --- .../Api/Classes/EmulationApi.cs | 2 +- .../DisplayManager/DisplayManagerBase.cs | 13 +--- .../inputAdapters/OverrideAdapter.cs | 34 ++--------- .../inputAdapters/StickyAdapters.cs | 20 ++---- .../movie/MovieSession.cs | 8 +-- .../movie/PlatformFrameRates.cs | 5 +- .../movie/bk2/Bk2Header.cs | 2 +- .../movie/bk2/Bk2MnemonicLookup.cs | 16 ++--- .../movie/bk2/Bk2Movie.HeaderApi.cs | 35 +++++------ .../movie/bk2/Bk2Movie.cs | 12 ++-- .../movie/import/bkm/BkmHeader.cs | 18 +----- .../config/ControllerConfig.cs | 17 ++---- .../config/FirmwaresConfig.cs | 6 +- .../tools/HexEditor/HexEditor.cs | 5 +- .../tools/Lua/LuaPictureBox.cs | 14 +---- .../tools/PCE/PCESoundDebugger.cs | 7 +-- src/BizHawk.Common/Serializer.cs | 19 +----- .../Base Implementations/CodeDataLog.cs | 12 +--- .../Database/Database.cs | 4 +- .../Database/GameInfo.cs | 2 +- .../AmstradCPC/Media/Tape/TapeDataBlock.cs | 16 +---- .../Media/Tape/TapeDataBlock.cs | 15 +---- .../Consoles/Atari/2600/Atari2600.Core.cs | 14 ++--- .../Consoles/Atari/A7800Hawk/A7800Hawk.cs | 26 +++----- .../Consoles/Intellivision/Cartridge.cs | 23 +------ .../Consoles/Nintendo/NES/NES.BoardSystem.cs | 61 +++++++------------ .../Consoles/Sony/PSX/PSF.cs | 4 +- .../Waterbox/NymaCore.Controller.cs | 2 +- .../DiscFormats/CCD_format.cs | 4 +- 29 files changed, 112 insertions(+), 304 deletions(-) diff --git a/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs b/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs index 9ad4611a4b..398b585c2e 100644 --- a/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs @@ -102,7 +102,7 @@ namespace BizHawk.Client.Common if (DebuggableCore != null) { var registers = DebuggableCore.GetCpuFlagsAndRegisters(); - return registers.ContainsKey(name) ? registers[name].Value : (ulong?) null; + return registers.TryGetValue(name, out var rv) ? rv.Value : (ulong?) null; } } catch (NotImplementedException) {} diff --git a/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs b/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs index e036ac88f7..05700ae37e 100644 --- a/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs +++ b/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs @@ -1020,11 +1020,7 @@ namespace BizHawk.Client.Common /// Peeks a locked lua surface, or returns null if it isn't locked /// public IDisplaySurface PeekApiHawkLockedSurface(DisplaySurfaceID surfaceID) - { - if (_apiHawkIDToSurface.ContainsKey(surfaceID)) - return _apiHawkIDToSurface[surfaceID]; - return null; - } + => _apiHawkIDToSurface.TryGetValue(surfaceID, out var surface) ? surface : null; public IDisplaySurface LockApiHawkSurface(DisplaySurfaceID surfaceID, bool clear) { @@ -1082,12 +1078,7 @@ namespace BizHawk.Client.Common public void UnlockApiHawkSurface(IDisplaySurface surface) { if (surface is not DisplaySurface dispSurfaceImpl) throw new ArgumentException("don't mix " + nameof(IDisplaySurface) + " implementations!", nameof(surface)); - if (!_apiHawkSurfaceToID.ContainsKey(dispSurfaceImpl)) - { - throw new InvalidOperationException("Surface was not locked as a lua surface"); - } - - var surfaceID = _apiHawkSurfaceToID[dispSurfaceImpl]; + if (!_apiHawkSurfaceToID.TryGetValue(dispSurfaceImpl, out var surfaceID)) throw new InvalidOperationException("Surface was not locked as a lua surface"); _apiHawkSurfaceToID.Remove(dispSurfaceImpl); _apiHawkIDToSurface.Remove(surfaceID); _apiHawkSurfaceSets[surfaceID].SetPending(dispSurfaceImpl); diff --git a/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs b/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs index 02cd96d7ca..fd72390cb2 100644 --- a/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs +++ b/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs @@ -19,19 +19,10 @@ namespace BizHawk.Client.Common /// not overridden public bool IsPressed(string button) - { - if (_overrides.ContainsKey(button)) - { - return _overrides[button]; - } - - throw new InvalidOperationException(); - } + => _overrides.TryGetValue(button, out var b) ? b : throw new InvalidOperationException(); public int AxisValue(string name) - => _axisOverrides.ContainsKey(name) - ? _axisOverrides[name] - : 0; + => _axisOverrides.TryGetValue(name, out var i) ? i : 0; public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => throw new NotImplementedException(); // no idea --yoshi @@ -44,28 +35,11 @@ namespace BizHawk.Client.Common public IEnumerable InversedButtons => _inverses; public void SetAxis(string name, int value) - { - if (_axisOverrides.ContainsKey(name)) - { - _axisOverrides[name] = value; - } - else - { - _axisOverrides.Add(name, value); - } - } + => _axisOverrides[name] = value; public void SetButton(string button, bool value) { - if (_overrides.ContainsKey(button)) - { - _overrides[button] = value; - } - else - { - _overrides.Add(button, value); - } - + _overrides[button] = value; _inverses.Remove(button); } diff --git a/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs b/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs index a12aa2de0b..988f7023e9 100644 --- a/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs +++ b/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs @@ -119,10 +119,10 @@ namespace BizHawk.Client.Common { var source = Source.IsPressed(button); bool patternValue = false; - if (_boolPatterns.ContainsKey(button)) + if (_boolPatterns.TryGetValue(button, out var pattern)) { // I can't figure a way to determine right here if it should Peek or Get. - patternValue = _boolPatterns[button].PeekNextValue(); + patternValue = pattern.PeekNextValue(); } source ^= patternValue; @@ -131,19 +131,9 @@ namespace BizHawk.Client.Common } public int AxisValue(string name) - { - if (_axisPatterns.ContainsKey(name)) - { - return _axisPatterns[name].PeekNextValue(); - } - - if (Source == null) - { - return 0; - } - - return Source.AxisValue(name); - } + => _axisPatterns.TryGetValue(name, out var pattern) + ? pattern.PeekNextValue() + : Source?.AxisValue(name) ?? 0; public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => Source.GetHapticsSnapshot(); diff --git a/src/BizHawk.Client.Common/movie/MovieSession.cs b/src/BizHawk.Client.Common/movie/MovieSession.cs index d32ef14380..66bfd84cd2 100644 --- a/src/BizHawk.Client.Common/movie/MovieSession.cs +++ b/src/BizHawk.Client.Common/movie/MovieSession.cs @@ -352,12 +352,8 @@ namespace BizHawk.Client.Common if (Movie.IsAtEnd() && Movie.Core == CoreNames.Gambatte) { var coreCycles = (ulong) ((Gameboy)Movie.Emulator).CycleCount; - var cyclesSaved = Movie.HeaderEntries.ContainsKey(HeaderKeys.CycleCount); - ulong previousCycles = 0; - if (cyclesSaved) - { - previousCycles = Convert.ToUInt64(Movie.HeaderEntries[HeaderKeys.CycleCount]); - } + var cyclesSaved = Movie.HeaderEntries.TryGetValue(HeaderKeys.CycleCount, out var previousCyclesStr); + var previousCycles = cyclesSaved ? Convert.ToUInt64(previousCyclesStr) : 0UL; var cyclesMatch = previousCycles == coreCycles; if (!cyclesSaved || !cyclesMatch) { diff --git a/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs b/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs index 8132ae5291..cf91a8a5ad 100644 --- a/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs +++ b/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs @@ -78,9 +78,6 @@ namespace BizHawk.Client.Common }; public static double GetFrameRate(string systemId, bool pal) - { - var key = systemId + (pal ? "_PAL" : ""); - return Rates.ContainsKey(key) ? Rates[key] : 60.0; - } + => Rates.TryGetValue(systemId + (pal ? "_PAL" : ""), out var d) ? d : 60.0; } } diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs index 83165be63c..d895990f27 100644 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs @@ -7,7 +7,7 @@ namespace BizHawk.Client.Common { public new string this[string key] { - get => ContainsKey(key) ? base[key] : ""; + get => TryGetValue(key, out var s) ? s : string.Empty; set => base[key] = value; } diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs index 83ad8e1380..6f4b8a54de 100644 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs @@ -20,14 +20,14 @@ namespace BizHawk.Client.Common } } - if (SystemOverrides.ContainsKey(systemId) && SystemOverrides[systemId].ContainsKey(key)) + if (SystemOverrides.TryGetValue(systemId, out var overridesForSys) && overridesForSys.TryGetValue(key, out var c)) { - return SystemOverrides[systemId][key]; + return c; } - if (BaseMnemonicLookupTable.ContainsKey(key)) + if (BaseMnemonicLookupTable.TryGetValue(key, out var c1)) { - return BaseMnemonicLookupTable[key]; + return c1; } if (key.Length == 1) @@ -47,14 +47,14 @@ namespace BizHawk.Client.Common .Replace("P4 ", "") .Replace("Key ", ""); - if (AxisSystemOverrides.ContainsKey(systemId) && AxisSystemOverrides[systemId].ContainsKey(key)) + if (AxisSystemOverrides.TryGetValue(systemId, out var overridesForSystem) && overridesForSystem.TryGetValue(key, out var s)) { - return AxisSystemOverrides[systemId][key]; + return s; } - if (BaseAxisLookupTable.ContainsKey(key)) + if (BaseAxisLookupTable.TryGetValue(key, out var s1)) { - return BaseAxisLookupTable[key]; + return s1; } return button; diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs index b30ac9b23d..07e4245eff 100644 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs @@ -28,17 +28,9 @@ namespace BizHawk.Client.Common public ulong Rerecords { - get - { - if (!Header.ContainsKey(HeaderKeys.Rerecords)) - { - // Modifying the header itself can cause a race condition between loading a movie and rendering the rerecord count, causing a movie's rerecord count to be overwritten with 0 during loading. - return 0; - } - - return ulong.Parse(Header[HeaderKeys.Rerecords]); - } - + get => Header.TryGetValue(HeaderKeys.Rerecords, out var s) + ? ulong.Parse(s) + : 0UL; // Modifying the header itself can cause a race condition between loading a movie and rendering the rerecord count, causing a movie's rerecord count to be overwritten with 0 during loading. set { if (Header[HeaderKeys.Rerecords] != value.ToString()) @@ -51,7 +43,9 @@ namespace BizHawk.Client.Common public virtual bool StartsFromSavestate { - get => Header.ContainsKey(HeaderKeys.StartsFromSavestate) && bool.Parse(Header[HeaderKeys.StartsFromSavestate]); + // ReSharper disable SimplifyConditionalTernaryExpression + get => Header.TryGetValue(HeaderKeys.StartsFromSavestate, out var s) ? bool.Parse(s) : false; + // ReSharper restore SimplifyConditionalTernaryExpression set { if (value) @@ -67,7 +61,9 @@ namespace BizHawk.Client.Common public bool StartsFromSaveRam { - get => Header.ContainsKey(HeaderKeys.StartsFromSaveram) && bool.Parse(Header[HeaderKeys.StartsFromSaveram]); + // ReSharper disable SimplifyConditionalTernaryExpression + get => Header.TryGetValue(HeaderKeys.StartsFromSaveram, out var s) ? bool.Parse(s) : false; + // ReSharper restore SimplifyConditionalTernaryExpression set { if (value) @@ -79,17 +75,14 @@ namespace BizHawk.Client.Common } else { - if (Header.ContainsKey(HeaderKeys.StartsFromSaveram)) - { - Header.Remove(HeaderKeys.StartsFromSaveram); - } + Header.Remove(HeaderKeys.StartsFromSaveram); } } } public string GameName { - get => Header.ContainsKey(HeaderKeys.GameName) ? Header[HeaderKeys.GameName] : ""; + get => Header.TryGetValue(HeaderKeys.GameName, out var s) ? s : string.Empty; set { if (Header[HeaderKeys.GameName] != value) @@ -102,7 +95,7 @@ namespace BizHawk.Client.Common public string SystemID { - get => Header.ContainsKey(HeaderKeys.Platform) ? Header[HeaderKeys.Platform] : ""; + get => Header.TryGetValue(HeaderKeys.Platform, out var s) ? s : string.Empty; set { if (Header[HeaderKeys.Platform] != value) @@ -216,7 +209,9 @@ namespace BizHawk.Client.Common return sb.ToString(); } - public bool IsPal => Header.ContainsKey(HeaderKeys.Pal) && Header[HeaderKeys.Pal] == "1"; + // ReSharper disable SimplifyConditionalTernaryExpression + public bool IsPal => Header.TryGetValue(HeaderKeys.Pal, out var s) ? s == "1" : false; + // ReSharper restore SimplifyConditionalTernaryExpression public string TextSavestate { get; set; } public byte[] BinarySavestate { get; set; } diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs index a328f9274d..031792d58f 100755 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs @@ -70,19 +70,17 @@ namespace BizHawk.Client.Common double dblSeconds; var core = Header[HeaderKeys.Core]; - if (Header.ContainsKey(HeaderKeys.CycleCount) && (core == CoreNames.Gambatte || core == CoreNames.SubGbHawk)) + if (Header.TryGetValue(HeaderKeys.CycleCount, out var numCyclesStr) && (core == CoreNames.Gambatte || core == CoreNames.SubGbHawk)) { - ulong numCycles = Convert.ToUInt64(Header[HeaderKeys.CycleCount]); + var numCycles = Convert.ToUInt64(numCyclesStr); double cyclesPerSecond = PlatformFrameRates.GetFrameRate("GB_Clock", IsPal); dblSeconds = numCycles / cyclesPerSecond; } else { - ulong numFrames = (ulong) FrameCount; - if (Header.ContainsKey(HeaderKeys.VBlankCount)) - { - numFrames = Convert.ToUInt64(Header[HeaderKeys.VBlankCount]); - } + var numFrames = Header.TryGetValue(HeaderKeys.VBlankCount, out var numFramesStr) + ? Convert.ToUInt64(numFramesStr) + : (ulong) FrameCount; dblSeconds = numFrames / FrameRate; } diff --git a/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs b/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs index b8bb217862..277a996803 100644 --- a/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs +++ b/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs @@ -17,9 +17,7 @@ namespace BizHawk.Client.Common public string SavestateBinaryBase64Blob { - get => ContainsKey(HeaderKeys.SavestateBinaryBase64Blob) - ? this[HeaderKeys.SavestateBinaryBase64Blob] - : null; + get => TryGetValue(HeaderKeys.SavestateBinaryBase64Blob, out var s) ? s : null; set { if (value == null) @@ -35,18 +33,8 @@ namespace BizHawk.Client.Common public new string this[string key] { - get => ContainsKey(key) ? base[key] : ""; - set - { - if (ContainsKey(key)) - { - base[key] = value; - } - else - { - Add(key, value); - } - } + get => TryGetValue(key, out var s) ? s : string.Empty; + set => base[key] = value; } public new void Clear() diff --git a/src/BizHawk.Client.EmuHawk/config/ControllerConfig.cs b/src/BizHawk.Client.EmuHawk/config/ControllerConfig.cs index 47bc008bab..4067cbe986 100644 --- a/src/BizHawk.Client.EmuHawk/config/ControllerConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/ControllerConfig.cs @@ -137,19 +137,12 @@ namespace BizHawk.Client.EmuHawk // saving works, those entries will still be preserved in the config file, tho foreach (var button in controllerButtons) { - Match m; - string categoryLabel; - if (categoryLabels.ContainsKey(button)) + if (!categoryLabels.TryGetValue(button, out var categoryLabel)) { - categoryLabel = categoryLabels[button]; - } - else if ((m = ButtonMatchesPlayer.Match(button)).Success) - { - categoryLabel = $"Player {m.Groups[1].Value}"; - } - else - { - categoryLabel = "Console"; // anything that wants not console can set it in the categorylabels + var m = ButtonMatchesPlayer.Match(button); + categoryLabel = m.Success + ? $"Player {m.Groups[1].Value}" + : "Console"; // anything that wants not console can set it in the categorylabels } if (!buckets.ContainsKey(categoryLabel)) diff --git a/src/BizHawk.Client.EmuHawk/config/FirmwaresConfig.cs b/src/BizHawk.Client.EmuHawk/config/FirmwaresConfig.cs index 0fc7a0b429..a6b887dac8 100644 --- a/src/BizHawk.Client.EmuHawk/config/FirmwaresConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/FirmwaresConfig.cs @@ -195,15 +195,15 @@ namespace BizHawk.Client.EmuHawk lvFirmwares.Items.Add(lvi); // build the groups in the ListView as we go: - if (!groups.ContainsKey(sysID)) + if (!groups.TryGetValue(sysID, out var group)) { if (!SystemGroupNames.TryGetValue(sysID, out var name)) name = "FIX ME (FirmwaresConfig.cs)"; lvFirmwares.Groups.Add(sysID, name); var lvg = lvFirmwares.Groups[lvFirmwares.Groups.Count - 1]; - groups[sysID] = lvg; + group = groups[sysID] = lvg; } - lvi.Group = groups[sysID]; + lvi.Group = group; } // now that we have some items in the ListView, we can size some columns to sensible widths diff --git a/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs b/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs index d7c3f159dd..5b18421966 100644 --- a/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs +++ b/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs @@ -381,10 +381,7 @@ namespace BizHawk.Client.EmuHawk private char Remap(byte val) { - if (_textTable.Any()) - { - return _textTable.ContainsKey(val) ? _textTable[val] : '?'; - } + if (_textTable.Count != 0) return _textTable.TryGetValue(val, out var c) ? c : '?'; if (val < ' ' || val >= 0x7F) { diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs index fc349d4032..fb9eab4400 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs @@ -165,12 +165,7 @@ namespace BizHawk.Client.EmuHawk public void DrawImage(string path, int x, int y, int? width = null, int? height = null, bool cache = true) { - Image img; - if (_imageCache.ContainsKey(path)) - { - img = _imageCache[path]; - } - else + if (!_imageCache.TryGetValue(path, out var img)) { img = Image.FromFile(path); if (cache) @@ -195,12 +190,7 @@ namespace BizHawk.Client.EmuHawk public void DrawImageRegion(string path, int sourceX, int sourceY, int sourceWidth, int sourceHeight, int destX, int destY, int? destWidth = null, int? destHeight = null) { - Image img; - if (_imageCache.ContainsKey(path)) - { - img = _imageCache[path]; - } - else + if (!_imageCache.TryGetValue(path, out var img)) { img = Image.FromFile(path); _imageCache.Add(path, img); diff --git a/src/BizHawk.Client.EmuHawk/tools/PCE/PCESoundDebugger.cs b/src/BizHawk.Client.EmuHawk/tools/PCE/PCESoundDebugger.cs index 186de35992..1e92d53542 100644 --- a/src/BizHawk.Client.EmuHawk/tools/PCE/PCESoundDebugger.cs +++ b/src/BizHawk.Client.EmuHawk/tools/PCE/PCESoundDebugger.cs @@ -105,9 +105,9 @@ namespace BizHawk.Client.EmuHawk bw.Flush(); string md5 = _waveformTemp.HashMD5(); - if (!_psgEntryTable.ContainsKey(md5)) + if (!_psgEntryTable.TryGetValue(md5, out var entry)) { - var entry = new PsgEntry + entry = new PsgEntry { Name = md5, WaveForm = waveform, @@ -122,7 +122,6 @@ namespace BizHawk.Client.EmuHawk } else { - PsgEntry entry = _psgEntryTable[md5]; entry.Active = true; // are we playing the same sample as before? @@ -141,7 +140,7 @@ namespace BizHawk.Client.EmuHawk } } - lvChannels.Items[i].SubItems[3].Text = _psgEntryTable[md5].Name; + lvChannels.Items[i].SubItems[3].Text = entry.Name; } if (sync) diff --git a/src/BizHawk.Common/Serializer.cs b/src/BizHawk.Common/Serializer.cs index 3138241795..0616b8b572 100644 --- a/src/BizHawk.Common/Serializer.cs +++ b/src/BizHawk.Common/Serializer.cs @@ -802,15 +802,7 @@ namespace BizHawk.Common var name = begin.Groups[1].Value; ss.Push(curs); var news = new Section { Name = name }; - if (!curs.ContainsKey(name)) - { - curs[name] = news; - } - else - { - throw new Exception($"Duplicate key \"{name}\" in serializer savestate!"); - } - + curs.Add(name, news); curs = news; } else @@ -825,14 +817,7 @@ namespace BizHawk.Common 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($"Duplicate key \"{key}\" in serializer savestate!"); - } + curs.Items.Add(key, parts[1]); } } diff --git a/src/BizHawk.Emulation.Common/Base Implementations/CodeDataLog.cs b/src/BizHawk.Emulation.Common/Base Implementations/CodeDataLog.cs index 3f257d8270..c92a21c25a 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/CodeDataLog.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/CodeDataLog.cs @@ -93,17 +93,9 @@ namespace BizHawk.Emulation.Common foreach (var kvp in this) { - if (!other.ContainsKey(kvp.Key)) - { - return false; - } - - var oval = other[kvp.Key]; - if (oval.Length != kvp.Value.Length) - { - return false; - } + if (!other.TryGetValue(kvp.Key, out var oval) || oval.Length != kvp.Value.Length) return false; } + // don't need to check keys present in other but not in this -- `Count` would differ return true; } diff --git a/src/BizHawk.Emulation.Common/Database/Database.cs b/src/BizHawk.Emulation.Common/Database/Database.cs index 7418fa5f2e..6962b7c70f 100644 --- a/src/BizHawk.Emulation.Common/Database/Database.cs +++ b/src/BizHawk.Emulation.Common/Database/Database.cs @@ -144,9 +144,9 @@ namespace BizHawk.Emulation.Common ForcedCore = items.Length >= 8 ? items[7].ToLowerInvariant() : "" }; - if (!silent && DB.ContainsKey(game.Hash)) + if (!silent && DB.TryGetValue(game.Hash, out var dupe)) { - Console.WriteLine("gamedb: Multiple hash entries {0}, duplicate detected on \"{1}\" and \"{2}\"", game.Hash, game.Name, DB[game.Hash].Name); + Console.WriteLine("gamedb: Multiple hash entries {0}, duplicate detected on \"{1}\" and \"{2}\"", game.Hash, game.Name, dupe.Name); } DB[game.Hash] = game; diff --git a/src/BizHawk.Emulation.Common/Database/GameInfo.cs b/src/BizHawk.Emulation.Common/Database/GameInfo.cs index 9d4fb881a8..7503631886 100644 --- a/src/BizHawk.Emulation.Common/Database/GameInfo.cs +++ b/src/BizHawk.Emulation.Common/Database/GameInfo.cs @@ -85,7 +85,7 @@ namespace BizHawk.Emulation.Common public string OptionValue(string option) { - return Options.ContainsKey(option) ? Options[option] : null; + return Options.TryGetValue(option, out var s) ? s : null; } public int GetIntValue(string option) diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/TapeDataBlock.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/TapeDataBlock.cs index 53e2d50ed4..5ba41f11da 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/TapeDataBlock.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/TapeDataBlock.cs @@ -88,21 +88,7 @@ namespace BizHawk.Emulation.Cores.Computers.AmstradCPC /// Adds a single metadata item to the Dictionary /// public void AddMetaData(BlockDescriptorTitle descriptor, string data) - { - // check whether entry already exists - bool check = MetaData.ContainsKey(descriptor); - if (check) - { - // already exists - update - MetaData[descriptor] = data; - } - else - { - // create new - MetaData.Add(descriptor, data); - } - } - + => MetaData[descriptor] = data; /// /// List containing the pulse timing values diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TapeDataBlock.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TapeDataBlock.cs index adb8605455..293732f6c3 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TapeDataBlock.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TapeDataBlock.cs @@ -63,20 +63,7 @@ namespace BizHawk.Emulation.Cores.Computers.SinclairSpectrum /// Adds a single metadata item to the Dictionary /// public void AddMetaData(BlockDescriptorTitle descriptor, string data) - { - // check whether entry already exists - bool check = MetaData.ContainsKey(descriptor); - if (check) - { - // already exists - update - MetaData[descriptor] = data; - } - else - { - // create new - MetaData.Add(descriptor, data); - } - } + => MetaData[descriptor] = data; /// /// List containing the pulse timing values diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.Core.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.Core.cs index 4b4a958b40..4d9c0235b5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.Core.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.Core.cs @@ -223,19 +223,13 @@ namespace BizHawk.Emulation.Cores.Atari.Atari2600 RomDetails = $"{_game.Name}\r\nSHA1:{Rom.HashSHA1()}\r\nMD5:{Rom.HashMD5()}\r\nMapper Impl \"{_mapper.GetType()}\""; // Some games (ex. 3D tic tac toe), turn off the screen for extended periods, so we need to allow for this here. - if (_game.GetOptions().ContainsKey("SP_FRAME")) + if (_game.GetOptions().TryGetValue("SP_FRAME", out var spFrameStr) && spFrameStr == "true") { - if (_game.GetOptions()["SP_FRAME"] == "true") - { - SP_FRAME = true; - } + SP_FRAME = true; } - if (_game.GetOptions().ContainsKey("SP_RESET")) + if (_game.GetOptions().TryGetValue("SP_RESET", out var spResetStr) && spResetStr == "true") { - if (_game.GetOptions()["SP_RESET"] == "true") - { - SP_RESET = true; - } + SP_RESET = true; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs index 9ef3576a8a..68ce12aac3 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs @@ -133,36 +133,30 @@ namespace BizHawk.Emulation.Cores.Atari.A7800Hawk { _isPAL = true; } - if (dict.ContainsKey("board")) - { - s_mapper = dict["board"]; - } - else - { - throw new Exception("No Board selected for this game"); - } + + if (!dict.TryGetValue("board", out s_mapper)) throw new Exception("No Board selected for this game"); // check if the game uses pokey or RAM - if (dict.ContainsKey("RAM")) + if (dict.TryGetValue("RAM", out var cartRAMStr)) { - int.TryParse(dict["RAM"], out cart_RAM); + int.TryParse(cartRAMStr, out cart_RAM); } - if (dict.ContainsKey("Pokey")) + if (dict.TryGetValue("Pokey", out var pokeyStr)) { - bool.TryParse(dict["Pokey"], out is_pokey); + bool.TryParse(pokeyStr, out is_pokey); } - if (dict.ContainsKey("Pokey_450")) + if (dict.TryGetValue("Pokey_450", out var pokey450Str)) { - bool.TryParse(dict["Pokey_450"], out is_pokey_450); + bool.TryParse(pokey450Str, out is_pokey_450); } // some games will not function with the high score bios // if such a game is being played, tell the user and disable it - if (dict.ContainsKey("No_HS")) + if (dict.TryGetValue("No_HS", out var noHSStr)) { - bool.TryParse(dict["No_HS"], out var no_hs); + bool.TryParse(noHSStr, out var no_hs); if (no_hs) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Cartridge.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Cartridge.cs index 53ef6ed37d..93ccad5e8a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Cartridge.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Cartridge.cs @@ -39,27 +39,10 @@ namespace BizHawk.Emulation.Cores.Intellivision } // look up hash in gamedb to see what mapper to use - // if none found default is zero - string hash_sha1 = null; string s_mapper = null; - hash_sha1 = "sha1:" + rom.HashSHA1(16, rom.Length - 16); - - var gi = Database.CheckDatabase(hash_sha1); - if (gi != null) - { - var dict = gi.GetOptions(); - if (!dict.ContainsKey("board")) - { - throw new Exception("INTV gamedb entries must have a board identifier!"); - } - - s_mapper = dict["board"]; - } - else - { - s_mapper = "0"; - } - + var gi = Database.CheckDatabase($"sha1:{rom.HashSHA1(16, rom.Length - 16)}"); + if (gi != null && !gi.GetOptions().TryGetValue("board", out s_mapper)) throw new Exception("INTV gamedb entries must have a board identifier!"); + _mapper = 0; int.TryParse(s_mapper, out _mapper); return rom.Length; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.BoardSystem.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.BoardSystem.cs index 06977f6295..f4f486a5c8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.BoardSystem.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.BoardSystem.cs @@ -163,54 +163,35 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES //try generating a bootgod cart descriptor from the game database var dict = gi.GetOptions(); cart.GameInfo = gi; - if (!dict.ContainsKey("board")) - throw new Exception("NES gamedb entries must have a board identifier!"); - cart.BoardType = dict["board"]; - if (dict.ContainsKey("system")) - cart.System = dict["system"]; - cart.PrgSize = -1; - cart.VramSize = -1; - cart.WramSize = -1; - cart.ChrSize = -1; - if (dict.ContainsKey("PRG")) - cart.PrgSize = short.Parse(dict["PRG"]); - if (dict.ContainsKey("CHR")) - cart.ChrSize = short.Parse(dict["CHR"]); - if(dict.ContainsKey("VRAM")) - cart.VramSize = short.Parse(dict["VRAM"]); - if (dict.ContainsKey("WRAM")) - cart.WramSize = short.Parse(dict["WRAM"]); - if (dict.ContainsKey("PAD_H")) - cart.PadH = byte.Parse(dict["PAD_H"]); - if (dict.ContainsKey("PAD_V")) - cart.PadV = byte.Parse(dict["PAD_V"]); - if(dict.ContainsKey("MIR")) - if (dict["MIR"] == "H") + if (!dict.TryGetValue("board", out var board)) throw new Exception("NES gamedb entries must have a board identifier!"); + cart.BoardType = board; + if (dict.TryGetValue("system", out var system)) cart.System = system; + + cart.PrgSize = dict.TryGetValue("PRG", out var prgSizeStr) ? short.Parse(prgSizeStr) : -1; + cart.ChrSize = dict.TryGetValue("CHR", out var chrSizeStr) ? short.Parse(chrSizeStr) : -1; + cart.VramSize = dict.TryGetValue("VRAM", out var vramSizeStr) ? short.Parse(vramSizeStr) : -1; + cart.WramSize = dict.TryGetValue("WRAM", out var wramSizeStr) ? short.Parse(wramSizeStr) : -1; + + if (dict.TryGetValue("PAD_H", out var padHStr)) cart.PadH = byte.Parse(padHStr); + if (dict.TryGetValue("PAD_V", out var padVStr)) cart.PadV = byte.Parse(padVStr); + if (dict.TryGetValue("MIR", out var mirStr)) + { + if (mirStr == "H") { cart.PadV = 1; cart.PadH = 0; } - else if (dict["MIR"] == "V") + else if (mirStr == "V") { cart.PadH = 1; cart.PadV = 0; } - if (dict.ContainsKey("BAD")) - cart.Bad = true; - if (dict.ContainsKey("MMC3")) - cart.Chips.Add(dict["MMC3"]); - if (dict.ContainsKey("PCB")) - cart.Pcb = dict["PCB"]; - if (dict.ContainsKey("BATT")) - cart.WramBattery = bool.Parse(dict["BATT"]); - - if(dict.ContainsKey("palette")) - { - cart.Palette = dict["palette"]; } - if (dict.ContainsKey("vs_security")) - { - cart.VsSecurity = byte.Parse(dict["vs_security"]); - } + if (dict.ContainsKey("BAD")) cart.Bad = true; + if (dict.TryGetValue("MMC3", out var mmc3)) cart.Chips.Add(mmc3); + if (dict.TryGetValue("PCB", out var pcb)) cart.Pcb = pcb; + if (dict.TryGetValue("BATT", out var batteryStr)) cart.WramBattery = bool.Parse(batteryStr); + if (dict.TryGetValue("palette", out var palette)) cart.Palette = palette; + if (dict.TryGetValue("vs_security", out var vsSecurityStr)) cart.VsSecurity = byte.Parse(vsSecurityStr); return cart; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/PSF.cs b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/PSF.cs index 76d1d8d7fc..4ec469872b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/PSF.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/PSF.cs @@ -58,9 +58,9 @@ namespace BizHawk.Emulation.Cores.Sony.PSX Data = cbDeflater(fs, compressed_size); //load lib if needed - if (TagsDictionary.ContainsKey("_lib")) + if (TagsDictionary.TryGetValue("_lib", out var relPath)) { - var fpLib = Path.Combine(Path.GetDirectoryName(fpPSF), TagsDictionary["_lib"]); + var fpLib = Path.Combine(Path.GetDirectoryName(fpPSF), relPath); if (!File.Exists(fpLib)) return false; PSF lib = new PSF(); diff --git a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.cs b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.cs index 38a10e9cc1..88afe1b055 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.cs @@ -64,7 +64,7 @@ namespace BizHawk.Emulation.Cores.Waterbox for (int port = 0, devByteStart = 0; port < allPorts.Count; port++) { var portInfo = allPorts[port]; - var deviceName = config.ContainsKey(port) ? config[port] : portInfo.DefaultDeviceShortName; + if (!config.TryGetValue(port, out var deviceName)) deviceName = portInfo.DefaultDeviceShortName; finalDevices.Add(deviceName); if (hiddenPorts.Contains(portInfo.ShortName)) diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CCD_format.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CCD_format.cs index 4a59b8e3f6..ac8d2b982f 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CCD_format.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CCD_format.cs @@ -233,14 +233,12 @@ namespace BizHawk.Emulation.DiscSystem if (ccdSection.Name != "CLONECD") throw new CCDParseException("Malformed CCD format: confusing first section name"); - if (!ccdSection.ContainsKey("VERSION")) + if (!ccdSection.TryGetValue("VERSION", out var version)) throw new CCDParseException("Malformed CCD format: missing version in CloneCD section"); if(sections[1].Name != "DISC") throw new CCDParseException("Malformed CCD format: section[1] isn't [Disc]"); - int version = ccdSection["VERSION"]; - return version; }