Skip to content

Commit d714ae5

Browse files
5 algorithmic optimizations (#3036)
Co-authored-by: codefactor-io <support@codefactor.io>
1 parent d6c04f9 commit d714ae5

5 files changed

Lines changed: 68 additions & 36 deletions

File tree

ImperatorToCK3/CK3/ParserExtensions.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,16 +101,13 @@ public static void ParseLiquidFile(this Parser parser, string filePath, Hash liq
101101
}
102102

103103
public static void ParseFolderWithLiquidSupport(this Parser parser, string path, string extensions, bool recursive, Hash liquidVariables, bool logFilePaths = false) {
104-
var searchPattern = recursive ? "*" : "*.*";
105104
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
106-
var files = Directory.GetFiles(path, searchPattern, searchOption);
107-
108105
var validExtensions = new HashSet<string>(
109106
extensions.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
110107
StringComparer.OrdinalIgnoreCase
111108
);
112109

113-
foreach (var file in files) {
110+
foreach (var file in Directory.EnumerateFiles(path, "*", searchOption)) {
114111
var extension = CommonFunctions.GetExtension(file);
115112
if (!validExtensions.Contains(extension)) {
116113
continue;

ImperatorToCK3/CK3/World.cs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -753,10 +753,9 @@ private bool TryGiveCountyToGovernor(Title county,
753753
}
754754

755755
var parentRegionName = imperatorRegionMapper.GetParentRegionName(irProvince.Id);
756-
var matchingGovernorships = governorshipsSet
757-
.Where(g => g.Country.Id == irCountry.Id && g.Region.Id == parentRegionName)
758-
.ToArray();
759-
if (matchingGovernorships.Length == 0) {
756+
var governorship = governorshipsSet
757+
.FirstOrDefault(g => g.Country.Id == irCountry.Id && g.Region.Id == parentRegionName);
758+
if (governorship is null) {
760759
// We have no matching governorship.
761760
return false;
762761
}
@@ -766,7 +765,6 @@ private bool TryGiveCountyToGovernor(Title county,
766765
}
767766

768767
// give county to governor
769-
var governorship = matchingGovernorships[0];
770768
var ck3GovernorshipId = tagTitleMapper.GetTitleForGovernorship(governorship, LandedTitles, irProvinces, Provinces, imperatorRegionMapper, provinceMapper);
771769
if (ck3GovernorshipId is null) {
772770
Logger.Warn($"{nameof(ck3GovernorshipId)} is null for {ck3Country} {governorship.Region.Id}!");
@@ -825,11 +823,12 @@ private bool TryGiveCountyToCountyLevelRuler(Title county,
825823
Country irCountry,
826824
List<KeyValuePair<Country, Dependency?>> countyLevelCountries,
827825
CountryCollection irCountries) {
828-
var matchingCountyLevelRulers = countyLevelCountries.Where(c => c.Key.Id == irCountry.Id).ToArray();
829-
if (matchingCountyLevelRulers.Length == 0) {
826+
var matchingCountyLevelRuler = countyLevelCountries
827+
.FirstOrDefault(c => c.Key.Id == irCountry.Id);
828+
if (matchingCountyLevelRuler.Key is null) {
830829
return false;
831830
}
832-
var dependency = matchingCountyLevelRulers[0].Value;
831+
var dependency = matchingCountyLevelRuler.Value;
833832

834833
// Give county to ruler.
835834
var ck3Ruler = irCountry.Monarch?.CK3Character;

ImperatorToCK3/CommonUtils/EnumerableExtensions.cs

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,27 @@
55
namespace ImperatorToCK3.CommonUtils;
66

77
public static class EnumerableExtensions {
8-
public static T? LastOrNull<T>(this IEnumerable<T> source, Func<T,bool> predicate) where T : struct {
9-
var enumerable = source as T[] ?? [.. source];
8+
public static T? LastOrNull<T>(this IEnumerable<T> source, Func<T, bool> predicate) where T : struct {
9+
ArgumentNullException.ThrowIfNull(source);
10+
ArgumentNullException.ThrowIfNull(predicate);
1011

11-
if (enumerable.Length == 0) {
12-
return null;
13-
}
14-
15-
foreach (var element in Enumerable.Reverse(enumerable)) {
12+
T? last = null;
13+
foreach (var element in source) {
1614
if (predicate(element)) {
17-
return element;
15+
last = element;
1816
}
1917
}
20-
21-
return null;
18+
return last;
2219
}
20+
2321
public static KeyValuePair<TKey, TValue>? LastOrNull<TKey, TValue>(
2422
this IEnumerable<KeyValuePair<TKey, TValue>> source) {
25-
var keyValuePairs = source as KeyValuePair<TKey, TValue>[] ?? source.ToArray();
26-
return keyValuePairs.Length != 0
27-
? keyValuePairs[^1] : null;
23+
ArgumentNullException.ThrowIfNull(source);
24+
25+
KeyValuePair<TKey, TValue>? last = null;
26+
foreach (var kvp in source) {
27+
last = kvp;
28+
}
29+
return last;
2830
}
2931
}

ImperatorToCK3/CommonUtils/Map/ProvinceDefinitions.cs

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@
99
namespace ImperatorToCK3.CommonUtils.Map;
1010

1111
internal sealed class ProvinceDefinitions : IdObjectCollection<ulong, ProvinceDefinition> {
12-
public Dictionary<Rgb24, ulong> ColorToProvinceDict { get; } = [];
13-
public Dictionary<ulong, Rgb24> ProvinceToColorDict { get; } = [];
12+
internal Dictionary<Rgb24, ulong> ColorToProvinceDict { get; } = [];
13+
internal Dictionary<ulong, Rgb24> ProvinceToColorDict { get; } = [];
1414

15-
public void LoadDefinitions(string definitionsFilename, ModFilesystem modFS) {
15+
internal void LoadDefinitions(string definitionsFilename, ModFilesystem modFS) {
1616
var relativePath = Path.Combine("map_data", definitionsFilename);
17-
var definitionsFilePath = modFS.GetActualFileLocation(relativePath);
17+
string? definitionsFilePath = modFS.GetActualFileLocation(relativePath);
1818
if (definitionsFilePath is null) {
1919
Logger.Warn($"Province definitions file {definitionsFilename} not found!");
2020
return;
@@ -36,14 +36,46 @@ public void LoadDefinitions(string definitionsFilename, ModFilesystem modFS) {
3636
}
3737

3838
try {
39-
var columns = line.Split(';');
39+
var span = line.AsSpan();
40+
int pos = 0;
4041

41-
var id = ulong.Parse(columns[0]);
42+
// id
43+
var idEnd = span.IndexOf(';');
44+
if (idEnd < 0) throw new FormatException("Missing separators");
45+
var idSpan = span[pos..idEnd];
46+
pos = idEnd + 1;
47+
if (!ulong.TryParse(idSpan, out var id)) {
48+
throw new FormatException($"Invalid id: {idSpan}");
49+
}
4250
AddOrReplace(new ProvinceDefinition(id));
4351

44-
var r = byte.Parse(columns[1]);
45-
var g = byte.Parse(columns[2]);
46-
var b = byte.Parse(columns[3]);
52+
// r
53+
var rEnd = span[pos..].IndexOf(';');
54+
if (rEnd < 0) throw new FormatException("Missing separators");
55+
var rSpan = span[pos..(pos + rEnd)];
56+
pos += rEnd + 1;
57+
if (!byte.TryParse(rSpan, out var r)) {
58+
throw new FormatException($"Invalid r: {rSpan}");
59+
}
60+
61+
// g
62+
var gEnd = span[pos..].IndexOf(';');
63+
if (gEnd < 0) throw new FormatException("Missing separators");
64+
var gSpan = span[pos..(pos + gEnd)];
65+
pos += gEnd + 1;
66+
if (!byte.TryParse(gSpan, out var g)) {
67+
throw new FormatException($"Invalid g: {gSpan}");
68+
}
69+
70+
// b
71+
var bEnd = span[pos..].IndexOf(';');
72+
if (bEnd < 0) throw new FormatException("Missing separators");
73+
var bSpan = span[pos..(pos + bEnd)];
74+
pos += bEnd + 1;
75+
if (!byte.TryParse(bSpan, out var b)) {
76+
throw new FormatException($"Invalid b: {bSpan}");
77+
}
78+
4779
var color = new Rgb24(r, g, b);
4880
ProvinceToColorDict.Add(id, color);
4981
ColorToProvinceDict[color] = id;

ImperatorToCK3/Configuration.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,8 @@ internal OrderedDictionary<string, bool> GetCK3ModFlags() {
461461
flags[definition.Flag] = activeCK3ModFlags.Contains(definition.Flag);
462462
}
463463

464-
flags["vanilla_ck3"] = !flags.Any(f => f.Value);
464+
// If no CK3 mod flags are set, treat it as vanilla CK3.
465+
flags["vanilla_ck3"] = activeCK3ModFlags.Count == 0;
465466
return flags;
466467
}
467468

@@ -479,7 +480,8 @@ internal OrderedDictionary<string, bool> GetImperatorModFlags() {
479480
flags[definition.Flag] = activeImperatorModFlags.Contains(definition.Flag);
480481
}
481482

482-
flags["vanilla_ir"] = !flags.Any(f => f.Value);
483+
// If no Imperator mod flags are set, treat it as vanilla Imperator.
484+
flags["vanilla_ir"] = activeImperatorModFlags.Count == 0;
483485
return flags;
484486
}
485487

0 commit comments

Comments
 (0)