Started lint work

This commit is contained in:
Daniel Cronqvist 2024-08-22 00:15:13 +02:00
parent 7d6ee330a5
commit bb8c3a133c
39 changed files with 83 additions and 143 deletions

View file

@ -40,17 +40,17 @@ dotnet_style_require_accessibility_modifiers = for_non_interface_members
# Expression-level preferences # Expression-level preferences
dotnet_style_coalesce_expression = true dotnet_style_coalesce_expression = true
dotnet_style_collection_initializer = true dotnet_style_collection_initializer = false
dotnet_style_explicit_tuple_names = true dotnet_style_explicit_tuple_names = true
dotnet_style_namespace_match_folder = true dotnet_style_namespace_match_folder = true
dotnet_style_null_propagation = true dotnet_style_null_propagation = true
dotnet_style_object_initializer = true dotnet_style_object_initializer = true
dotnet_style_operator_placement_when_wrapping = beginning_of_line dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true dotnet_style_prefer_auto_properties = true
dotnet_style_prefer_collection_expression = when_types_loosely_match dotnet_style_prefer_collection_expression = false
dotnet_style_prefer_compound_assignment = true dotnet_style_prefer_compound_assignment = true
dotnet_style_prefer_conditional_expression_over_assignment = true dotnet_style_prefer_conditional_expression_over_assignment = false
dotnet_style_prefer_conditional_expression_over_return = true dotnet_style_prefer_conditional_expression_over_return = false
dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed
dotnet_style_prefer_inferred_anonymous_type_member_names = true dotnet_style_prefer_inferred_anonymous_type_member_names = true
dotnet_style_prefer_inferred_tuple_names = true dotnet_style_prefer_inferred_tuple_names = true
@ -84,7 +84,7 @@ csharp_style_expression_bodied_constructors = false
csharp_style_expression_bodied_indexers = true csharp_style_expression_bodied_indexers = true
csharp_style_expression_bodied_lambdas = true csharp_style_expression_bodied_lambdas = true
csharp_style_expression_bodied_local_functions = false csharp_style_expression_bodied_local_functions = false
csharp_style_expression_bodied_methods = false csharp_style_expression_bodied_methods = when_on_single_line
csharp_style_expression_bodied_operators = false csharp_style_expression_bodied_operators = false
csharp_style_expression_bodied_properties = true csharp_style_expression_bodied_properties = true
@ -106,11 +106,11 @@ csharp_style_prefer_readonly_struct = true
csharp_style_prefer_readonly_struct_member = true csharp_style_prefer_readonly_struct_member = true
# Code-block preferences # Code-block preferences
csharp_prefer_braces = true csharp_prefer_braces = when_multiline
csharp_prefer_simple_using_statement = true csharp_prefer_simple_using_statement = true
csharp_style_namespace_declarations = block_scoped csharp_style_namespace_declarations = block_scoped
csharp_style_prefer_method_group_conversion = true csharp_style_prefer_method_group_conversion = true
csharp_style_prefer_primary_constructors = true csharp_style_prefer_primary_constructors = false
csharp_style_prefer_top_level_statements = true csharp_style_prefer_top_level_statements = true
# Expression-level preferences # Expression-level preferences
@ -145,7 +145,7 @@ csharp_new_line_before_catch = true
csharp_new_line_before_else = true csharp_new_line_before_else = true
csharp_new_line_before_finally = true csharp_new_line_before_finally = true
csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_members_in_object_initializers = false
csharp_new_line_before_open_brace = all csharp_new_line_before_open_brace = all
csharp_new_line_between_query_expression_clauses = true csharp_new_line_between_query_expression_clauses = true
@ -227,7 +227,14 @@ dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator = dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case dotnet_naming_style.begins_with_i.capitalization = pascal_case
# Diagnostics
dotnet_analyzer_diagnostic.severity = warning
dotnet_diagnostic.IDE0001.severity = none
dotnet_diagnostic.IDE0004.severity = silent
dotnet_diagnostic.IDE0005.severity = error dotnet_diagnostic.IDE0005.severity = error
dotnet_diagnostic.IDE0008.severity = silent
dotnet_diagnostic.IDE0160.severity = none
[.github/**/*.yml] [.github/**/*.yml]
charset = utf-8 charset = utf-8

View file

@ -1,17 +1,13 @@
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Xml; using System.Xml;
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Columns; using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs; using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Order; using BenchmarkDotNet.Order;
using BenchmarkDotNet.Reports;
using BenchmarkDotNet.Running; using BenchmarkDotNet.Running;
namespace MyBenchmarks namespace DotTiled.Benchmark
{ {
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[CategoriesColumn] [CategoriesColumn]
@ -19,11 +15,11 @@ namespace MyBenchmarks
[HideColumns(["StdDev", "Error", "RatioSD"])] [HideColumns(["StdDev", "Error", "RatioSD"])]
public class MapLoading public class MapLoading
{ {
private string _tmxPath = @"DotTiled.Tests/Serialization/TestData/Map/default-map/default-map.tmx"; private readonly string _tmxPath = @"DotTiled.Tests/Serialization/TestData/Map/default-map/default-map.tmx";
private string _tmxContents = ""; private readonly string _tmxContents = "";
private string _tmjPath = @"DotTiled.Tests/Serialization/TestData/Map/default-map/default-map.tmj"; private readonly string _tmjPath = @"DotTiled.Tests/Serialization/TestData/Map/default-map/default-map.tmj";
private string _tmjContents = ""; private readonly string _tmjContents = "";
public MapLoading() public MapLoading()
{ {
@ -31,11 +27,11 @@ namespace MyBenchmarks
var tmxPath = Path.Combine(basePath, $"../{_tmxPath}"); var tmxPath = Path.Combine(basePath, $"../{_tmxPath}");
var tmjPath = Path.Combine(basePath, $"../{_tmjPath}"); var tmjPath = Path.Combine(basePath, $"../{_tmjPath}");
_tmxContents = System.IO.File.ReadAllText(tmxPath); _tmxContents = File.ReadAllText(tmxPath);
_tmjContents = System.IO.File.ReadAllText(tmjPath); _tmjContents = File.ReadAllText(tmjPath);
} }
static string WhereAmI([CallerFilePath] string callerFilePath = "") => callerFilePath; private static string WhereAmI([CallerFilePath] string callerFilePath = "") => callerFilePath;
[BenchmarkCategory("MapFromInMemoryTmxString")] [BenchmarkCategory("MapFromInMemoryTmxString")]
[Benchmark(Baseline = true, Description = "DotTiled")] [Benchmark(Baseline = true, Description = "DotTiled")]
@ -43,7 +39,7 @@ namespace MyBenchmarks
{ {
using var stringReader = new StringReader(_tmxContents); using var stringReader = new StringReader(_tmxContents);
using var xmlReader = XmlReader.Create(stringReader); using var xmlReader = XmlReader.Create(stringReader);
using var mapReader = new DotTiled.Serialization.Tmx.TmxMapReader(xmlReader, _ => throw new Exception(), _ => throw new Exception(), []); using var mapReader = new DotTiled.Serialization.Tmx.TmxMapReader(xmlReader, _ => throw new NotSupportedException(), _ => throw new NotSupportedException(), []);
return mapReader.ReadMap(); return mapReader.ReadMap();
} }
@ -51,7 +47,7 @@ namespace MyBenchmarks
[Benchmark(Baseline = true, Description = "DotTiled")] [Benchmark(Baseline = true, Description = "DotTiled")]
public DotTiled.Model.Map LoadWithDotTiledFromInMemoryTmjString() public DotTiled.Model.Map LoadWithDotTiledFromInMemoryTmjString()
{ {
using var mapReader = new DotTiled.Serialization.Tmj.TmjMapReader(_tmjContents, _ => throw new Exception(), _ => throw new Exception(), []); using var mapReader = new DotTiled.Serialization.Tmj.TmjMapReader(_tmjContents, _ => throw new NotSupportedException(), _ => throw new NotSupportedException(), []);
return mapReader.ReadMap(); return mapReader.ReadMap();
} }
@ -84,11 +80,11 @@ namespace MyBenchmarks
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
var config = BenchmarkDotNet.Configs.DefaultConfig.Instance var config = DefaultConfig.Instance
.WithArtifactsPath(args[0]) .WithArtifactsPath(args[0])
.WithOptions(ConfigOptions.DisableOptimizationsValidator) .WithOptions(ConfigOptions.DisableOptimizationsValidator)
.AddDiagnoser(BenchmarkDotNet.Diagnosers.MemoryDiagnoser.Default); .AddDiagnoser(BenchmarkDotNet.Diagnosers.MemoryDiagnoser.Default);
var summary = BenchmarkRunner.Run<MapLoading>(config); _ = BenchmarkRunner.Run<MapLoading>(config);
} }
} }
} }

View file

@ -1,5 +1,4 @@
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,6 +1,5 @@
using System.Xml; using System.Xml;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,5 +1,4 @@
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,8 +1,5 @@
using System.Globalization; using System.Globalization;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,7 +1,5 @@
using System.Globalization; using System.Globalization;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,7 +1,5 @@
using System.Globalization; using System.Globalization;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,8 +1,5 @@
using System.Globalization; using System.Globalization;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,7 +1,5 @@
using System.Globalization; using System.Globalization;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,7 +1,5 @@
using System.Globalization; using System.Globalization;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,7 +1,5 @@
using System.Globalization; using System.Globalization;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,9 +1,5 @@
using System.Numerics; using System.Numerics;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,6 +1,4 @@
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Serialization.Tmj; using DotTiled.Serialization.Tmj;
namespace DotTiled.Tests; namespace DotTiled.Tests;

View file

@ -1,6 +1,3 @@
using System.Xml;
using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Serialization.Tmx; using DotTiled.Serialization.Tmx;

View file

@ -1,7 +1,6 @@
using System; using System;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Threading;
namespace DotTiled.Model; namespace DotTiled.Model;
@ -40,7 +39,7 @@ public class Color : IParsable<Color>, IEquatable<Color>
/// <exception cref="FormatException">Thrown in case the provided string <paramref name="s"/> is not in a valid format.</exception> /// <exception cref="FormatException">Thrown in case the provided string <paramref name="s"/> is not in a valid format.</exception>
public static Color Parse(string s, IFormatProvider? provider) public static Color Parse(string s, IFormatProvider? provider)
{ {
TryParse(s, provider, out var result); _ = TryParse(s, provider, out var result);
return result ?? throw new FormatException($"Invalid format for TiledColor: {s}"); return result ?? throw new FormatException($"Invalid format for TiledColor: {s}");
} }
@ -61,7 +60,7 @@ public class Color : IParsable<Color>, IEquatable<Color>
return TryParse($"#{s}", provider, out result); return TryParse($"#{s}", provider, out result);
// Format: #RRGGBB or #AARRGGBB // Format: #RRGGBB or #AARRGGBB
if (s is null || s.Length != 7 && s.Length != 9 || s[0] != '#') if (s is null || (s.Length != 7 && s.Length != 9) || s[0] != '#')
{ {
result = default; result = default;
return false; return false;

View file

@ -4,8 +4,6 @@ using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq; using System.Linq;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Serialization; namespace DotTiled.Serialization;

View file

@ -9,10 +9,9 @@ internal static class ExtensionsJsonElement
{ {
internal static T GetRequiredProperty<T>(this JsonElement element, string propertyName) internal static T GetRequiredProperty<T>(this JsonElement element, string propertyName)
{ {
if (!element.TryGetProperty(propertyName, out var property)) return !element.TryGetProperty(propertyName, out var property)
throw new JsonException($"Missing required property '{propertyName}'."); ? throw new JsonException($"Missing required property '{propertyName}'.")
: property.GetValueAs<T>();
return property.GetValueAs<T>();
} }
internal static T GetOptionalProperty<T>(this JsonElement element, string propertyName, T defaultValue) internal static T GetOptionalProperty<T>(this JsonElement element, string propertyName, T defaultValue)

View file

@ -1,9 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO; using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;
@ -69,7 +65,8 @@ internal partial class Tmj
{ {
DataCompression.GZip => Helpers.DecompressGZip(stream), DataCompression.GZip => Helpers.DecompressGZip(stream),
DataCompression.ZLib => Helpers.DecompressZLib(stream), DataCompression.ZLib => Helpers.DecompressZLib(stream),
_ => throw new JsonException($"Unsupported compression '{compression}'.") DataCompression.ZStd => throw new NotSupportedException("ZStd compression is not supported."),
_ => throw new InvalidOperationException($"Unsupported compression '{compression}'.")
}; };
{ {

View file

@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Numerics;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;

View file

@ -1,10 +1,7 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Numerics;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;
using DotTiled.Model;
namespace DotTiled.Serialization.Tmj; namespace DotTiled.Serialization.Tmj;

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;

View file

@ -1,8 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;

View file

@ -112,8 +112,8 @@ internal partial class Tmj
var id = element.GetOptionalProperty<uint?>("id", idDefault); var id = element.GetOptionalProperty<uint?>("id", idDefault);
var name = element.GetOptionalProperty<string>("name", nameDefault); var name = element.GetOptionalProperty<string>("name", nameDefault);
var point = element.GetOptionalProperty<bool>("point", pointDefault); var point = element.GetOptionalProperty<bool>("point", pointDefault);
var polygon = element.GetOptionalPropertyCustom<List<Vector2>?>("polygon", e => ReadPoints(e), polygonDefault); var polygon = element.GetOptionalPropertyCustom<List<Vector2>?>("polygon", ReadPoints, polygonDefault);
var polyline = element.GetOptionalPropertyCustom<List<Vector2>?>("polyline", e => ReadPoints(e), polylineDefault); var polyline = element.GetOptionalPropertyCustom<List<Vector2>?>("polyline", ReadPoints, polylineDefault);
var properties = element.GetOptionalPropertyCustom<Dictionary<string, IProperty>?>("properties", e => ReadProperties(e, customTypeDefinitions), propertiesDefault); var properties = element.GetOptionalPropertyCustom<Dictionary<string, IProperty>?>("properties", e => ReadProperties(e, customTypeDefinitions), propertiesDefault);
var rotation = element.GetOptionalProperty<float>("rotation", rotationDefault); var rotation = element.GetOptionalProperty<float>("rotation", rotationDefault);
var text = element.GetOptionalPropertyCustom<TextObject?>("text", ReadText, null); var text = element.GetOptionalPropertyCustom<TextObject?>("text", ReadText, null);
@ -249,12 +249,12 @@ internal partial class Tmj
} }
internal static List<Vector2> ReadPoints(JsonElement element) => internal static List<Vector2> ReadPoints(JsonElement element) =>
element.GetValueAsList<Vector2>(e => element.GetValueAsList<Vector2>(e =>
{ {
var x = e.GetRequiredProperty<float>("x"); var x = e.GetRequiredProperty<float>("x");
var y = e.GetRequiredProperty<float>("y"); var y = e.GetRequiredProperty<float>("y");
return new Vector2(x, y); return new Vector2(x, y);
}); });
internal static TextObject ReadText(JsonElement element) internal static TextObject ReadText(JsonElement element)
{ {

View file

@ -1,6 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO;
using System.Linq; using System.Linq;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;
@ -102,8 +101,6 @@ internal partial class Tmj
return resultingProps; return resultingProps;
} }
internal static Dictionary<string, IProperty> CreateInstanceOfCustomClass(CustomClassDefinition customClassDefinition) internal static Dictionary<string, IProperty> CreateInstanceOfCustomClass(CustomClassDefinition customClassDefinition) =>
{ customClassDefinition.Members.ToDictionary(m => m.Name, m => m.Clone());
return customClassDefinition.Members.ToDictionary(m => m.Name, m => m.Clone());
}
} }

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;

View file

@ -1,7 +1,5 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Numerics;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;

View file

@ -1,9 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;

View file

@ -1,7 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json; using System.Text.Json;
using DotTiled.Model; using DotTiled.Model;
@ -16,7 +14,7 @@ public class TmjMapReader : IMapReader
private readonly Func<string, Tileset> _externalTilesetResolver; private readonly Func<string, Tileset> _externalTilesetResolver;
private readonly Func<string, Template> _externalTemplateResolver; private readonly Func<string, Template> _externalTemplateResolver;
private string _jsonString; private readonly string _jsonString;
private bool disposedValue; private bool disposedValue;
private readonly IReadOnlyCollection<CustomTypeDefinition> _customTypeDefinitions; private readonly IReadOnlyCollection<CustomTypeDefinition> _customTypeDefinitions;
@ -77,6 +75,6 @@ public class TmjMapReader : IMapReader
{ {
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true); Dispose(disposing: true);
System.GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }

View file

@ -74,6 +74,6 @@ public class TsjTilesetReader : ITilesetReader
{ {
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true); Dispose(disposing: true);
System.GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }

View file

@ -31,10 +31,8 @@ internal static class ExtensionsXmlReader
return enumParser(value); return enumParser(value);
} }
internal static string? GetOptionalAttribute(this XmlReader reader, string attribute, string? defaultValue = default) internal static string? GetOptionalAttribute(this XmlReader reader, string attribute, string? defaultValue = default) =>
{ reader.GetAttribute(attribute) ?? defaultValue;
return reader.GetAttribute(attribute) ?? defaultValue;
}
internal static T? GetOptionalAttributeParseable<T>(this XmlReader reader, string attribute) where T : struct, IParsable<T> internal static T? GetOptionalAttributeParseable<T>(this XmlReader reader, string attribute) where T : struct, IParsable<T>
{ {
@ -84,7 +82,7 @@ internal static class ExtensionsXmlReader
if (reader.NodeType == XmlNodeType.EndElement) if (reader.NodeType == XmlNodeType.EndElement)
continue; // At end of list, no need to read again continue; // At end of list, no need to read again
reader.Read(); _ = reader.Read();
} }
reader.ReadEndElement(); reader.ReadEndElement();
@ -135,6 +133,6 @@ internal static class ExtensionsXmlReader
internal static void SkipXmlDeclaration(this XmlReader reader) internal static void SkipXmlDeclaration(this XmlReader reader)
{ {
if (reader.NodeType == XmlNodeType.XmlDeclaration) if (reader.NodeType == XmlNodeType.XmlDeclaration)
reader.Read(); _ = reader.Read();
} }
} }

View file

@ -62,10 +62,8 @@ internal partial class Tmx
return (clearedGlobalTileIDs, flippingFlags); return (clearedGlobalTileIDs, flippingFlags);
} }
internal static uint[] ReadTileChildrenInWrapper(string wrapper, XmlReader reader) internal static uint[] ReadTileChildrenInWrapper(string wrapper, XmlReader reader) =>
{ reader.ReadList(wrapper, "tile", (r) => r.GetOptionalAttributeParseable<uint>("gid") ?? 0).ToArray();
return reader.ReadList(wrapper, "tile", (r) => r.GetOptionalAttributeParseable<uint>("gid") ?? 0).ToArray();
}
internal static uint[] ReadRawData(XmlReader reader, DataEncoding encoding, DataCompression? compression) internal static uint[] ReadRawData(XmlReader reader, DataEncoding encoding, DataCompression? compression)
{ {

View file

@ -25,7 +25,7 @@ internal partial class Tmx
"isometric" => MapOrientation.Isometric, "isometric" => MapOrientation.Isometric,
"staggered" => MapOrientation.Staggered, "staggered" => MapOrientation.Staggered,
"hexagonal" => MapOrientation.Hexagonal, "hexagonal" => MapOrientation.Hexagonal,
_ => throw new Exception($"Unknown orientation '{s}'") _ => throw new InvalidOperationException($"Unknown orientation '{s}'")
}); });
var renderOrder = reader.GetOptionalAttributeEnum<RenderOrder>("renderorder", s => s switch var renderOrder = reader.GetOptionalAttributeEnum<RenderOrder>("renderorder", s => s switch
{ {
@ -33,7 +33,7 @@ internal partial class Tmx
"right-up" => RenderOrder.RightUp, "right-up" => RenderOrder.RightUp,
"left-down" => RenderOrder.LeftDown, "left-down" => RenderOrder.LeftDown,
"left-up" => RenderOrder.LeftUp, "left-up" => RenderOrder.LeftUp,
_ => throw new Exception($"Unknown render order '{s}'") _ => throw new InvalidOperationException($"Unknown render order '{s}'")
}) ?? RenderOrder.RightDown; }) ?? RenderOrder.RightDown;
var compressionLevel = reader.GetOptionalAttributeParseable<int>("compressionlevel") ?? -1; var compressionLevel = reader.GetOptionalAttributeParseable<int>("compressionlevel") ?? -1;
var width = reader.GetRequiredAttributeParseable<uint>("width"); var width = reader.GetRequiredAttributeParseable<uint>("width");
@ -45,13 +45,13 @@ internal partial class Tmx
{ {
"x" => StaggerAxis.X, "x" => StaggerAxis.X,
"y" => StaggerAxis.Y, "y" => StaggerAxis.Y,
_ => throw new Exception($"Unknown stagger axis '{s}'") _ => throw new InvalidOperationException($"Unknown stagger axis '{s}'")
}); });
var staggerIndex = reader.GetOptionalAttributeEnum<StaggerIndex>("staggerindex", s => s switch var staggerIndex = reader.GetOptionalAttributeEnum<StaggerIndex>("staggerindex", s => s switch
{ {
"odd" => StaggerIndex.Odd, "odd" => StaggerIndex.Odd,
"even" => StaggerIndex.Even, "even" => StaggerIndex.Even,
_ => throw new Exception($"Unknown stagger index '{s}'") _ => throw new InvalidOperationException($"Unknown stagger index '{s}'")
}); });
var parallaxOriginX = reader.GetOptionalAttributeParseable<float>("parallaxoriginx") ?? 0.0f; var parallaxOriginX = reader.GetOptionalAttributeParseable<float>("parallaxoriginx") ?? 0.0f;
var parallaxOriginY = reader.GetOptionalAttributeParseable<float>("parallaxoriginy") ?? 0.0f; var parallaxOriginY = reader.GetOptionalAttributeParseable<float>("parallaxoriginy") ?? 0.0f;

View file

@ -35,7 +35,7 @@ internal partial class Tmx
{ {
"topdown" => DrawOrder.TopDown, "topdown" => DrawOrder.TopDown,
"index" => DrawOrder.Index, "index" => DrawOrder.Index,
_ => throw new Exception($"Unknown draw order '{s}'") _ => throw new InvalidOperationException($"Unknown draw order '{s}'")
}) ?? DrawOrder.TopDown; }) ?? DrawOrder.TopDown;
// Elements // Elements
@ -119,7 +119,7 @@ internal partial class Tmx
"polygon" => () => Helpers.SetAtMostOnce(ref foundObject, ReadPolygonObject(r), "Object marker"), "polygon" => () => Helpers.SetAtMostOnce(ref foundObject, ReadPolygonObject(r), "Object marker"),
"polyline" => () => Helpers.SetAtMostOnce(ref foundObject, ReadPolylineObject(r), "Object marker"), "polyline" => () => Helpers.SetAtMostOnce(ref foundObject, ReadPolylineObject(r), "Object marker"),
"text" => () => Helpers.SetAtMostOnce(ref foundObject, ReadTextObject(r), "Object marker"), "text" => () => Helpers.SetAtMostOnce(ref foundObject, ReadTextObject(r), "Object marker"),
_ => throw new Exception($"Unknown object marker '{elementName}'") _ => throw new InvalidOperationException($"Unknown object marker '{elementName}'")
}); });
if (foundObject is null) if (foundObject is null)
@ -175,7 +175,7 @@ internal partial class Tmx
return new EllipseObject { }; return new EllipseObject { };
} }
internal static EllipseObject OverrideObject(EllipseObject obj, EllipseObject foundObject) => obj; internal static EllipseObject OverrideObject(EllipseObject obj, EllipseObject _) => obj;
internal static PointObject ReadPointObject(XmlReader reader) internal static PointObject ReadPointObject(XmlReader reader)
{ {
@ -183,7 +183,7 @@ internal partial class Tmx
return new PointObject { }; return new PointObject { };
} }
internal static PointObject OverrideObject(PointObject obj, PointObject foundObject) => obj; internal static PointObject OverrideObject(PointObject obj, PointObject _) => obj;
internal static PolygonObject ReadPolygonObject(XmlReader reader) internal static PolygonObject ReadPolygonObject(XmlReader reader)
{ {
@ -251,14 +251,14 @@ internal partial class Tmx
"center" => TextHorizontalAlignment.Center, "center" => TextHorizontalAlignment.Center,
"right" => TextHorizontalAlignment.Right, "right" => TextHorizontalAlignment.Right,
"justify" => TextHorizontalAlignment.Justify, "justify" => TextHorizontalAlignment.Justify,
_ => throw new Exception($"Unknown horizontal alignment '{s}'") _ => throw new InvalidOperationException($"Unknown horizontal alignment '{s}'")
}) ?? TextHorizontalAlignment.Left; }) ?? TextHorizontalAlignment.Left;
var vAlign = reader.GetOptionalAttributeEnum<TextVerticalAlignment>("valign", s => s switch var vAlign = reader.GetOptionalAttributeEnum<TextVerticalAlignment>("valign", s => s switch
{ {
"top" => TextVerticalAlignment.Top, "top" => TextVerticalAlignment.Top,
"center" => TextVerticalAlignment.Center, "center" => TextVerticalAlignment.Center,
"bottom" => TextVerticalAlignment.Bottom, "bottom" => TextVerticalAlignment.Bottom,
_ => throw new Exception($"Unknown vertical alignment '{s}'") _ => throw new InvalidOperationException($"Unknown vertical alignment '{s}'")
}) ?? TextVerticalAlignment.Top; }) ?? TextVerticalAlignment.Top;
// Elements // Elements

View file

@ -66,8 +66,6 @@ internal partial class Tmx
throw new XmlException($"Unkonwn custom class definition: {propertyType}"); throw new XmlException($"Unkonwn custom class definition: {propertyType}");
} }
internal static Dictionary<string, IProperty> CreateInstanceOfCustomClass(CustomClassDefinition customClassDefinition) internal static Dictionary<string, IProperty> CreateInstanceOfCustomClass(CustomClassDefinition customClassDefinition) =>
{ customClassDefinition.Members.ToDictionary(m => m.Name, m => m.Clone());
return customClassDefinition.Members.ToDictionary(m => m.Name, m => m.Clone());
}
} }

View file

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Xml; using System.Xml;
@ -40,19 +41,19 @@ internal partial class Tmx
"bottomleft" => ObjectAlignment.BottomLeft, "bottomleft" => ObjectAlignment.BottomLeft,
"bottom" => ObjectAlignment.Bottom, "bottom" => ObjectAlignment.Bottom,
"bottomright" => ObjectAlignment.BottomRight, "bottomright" => ObjectAlignment.BottomRight,
_ => throw new Exception($"Unknown object alignment '{s}'") _ => throw new InvalidOperationException($"Unknown object alignment '{s}'")
}) ?? ObjectAlignment.Unspecified; }) ?? ObjectAlignment.Unspecified;
var renderSize = reader.GetOptionalAttributeEnum<TileRenderSize>("rendersize", s => s switch var renderSize = reader.GetOptionalAttributeEnum<TileRenderSize>("rendersize", s => s switch
{ {
"tile" => TileRenderSize.Tile, "tile" => TileRenderSize.Tile,
"grid" => TileRenderSize.Grid, "grid" => TileRenderSize.Grid,
_ => throw new Exception($"Unknown render size '{s}'") _ => throw new InvalidOperationException($"Unknown render size '{s}'")
}) ?? TileRenderSize.Tile; }) ?? TileRenderSize.Tile;
var fillMode = reader.GetOptionalAttributeEnum<FillMode>("fillmode", s => s switch var fillMode = reader.GetOptionalAttributeEnum<FillMode>("fillmode", s => s switch
{ {
"stretch" => FillMode.Stretch, "stretch" => FillMode.Stretch,
"preserve-aspect-fit" => FillMode.PreserveAspectFit, "preserve-aspect-fit" => FillMode.PreserveAspectFit,
_ => throw new Exception($"Unknown fill mode '{s}'") _ => throw new InvalidOperationException($"Unknown fill mode '{s}'")
}) ?? FillMode.Stretch; }) ?? FillMode.Stretch;
// Elements // Elements
@ -124,7 +125,7 @@ internal partial class Tmx
"jpg" => ImageFormat.Jpg, "jpg" => ImageFormat.Jpg,
"bmp" => ImageFormat.Bmp, "bmp" => ImageFormat.Bmp,
"gif" => ImageFormat.Gif, "gif" => ImageFormat.Gif,
_ => throw new Exception($"Unknown image format '{s}'") _ => throw new InvalidOperationException($"Unknown image format '{s}'")
}); });
var source = reader.GetOptionalAttribute("source"); var source = reader.GetOptionalAttribute("source");
var transparentColor = reader.GetOptionalAttributeClass<Color>("trans"); var transparentColor = reader.GetOptionalAttributeClass<Color>("trans");
@ -182,7 +183,7 @@ internal partial class Tmx
{ {
"orthogonal" => GridOrientation.Orthogonal, "orthogonal" => GridOrientation.Orthogonal,
"isometric" => GridOrientation.Isometric, "isometric" => GridOrientation.Isometric,
_ => throw new Exception($"Unknown orientation '{s}'") _ => throw new InvalidOperationException($"Unknown orientation '{s}'")
}) ?? GridOrientation.Orthogonal; }) ?? GridOrientation.Orthogonal;
var width = reader.GetRequiredAttributeParseable<uint>("width"); var width = reader.GetRequiredAttributeParseable<uint>("width");
var height = reader.GetRequiredAttributeParseable<uint>("height"); var height = reader.GetRequiredAttributeParseable<uint>("height");
@ -255,10 +256,8 @@ internal partial class Tmx
internal static List<Wangset> ReadWangsets( internal static List<Wangset> ReadWangsets(
XmlReader reader, XmlReader reader,
IReadOnlyCollection<CustomTypeDefinition> customTypeDefinitions) IReadOnlyCollection<CustomTypeDefinition> customTypeDefinitions) =>
{ reader.ReadList<Wangset>("wangsets", "wangset", r => ReadWangset(r, customTypeDefinitions));
return reader.ReadList<Wangset>("wangsets", "wangset", r => ReadWangset(r, customTypeDefinitions));
}
internal static Wangset ReadWangset( internal static Wangset ReadWangset(
XmlReader reader, XmlReader reader,
@ -334,7 +333,7 @@ internal partial class Tmx
var wangID = reader.GetRequiredAttributeParseable<byte[]>("wangid", s => var wangID = reader.GetRequiredAttributeParseable<byte[]>("wangid", s =>
{ {
// Comma-separated list of indices (0-254) // Comma-separated list of indices (0-254)
var indices = s.Split(',').Select(i => byte.Parse(i)).ToArray(); var indices = s.Split(',').Select(i => byte.Parse(i, CultureInfo.InvariantCulture)).ToArray();
if (indices.Length > 8) if (indices.Length > 8)
throw new ArgumentException("Wang ID can have at most 8 indices."); throw new ArgumentException("Wang ID can have at most 8 indices.");
return indices; return indices;

View file

@ -39,14 +39,11 @@ public class TmxMapReader : IMapReader
_customTypeDefinitions = customTypeDefinitions ?? throw new ArgumentNullException(nameof(customTypeDefinitions)); _customTypeDefinitions = customTypeDefinitions ?? throw new ArgumentNullException(nameof(customTypeDefinitions));
// Prepare reader // Prepare reader
_reader.MoveToContent(); _ = _reader.MoveToContent();
} }
/// <inheritdoc/> /// <inheritdoc/>
public Map ReadMap() public Map ReadMap() => Tmx.ReadMap(_reader, _externalTilesetResolver, _externalTemplateResolver, _customTypeDefinitions);
{
return Tmx.ReadMap(_reader, _externalTilesetResolver, _externalTemplateResolver, _customTypeDefinitions);
}
/// <inheritdoc/> /// <inheritdoc/>
protected virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing)
@ -77,6 +74,6 @@ public class TmxMapReader : IMapReader
{ {
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true); Dispose(disposing: true);
System.GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }

View file

@ -35,7 +35,7 @@ public class TsxTilesetReader : ITilesetReader
_customTypeDefinitions = customTypeDefinitions ?? throw new ArgumentNullException(nameof(customTypeDefinitions)); _customTypeDefinitions = customTypeDefinitions ?? throw new ArgumentNullException(nameof(customTypeDefinitions));
// Prepare reader // Prepare reader
_reader.MoveToContent(); _ = _reader.MoveToContent();
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -49,6 +49,7 @@ public class TsxTilesetReader : ITilesetReader
if (disposing) if (disposing)
{ {
// TODO: dispose managed state (managed objects) // TODO: dispose managed state (managed objects)
_reader.Dispose();
} }
// TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: free unmanaged resources (unmanaged objects) and override finalizer
@ -69,6 +70,6 @@ public class TsxTilesetReader : ITilesetReader
{ {
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true); Dispose(disposing: true);
System.GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }

View file

@ -39,7 +39,7 @@ public class TxTemplateReader : ITemplateReader
_customTypeDefinitions = customTypeDefinitions ?? throw new ArgumentNullException(nameof(customTypeDefinitions)); _customTypeDefinitions = customTypeDefinitions ?? throw new ArgumentNullException(nameof(customTypeDefinitions));
// Prepare reader // Prepare reader
_reader.MoveToContent(); _ = _reader.MoveToContent();
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -53,6 +53,7 @@ public class TxTemplateReader : ITemplateReader
if (disposing) if (disposing)
{ {
// TODO: dispose managed state (managed objects) // TODO: dispose managed state (managed objects)
_reader.Dispose();
} }
// TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: free unmanaged resources (unmanaged objects) and override finalizer
@ -73,6 +74,6 @@ public class TxTemplateReader : ITemplateReader
{ {
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true); Dispose(disposing: true);
System.GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }