Skip to content

Commit

Permalink
Fix CA1854
Browse files Browse the repository at this point in the history
  • Loading branch information
RoosterDragon authored and abcdefg30 committed Jun 20, 2023
1 parent 56fe08c commit 231bf01
Show file tree
Hide file tree
Showing 26 changed files with 93 additions and 86 deletions.
3 changes: 3 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,9 @@ dotnet_diagnostic.CA1852.severity = warning
# Unnecessary call to 'Dictionary.ContainsKey(key)'.
dotnet_diagnostic.CA1853.severity = warning

# Prefer the IDictionary.TryGetValue(TKey, out TValue) method.
dotnet_diagnostic.CA1854.severity = warning

# Use Span<T>.Clear() instead of Span<T>.Fill().
dotnet_diagnostic.CA1855.severity = warning

Expand Down
12 changes: 6 additions & 6 deletions OpenRA.Game/GameRules/MusicInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ public MusicInfo(string key, MiniYaml value)
Title = value.Value;

var nd = value.ToDictionary();
if (nd.ContainsKey("Hidden"))
bool.TryParse(nd["Hidden"].Value, out Hidden);
if (nd.TryGetValue("Hidden", out var yaml))
bool.TryParse(yaml.Value, out Hidden);

if (nd.ContainsKey("VolumeModifier"))
VolumeModifier = FieldLoader.GetValue<float>("VolumeModifier", nd["VolumeModifier"].Value);
if (nd.TryGetValue("VolumeModifier", out yaml))
VolumeModifier = FieldLoader.GetValue<float>("VolumeModifier", yaml.Value);

var ext = nd.ContainsKey("Extension") ? nd["Extension"].Value : "aud";
Filename = (nd.ContainsKey("Filename") ? nd["Filename"].Value : key) + "." + ext;
var ext = nd.TryGetValue("Extension", out yaml) ? yaml.Value : "aud";
Filename = (nd.TryGetValue("Filename", out yaml) ? yaml.Value : key) + "." + ext;
}

public void Load(IReadOnlyFileSystem fileSystem)
Expand Down
19 changes: 10 additions & 9 deletions OpenRA.Game/Graphics/CursorSequence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,13 @@ public CursorSequence(FrameCache cache, string name, string cursorSrc, string pa
var cursorSprites = cache[cursorSrc];
Frames = cursorSprites.Skip(Start).ToArray();

if ((d.ContainsKey("Length") && d["Length"].Value == "*") || (d.ContainsKey("End") && d["End"].Value == "*"))
if ((d.TryGetValue("Length", out var yaml) && yaml.Value == "*") ||
(d.TryGetValue("End", out yaml) && yaml.Value == "*"))
Length = Frames.Length;
else if (d.ContainsKey("Length"))
Length = Exts.ParseIntegerInvariant(d["Length"].Value);
else if (d.ContainsKey("End"))
Length = Exts.ParseIntegerInvariant(d["End"].Value) - Start;
else if (d.TryGetValue("Length", out yaml))
Length = Exts.ParseIntegerInvariant(yaml.Value);
else if (d.TryGetValue("End", out yaml))
Length = Exts.ParseIntegerInvariant(yaml.Value) - Start;
else
Length = 1;

Expand All @@ -51,15 +52,15 @@ public CursorSequence(FrameCache cache, string name, string cursorSrc, string pa
if (Length > cursorSprites.Length)
throw new YamlException($"Cursor {name}: {nameof(Length)} is greater than the length of the sprite sequence.");

if (d.ContainsKey("X"))
if (d.TryGetValue("X", out yaml))
{
Exts.TryParseIntegerInvariant(d["X"].Value, out var x);
Exts.TryParseIntegerInvariant(yaml.Value, out var x);
Hotspot = Hotspot.WithX(x);
}

if (d.ContainsKey("Y"))
if (d.TryGetValue("Y", out yaml))
{
Exts.TryParseIntegerInvariant(d["Y"].Value, out var y);
Exts.TryParseIntegerInvariant(yaml.Value, out var y);
Hotspot = Hotspot.WithY(y);
}
}
Expand Down
3 changes: 3 additions & 0 deletions OpenRA.Game/Graphics/HardwarePalette.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ public void AddPalette(string name, ImmutablePalette p, bool allowModifiers)
CopyPaletteToBuffer(index, p);
}

[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Performance", "CA1854:Prefer the 'IDictionary.TryGetValue(TKey, out TValue)' method",
Justification = "False positive - indexer is a set not a get.")]
public void ReplacePalette(string name, IPalette p)
{
if (mutablePalettes.ContainsKey(name))
Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Game/Graphics/WorldRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ public void ReplacePalette(string name, IPalette pal)
palette.ReplacePalette(name, pal);

// Update cached PlayerReference if one exists
if (palettes.ContainsKey(name))
palettes[name].Palette = pal;
if (palettes.TryGetValue(name, out var paletteReference))
paletteReference.Palette = pal;
}

public void SetPaletteColorShift(string name, float hueOffset, float satOffset, float valueModifier, float minHue, float maxHue)
Expand Down
5 changes: 4 additions & 1 deletion OpenRA.Game/HotkeyManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,17 @@ public HotkeyManager(IReadOnlyFileSystem fileSystem, Dictionary<string, Hotkey>

foreach (var kv in settings)
{
if (definitions.ContainsKey(kv.Key) && !definitions[kv.Key].Readonly)
if (definitions.TryGetValue(kv.Key, out var definition) && !definition.Readonly)
keys[kv.Key] = kv.Value;
}

foreach (var hd in definitions)
hd.Value.HasDuplicates = GetFirstDuplicate(hd.Value, this[hd.Value.Name].GetValue()) != null;
}

[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Performance", "CA1854:Prefer the 'IDictionary.TryGetValue(TKey, out TValue)' method",
Justification = "Func must perform a live lookup in the collection, as the lookup value can change.")]
internal Func<Hotkey> GetHotkeyReference(string name)
{
// Is this a mod-defined hotkey?
Expand Down
24 changes: 12 additions & 12 deletions OpenRA.Game/Manifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,25 +157,25 @@ public Manifest(string modId, IReadOnlyPackage package)
// Allow inherited mods to import parent maps.
var compat = new List<string> { Id };

if (yaml.ContainsKey("SupportsMapsFrom"))
compat.AddRange(yaml["SupportsMapsFrom"].Value.Split(',').Select(c => c.Trim()));
if (yaml.TryGetValue("SupportsMapsFrom", out var entry))
compat.AddRange(entry.Value.Split(',').Select(c => c.Trim()));

MapCompatibility = compat.ToArray();

if (yaml.ContainsKey("DefaultOrderGenerator"))
DefaultOrderGenerator = yaml["DefaultOrderGenerator"].Value;
if (yaml.TryGetValue("DefaultOrderGenerator", out entry))
DefaultOrderGenerator = entry.Value;

if (yaml.ContainsKey("PackageFormats"))
PackageFormats = FieldLoader.GetValue<string[]>("PackageFormats", yaml["PackageFormats"].Value);
if (yaml.TryGetValue("PackageFormats", out entry))
PackageFormats = FieldLoader.GetValue<string[]>("PackageFormats", entry.Value);

if (yaml.ContainsKey("SoundFormats"))
SoundFormats = FieldLoader.GetValue<string[]>("SoundFormats", yaml["SoundFormats"].Value);
if (yaml.TryGetValue("SoundFormats", out entry))
SoundFormats = FieldLoader.GetValue<string[]>("SoundFormats", entry.Value);

if (yaml.ContainsKey("SpriteFormats"))
SpriteFormats = FieldLoader.GetValue<string[]>("SpriteFormats", yaml["SpriteFormats"].Value);
if (yaml.TryGetValue("SpriteFormats", out entry))
SpriteFormats = FieldLoader.GetValue<string[]>("SpriteFormats", entry.Value);

if (yaml.ContainsKey("VideoFormats"))
VideoFormats = FieldLoader.GetValue<string[]>("VideoFormats", yaml["VideoFormats"].Value);
if (yaml.TryGetValue("VideoFormats", out entry))
VideoFormats = FieldLoader.GetValue<string[]>("VideoFormats", entry.Value);
}

public void LoadCustomData(ObjectCreator oc)
Expand Down
6 changes: 3 additions & 3 deletions OpenRA.Game/MiniYaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public MiniYaml(string value, List<MiniYamlNode> nodes)
public static List<MiniYamlNode> NodesOrEmpty(MiniYaml y, string s)
{
var nd = y.ToDictionary();
return nd.ContainsKey(s) ? nd[s].Nodes : new List<MiniYamlNode>();
return nd.TryGetValue(s, out var v) ? v.Nodes : new List<MiniYamlNode>();
}

static List<MiniYamlNode> FromLines(IEnumerable<ReadOnlyMemory<char>> lines, string filename, bool discardCommentsAndWhitespace, Dictionary<string, string> stringPool)
Expand Down Expand Up @@ -368,8 +368,8 @@ static List<MiniYamlNode> ResolveInherits(MiniYaml node, Dictionary<string, Mini
throw new YamlException(
$"{n.Location}: Parent type `{n.Value.Value}` not found");

if (inherited.ContainsKey(n.Value.Value))
throw new YamlException($"{n.Location}: Parent type `{n.Value.Value}` was already inherited by this yaml tree at {inherited[n.Value.Value]} (note: may be from a derived tree)");
if (inherited.TryGetValue(n.Value.Value, out var location))
throw new YamlException($"{n.Location}: Parent type `{n.Value.Value}` was already inherited by this yaml tree at {location} (note: may be from a derived tree)");

inherited.Add(n.Value.Value, n.Location);
foreach (var r in ResolveInherits(parent, tree, inherited))
Expand Down
12 changes: 6 additions & 6 deletions OpenRA.Game/Sound/Sound.cs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ public float VideoVolume
public float VideoSeekPosition => video?.SeekPosition ?? 0;

// Returns true if played successfully
public bool PlayPredefined(SoundType soundType, Ruleset ruleset, Player p, Actor voicedActor, string type, string definition, string variant,
public bool PlayPredefined(SoundType soundType, Ruleset ruleset, Player player, Actor voicedActor, string type, string definition, string variant,
bool relative, WPos pos, float volumeModifier, bool attenuateVolume)
{
if (ruleset == null)
Expand Down Expand Up @@ -399,16 +399,16 @@ public float VideoVolume

if (variant != null)
{
if (rules.Variants.ContainsKey(variant) && !rules.DisableVariants.Contains(definition))
suffix = rules.Variants[variant][id % rules.Variants[variant].Length];
if (rules.Prefixes.ContainsKey(variant) && !rules.DisablePrefixes.Contains(definition))
prefix = rules.Prefixes[variant][id % rules.Prefixes[variant].Length];
if (rules.Variants.TryGetValue(variant, out var v) && !rules.DisableVariants.Contains(definition))
suffix = v[id % v.Length];
if (rules.Prefixes.TryGetValue(variant, out var p) && !rules.DisablePrefixes.Contains(definition))
prefix = p[id % p.Length];
}

var name = prefix + clip + suffix;
var actorId = voicedActor != null && voicedActor.World.Selection.Contains(voicedActor) ? 0 : id;

if (!string.IsNullOrEmpty(name) && (p == null || p == p.World.LocalPlayer))
if (!string.IsNullOrEmpty(name) && (player == null || player == player.World.LocalPlayer))
{
ISound PlaySound()
{
Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Game/Sync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ internal static int Hash(ISync sync)

static void EmitSyncOpcodes(Type type, ILGenerator il)
{
if (CustomHashFunctions.ContainsKey(type))
il.EmitCall(OpCodes.Call, CustomHashFunctions[type], null);
if (CustomHashFunctions.TryGetValue(type, out var hashFunction))
il.EmitCall(OpCodes.Call, hashFunction, null);
else if (type == typeof(bool))
{
var l = il.DefineLabel();
Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Game/Widgets/Widget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,8 @@ public virtual void Initialize(WidgetArgs args)
? new Rectangle(0, 0, Game.Renderer.Resolution.Width, Game.Renderer.Resolution.Height)
: Parent.Bounds;

var substitutions = args.ContainsKey("substitutions") ?
new Dictionary<string, int>((Dictionary<string, int>)args["substitutions"]) :
var substitutions = args.TryGetValue("substitutions", out var subs) ?
new Dictionary<string, int>((Dictionary<string, int>)subs) :
new Dictionary<string, int>();

substitutions.Add("WINDOW_RIGHT", Game.Renderer.Resolution.Width);
Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Mods.Cnc/UtilityCommands/ImportGen2MapCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -370,11 +370,11 @@ protected virtual void ReadLamps(Map map, IniFile file)
var visibility = FieldLoader.GetValue<int>(kv.Key, kv.Value);
lightingNodes.Add(new MiniYamlNode("Range", FieldSaver.FormatValue(new WDist(visibility * 4))));
}
else if (lightingTypes.ContainsKey(kv.Key))
else if (lightingTypes.TryGetValue(kv.Key, out var lightingType))
{
// Some maps use "," instead of "."!
var value = FieldLoader.GetValue<float>(kv.Key, kv.Value.Replace(',', '.'));
lightingNodes.Add(new MiniYamlNode(lightingTypes[kv.Key], FieldSaver.FormatValue(value)));
lightingNodes.Add(new MiniYamlNode(lightingType, FieldSaver.FormatValue(value)));
}
}

Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Mods.Common/LoadScreens/LogoStripeLoadScreen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ public override void Init(ModData modData, Dictionary<string, string> info)
{
base.Init(modData, info);

if (info.ContainsKey("Text"))
messages = info["Text"].Split(',');
if (info.TryGetValue("Text", out var text))
messages = text.Split(',');
}

public override void DisplayInner(Renderer r, Sheet s, int density)
Expand Down
13 changes: 6 additions & 7 deletions OpenRA.Mods.Common/LoadScreens/SheetLoadScreen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,22 +56,21 @@ public override void Display()
sheet = null;
}

if (sheet == null && Info.ContainsKey("Image"))
if (sheet == null && Info.TryGetValue("Image", out var image))
{
var key = "Image";
density = 1;
if (dpiScale > 2 && Info.ContainsKey("Image3x"))
if (dpiScale > 2 && Info.TryGetValue("Image3x", out var image3))
{
key = "Image3x";
image = image3;
density = 3;
}
else if (dpiScale > 1 && Info.ContainsKey("Image2x"))
else if (dpiScale > 1 && Info.TryGetValue("Image2x", out var image2))
{
key = "Image2x";
image = image2;
density = 2;
}

using (var stream = ModData.DefaultFileSystem.Open(Platform.ResolvePath(Info[key])))
using (var stream = ModData.DefaultFileSystem.Open(Platform.ResolvePath(image)))
{
sheet = new Sheet(SheetType.BGRA, stream);
sheet.GetTexture().ScaleFilter = TextureScaleFilter.Linear;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,8 @@ void GlobalProductionHandler(Actor factory, Actor unit)

var queue = GetBuildableInfo(unit.Info.Name).Queue.First();

if (productionHandlers.ContainsKey(queue))
productionHandlers[queue](factory, unit);
if (productionHandlers.TryGetValue(queue, out var productionHandler))
productionHandler(factory, unit);
}

var triggers = TriggerGlobal.GetScriptTriggers(player.PlayerActor);
Expand Down
16 changes: 8 additions & 8 deletions OpenRA.Mods.Common/SpriteLoaders/PngSheetLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,29 +115,29 @@ static void RegionsFromSlices(Png png, out List<Rectangle> regions, out List<flo
var frameSize = new Size(png.Width, png.Height);
var frameAmount = 1;

if (png.EmbeddedData.ContainsKey("FrameSize"))
if (png.EmbeddedData.TryGetValue("FrameSize", out var value))
{
// If FrameSize exist, use it and...
frameSize = FieldLoader.GetValue<Size>("FrameSize", png.EmbeddedData["FrameSize"]);
frameSize = FieldLoader.GetValue<Size>("FrameSize", value);

// ... either use FrameAmount or calculate how many times FrameSize fits into the image.
if (png.EmbeddedData.ContainsKey("FrameAmount"))
frameAmount = FieldLoader.GetValue<int>("FrameAmount", png.EmbeddedData["FrameAmount"]);
if (png.EmbeddedData.TryGetValue("FrameAmount", out value))
frameAmount = FieldLoader.GetValue<int>("FrameAmount", value);
else
frameAmount = png.Width / frameSize.Width * (png.Height / frameSize.Height);
}
else if (png.EmbeddedData.ContainsKey("FrameAmount"))
else if (png.EmbeddedData.TryGetValue("FrameAmount", out value))
{
// Otherwise, calculate the number of frames by splitting the image horizontally by FrameAmount.
frameAmount = FieldLoader.GetValue<int>("FrameAmount", png.EmbeddedData["FrameAmount"]);
frameAmount = FieldLoader.GetValue<int>("FrameAmount", value);
frameSize = new Size(png.Width / frameAmount, png.Height);
}

float2 offset;

// If Offset property exists, use its value. Otherwise assume the frame is centered.
if (png.EmbeddedData.ContainsKey("Offset"))
offset = FieldLoader.GetValue<float2>("Offset", png.EmbeddedData["Offset"]);
if (png.EmbeddedData.TryGetValue("Offset", out value))
offset = FieldLoader.GetValue<float2>("Offset", value);
else
offset = float2.Zero;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,8 +322,8 @@ ActorInfo ChooseBuildingToBuild(ProductionQueue queue)

// Does this building have initial delay, if so have we passed it?
if (baseBuilder.Info.BuildingDelays != null &&
baseBuilder.Info.BuildingDelays.ContainsKey(name) &&
baseBuilder.Info.BuildingDelays[name] > world.WorldTick)
baseBuilder.Info.BuildingDelays.TryGetValue(name, out var delay) &&
delay > world.WorldTick)
continue;

// Can we build this structure?
Expand All @@ -341,7 +341,7 @@ ActorInfo ChooseBuildingToBuild(ProductionQueue queue)
if (count * 100 > frac.Value * playerBuildings.Length)
continue;

if (baseBuilder.Info.BuildingLimits.ContainsKey(name) && baseBuilder.Info.BuildingLimits[name] <= count)
if (baseBuilder.Info.BuildingLimits.TryGetValue(name, out var limit) && limit <= count)
continue;

// If we're considering to build a naval structure, check whether there is enough water inside the base perimeter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,8 @@ void IBotTick.BotTick(IBot bot)

// If we have recently tried and failed to find a use location for a power, then do not try again until later
var isDelayed = waitingPowers[sp] > 0;
if (sp.Ready && !isDelayed && powerDecisions.ContainsKey(sp.Info.OrderName))
if (sp.Ready && !isDelayed && powerDecisions.TryGetValue(sp.Info.OrderName, out var powerDecision))
{
var powerDecision = powerDecisions[sp.Info.OrderName];
if (powerDecision == null)
{
AIUtils.BotDebug("{0} couldn't find powerDecision for {1}", player.PlayerName, sp.Info.OrderName);
Expand Down
8 changes: 4 additions & 4 deletions OpenRA.Mods.Common/Traits/BotModules/UnitBuilderBotModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,13 @@ void BuildUnit(IBot bot, string category, bool buildRandom)
return;

if (Info.UnitDelays != null &&
Info.UnitDelays.ContainsKey(name) &&
Info.UnitDelays[name] > world.WorldTick)
Info.UnitDelays.TryGetValue(name, out var delay) &&
delay > world.WorldTick)
return;

if (Info.UnitLimits != null &&
Info.UnitLimits.ContainsKey(name) &&
world.Actors.Count(a => a.Owner == player && a.Info.Name == name) >= Info.UnitLimits[name])
Info.UnitLimits.TryGetValue(name, out var limit) &&
world.Actors.Count(a => a.Owner == player && a.Info.Name == name) >= limit)
return;

bot.QueueOrder(Order.StartProduction(queue.Actor, name, 1));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ void ITick.Tick(Actor self)
public void ResolveOrder(Actor self, Order order)
{
// order.OrderString is the key of the support power
if (Powers.ContainsKey(order.OrderString))
Powers[order.OrderString].Activate(order);
if (Powers.TryGetValue(order.OrderString, out var sp))
sp.Activate(order);
}

static readonly SupportPowerInstance[] NoInstances = Array.Empty<SupportPowerInstance>();
Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Mods.Common/Traits/World/Locomotor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ protected static object LoadSpeeds(MiniYaml y)
if (speed > 0)
{
var nodesDict = t.Value.ToDictionary();
var cost = nodesDict.ContainsKey("PathingCost")
? FieldLoader.GetValue<short>("cost", nodesDict["PathingCost"].Value)
var cost = nodesDict.TryGetValue("PathingCost", out var entry)
? FieldLoader.GetValue<short>("cost", entry.Value)
: 10000 / speed;
ret.Add(t.Key, new TerrainInfo(speed, (short)cost));
}
Expand Down
Loading

0 comments on commit 231bf01

Please sign in to comment.