From a88c6f07663cfddde831433e1907dd029732307d Mon Sep 17 00:00:00 2001 From: Kleis Auke Wolthuizen Date: Sun, 14 Jan 2024 11:21:25 +0100 Subject: [PATCH] C# 11 goodies --- build/Configuration.cs | 5 +- build/Shims.cs | 12 +- build/common.props | 2 +- docs/Build.cs | 7 +- samples/NetVips.Samples/Program.cs | 6 +- .../Samples/CaptchaGenerator.cs | 6 +- .../NetVips.Samples/Samples/GenerateEnums.cs | 20 ++- .../Samples/GenerateImageClass.cs | 138 +++++++-------- .../Samples/GenerateImageOperators.cs | 38 ++-- .../Samples/IdentifyExtension.cs | 5 +- .../NetVips.Samples/Samples/NetworkStream.cs | 3 +- .../NetVips.Samples/Samples/OnePointMosaic.cs | 6 +- .../NetVips.Samples/Samples/OperationRef.cs | 4 +- samples/NetVips.Samples/Samples/PostClose.cs | 2 +- samples/NetVips.Samples/Samples/Progress.cs | 2 +- .../NetVips.Samples/Samples/RandomCropper.cs | 2 +- .../NetVips.Samples/Samples/ShapeCropping.cs | 3 +- src/NetVips.Extensions/BitmapConverter.cs | 83 ++++----- src/NetVips/Cache.cs | 2 +- src/NetVips/ExtensionMethods.cs | 2 +- src/NetVips/GObject.cs | 15 +- src/NetVips/GValue.cs | 126 +++++-------- src/NetVips/Image.cs | 99 ++++------- src/NetVips/Internal/GLib.cs | 11 +- src/NetVips/Internal/GObject.cs | 57 +++--- src/NetVips/Internal/Vips.cs | 165 +++++++++--------- src/NetVips/Interpolate.cs | 4 - src/NetVips/Introspect.cs | 22 +-- src/NetVips/Log.cs | 16 +- src/NetVips/ModuleInitializer.cs | 5 +- src/NetVips/MutableImage.cs | 4 +- src/NetVips/NetVips.cs | 22 +-- src/NetVips/Operation.cs | 18 +- src/NetVips/Region.cs | 4 - src/NetVips/Source.cs | 11 +- src/NetVips/SourceCustom.cs | 7 +- src/NetVips/SourceStream.cs | 21 +-- src/NetVips/Target.cs | 9 - src/NetVips/TargetCustom.cs | 11 +- src/NetVips/TargetStream.cs | 20 +-- src/NetVips/VOption.cs | 4 +- src/NetVips/VipsBlob.cs | 11 +- src/NetVips/VipsObject.cs | 13 +- src/NetVips/VipsProgress.cs | 3 +- tests/NetVips.Benchmarks/Config.cs | 4 +- .../ImageSharp/ConvolutionProcessor.cs | 6 +- tests/NetVips.Tests/ArithmeticTests.cs | 14 +- tests/NetVips.Tests/ColourTests.cs | 8 +- tests/NetVips.Tests/ConversionTests.cs | 19 +- tests/NetVips.Tests/CreateTests.cs | 2 +- tests/NetVips.Tests/ExtensionsTests.cs | 10 +- tests/NetVips.Tests/ForeignTests.cs | 30 ++-- tests/NetVips.Tests/Helper.cs | 18 +- tests/NetVips.Tests/HistogramTests.cs | 6 +- tests/NetVips.Tests/IoFuncsTests.cs | 22 +-- tests/NetVips.Tests/MorphologyTests.cs | 2 +- tests/NetVips.Tests/ResampleTests.cs | 32 ++-- 57 files changed, 508 insertions(+), 691 deletions(-) diff --git a/build/Configuration.cs b/build/Configuration.cs index 253c2179..7ea2754d 100644 --- a/build/Configuration.cs +++ b/build/Configuration.cs @@ -7,8 +7,5 @@ public class Configuration : Enumeration public static Configuration Debug = new() { Value = nameof(Debug) }; public static Configuration Release = new() { Value = nameof(Release) }; - public static implicit operator string(Configuration configuration) - { - return configuration.Value; - } + public static implicit operator string(Configuration configuration) => configuration.Value; } \ No newline at end of file diff --git a/build/Shims.cs b/build/Shims.cs index 83736d48..20732688 100644 --- a/build/Shims.cs +++ b/build/Shims.cs @@ -5,23 +5,17 @@ using System.Xml.Linq; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; -using Nuke.Common; using Nuke.Common.CI; using Nuke.Common.CI.AppVeyor; using Nuke.Common.CI.GitHubActions; using Nuke.Common.CI.TravisCI; +using Serilog; public partial class Build { - static void Information(string info) - { - Serilog.Log.Information(info); - } + static void Information(string info) => Log.Information(info); - static void Information(string info, params object[] args) - { - Serilog.Log.Information(info, args); - } + static void Information(string info, params object[] args) => Log.Information(info, args); public static string GetVersion() { diff --git a/build/common.props b/build/common.props index b5ec4f4a..a47aaa20 100644 --- a/build/common.props +++ b/build/common.props @@ -14,7 +14,7 @@ false false - 9 + 11 2 4 diff --git a/docs/Build.cs b/docs/Build.cs index aef33586..8c305b5e 100644 --- a/docs/Build.cs +++ b/docs/Build.cs @@ -3,11 +3,12 @@ namespace NetVips.Docs using System; using System.IO; using System.Threading.Tasks; + using Docfx; using Docfx.Dotnet; - class Build + internal class Build { - static async Task Main(string[] args) + private static async Task Main(string[] args) { var projectDir = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..")); @@ -15,7 +16,7 @@ static async Task Main(string[] args) Directory.SetCurrentDirectory(projectDir); await DotnetApiCatalog.GenerateManagedReferenceYamlFiles("docfx.json"); - await Docfx.Docset.Build("docfx.json"); + await Docset.Build("docfx.json"); Directory.SetCurrentDirectory(currentDirectory); } } diff --git a/samples/NetVips.Samples/Program.cs b/samples/NetVips.Samples/Program.cs index c4796da5..faa72b12 100644 --- a/samples/NetVips.Samples/Program.cs +++ b/samples/NetVips.Samples/Program.cs @@ -6,7 +6,7 @@ namespace NetVips using System.Reflection; using System.Text; - class Program + internal class Program { private static readonly List Samples = Assembly.GetExecutingAssembly().GetTypes() .Where(x => x.GetInterfaces().Contains(typeof(ISample)) && x.GetConstructor(Type.EmptyTypes) != null) @@ -14,7 +14,7 @@ class Program .OrderBy(s => s?.Category) .ToList(); - static void Main(string[] args) + private static void Main(string[] args) { if (!ModuleInitializer.VipsInitialized) { @@ -33,7 +33,7 @@ static void Main(string[] args) string input; do { - string[] sampleArgs = Array.Empty(); + var sampleArgs = Array.Empty(); if (args.Length > 0) { var sampleId = Samples.Select((value, index) => new { Index = index + 1, value.Name }) diff --git a/samples/NetVips.Samples/Samples/CaptchaGenerator.cs b/samples/NetVips.Samples/Samples/CaptchaGenerator.cs index df50dbc1..88675208 100644 --- a/samples/NetVips.Samples/Samples/CaptchaGenerator.cs +++ b/samples/NetVips.Samples/Samples/CaptchaGenerator.cs @@ -65,7 +65,7 @@ public void Execute(string[] args) using var wobble = Wobble(similarity); // random colour - var colour = Enumerable.Range(1, 3).Select(i => random.Next(0, 255)).ToArray(); + var colour = Enumerable.Range(1, 3).Select(_ => random.Next(0, 255)).ToArray(); using var ifthenelse = wobble.Ifthenelse(colour, 0, blend: true); // tag as 9-bit srgb @@ -101,10 +101,10 @@ public void Execute(string[] args) textLayer = textLayer.Bandjoin(alpha); } - // make a white background with random speckles + // make a white background with random speckles using var speckles = Image.Gaussnoise(textLayer.Width, textLayer.Height, mean: 400, sigma: 200); using var background = Enumerable.Range(1, 2).Aggregate(speckles, - (a, b) => + (a, _) => { using (a) { diff --git a/samples/NetVips.Samples/Samples/GenerateEnums.cs b/samples/NetVips.Samples/Samples/GenerateEnums.cs index 1fc52192..8e4a972e 100644 --- a/samples/NetVips.Samples/Samples/GenerateEnums.cs +++ b/samples/NetVips.Samples/Samples/GenerateEnums.cs @@ -28,15 +28,17 @@ private string Generate() { var allEnums = NetVips.GetEnums(); - const string preamble = @"//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// libvips version: {0} -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------"; + const string preamble = """ + //------------------------------------------------------------------------------ + // + // This code was generated by a tool. + // libvips version: {0} + // + // Changes to this file may cause incorrect behavior and will be lost if + // the code is regenerated. + // + //------------------------------------------------------------------------------ + """; var stringBuilder = new StringBuilder(string.Format(preamble, diff --git a/samples/NetVips.Samples/Samples/GenerateImageClass.cs b/samples/NetVips.Samples/Samples/GenerateImageClass.cs index 847963ba..a14546dc 100644 --- a/samples/NetVips.Samples/Samples/GenerateImageClass.cs +++ b/samples/NetVips.Samples/Samples/GenerateImageClass.cs @@ -12,7 +12,7 @@ public class GenerateImageClass : ISample public string Name => "Generate image class"; public string Category => "Internal"; - private readonly Dictionary _gTypeToCSharpDict = new Dictionary + private readonly Dictionary _gTypeToCSharpDict = new() { {GValue.GBoolType, "bool"}, {GValue.GIntType, "int"}, @@ -35,12 +35,12 @@ public class GenerateImageClass : ISample /// /// The fundamental type for VipsFailOn. See . /// - public static readonly IntPtr FailOnType = NetVips.TypeFromName("VipsFailOn"); + public static readonly nint FailOnType = NetVips.TypeFromName("VipsFailOn"); /// /// The fundamental type for VipsForeignKeep. See . /// - public static readonly IntPtr ForeignKeepType = NetVips.TypeFromName("VipsForeignKeep"); + public static readonly nint ForeignKeepType = NetVips.TypeFromName("VipsForeignKeep"); public GenerateImageClass() { @@ -119,18 +119,18 @@ public GenerateImageClass() /// The GType identifier. /// The GType to map. /// The C# type we use to represent it. - private string GTypeToCSharp(string name, IntPtr gtype) + private string GTypeToCSharp(string name, nint gtype) { - if (_gTypeToCSharpDict.ContainsKey(gtype)) + if (_gTypeToCSharpDict.TryGetValue(gtype, out var value)) { - return _gTypeToCSharpDict[gtype]; + return value; } var fundamental = NetVips.FundamentalType(gtype); - if (_gTypeToCSharpDict.ContainsKey(fundamental)) + if (_gTypeToCSharpDict.TryGetValue(fundamental, out var fundamentalValue)) { - return _gTypeToCSharpDict[fundamental]; + return fundamentalValue; } throw new Exception($"Unsupported type: {gtype} name: {name}"); @@ -190,62 +190,52 @@ string SafeIdentifier(string name) => string SafeCast(string type, string name = "result") { - switch (type) - { - case "GObject": - case "Image": - case "int[]": - case "double[]": - case "byte[]": - case "Image[]": - case "object[]": - return $" as {type};"; - case "bool": - return $" is {type} {name} && {name};"; - case "int": - return $" is {type} {name} ? {name} : 0;"; - case "ulong": - return $" is {type} {name} ? {name} : 0ul;"; - case "double": - return $" is {type} {name} ? {name} : 0d;"; - case "string": - return $" is {type} {name} ? {name} : null;"; - default: - return ";"; - } + return type switch + { + "GObject" => $" as {type};", + "Image" => $" as {type};", + "int[]" => $" as {type};", + "double[]" => $" as {type};", + "byte[]" => $" as {type};", + "Image[]" => $" as {type};", + "object[]" => $" as {type};", + "bool" => $" is {type} {name} && {name};", + "int" => $" is {type} {name} ? {name} : 0;", + "ulong" => $" is {type} {name} ? {name} : 0ul;", + "double" => $" is {type} {name} ? {name} : 0d;", + "string" => $" is {type} {name} ? {name} : null;", + _ => ";" + }; } string ExplicitCast(string type) { return type switch { - { } enumString when enumString.StartsWith("Enums.") => $"({type})", + not null when type.StartsWith("Enums.") => $"({type})", _ => string.Empty }; } string ToNullable(string type, string name) { - switch (type) + return type switch { - case "Image[]": - case "object[]": - case "int[]": - case "double[]": - case "byte[]": - case "GObject": - case "Image": - case "string": - return $"{type} {name} = null"; - case "bool": - case "int": - case "ulong": - case "double": - case { } enumString when enumString.StartsWith("Enums."): - return $"{type}? {name} = null"; - default: - throw new Exception($"Unsupported type: {type}"); - } + "Image[]" => $"{type} {name} = null", + "object[]" => $"{type} {name} = null", + "int[]" => $"{type} {name} = null", + "double[]" => $"{type} {name} = null", + "byte[]" => $"{type} {name} = null", + "GObject" => $"{type} {name} = null", + "Image" => $"{type} {name} = null", + "string" => $"{type} {name} = null", + "bool" => $"{type}? {name} = null", + "int" => $"{type}? {name} = null", + "ulong" => $"{type}? {name} = null", + "double" => $"{type}? {name} = null", + not null when type.StartsWith("Enums.") => $"{type}? {name} = null", + _ => throw new Exception($"Unsupported type: {type}") + }; } var result = new StringBuilder($"{indent}/// \n"); @@ -340,10 +330,8 @@ string ToNullable(string type, string name) $"{indent}/// {op.GetBlurb(arg.Name)}."); } - string outputType; - var outputTypes = requiredOutput.Select(arg => GTypeToCSharp(arg.Name, arg.Type)).ToArray(); - outputType = outputTypes.Length switch + var outputType = outputTypes.Length switch { 0 => "void", 1 => outputTypes[0], @@ -555,7 +543,7 @@ string ToCref(string name) => result.Append($"{indent}}}") .AppendLine(); - var firstArgType = requiredInput.Length > 0 ? op.GetTypeOf(requiredInput[0].Name) : IntPtr.Zero; + nint firstArgType = requiredInput.Length > 0 ? op.GetTypeOf(requiredInput[0].Name) : IntPtr.Zero; // Create stream overload if necessary if (firstArgType == GValue.SourceType || firstArgType == GValue.TargetType) @@ -787,15 +775,17 @@ private string Generate(string indent = " ") // get the list of all nicknames we can generate docstrings for. var allNickNames = _allNickNames.Where(x => !exclude.Contains(x)).ToList(); - const string preamble = @"//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// libvips version: {0} -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------"; + const string preamble = """ + //------------------------------------------------------------------------------ + // + // This code was generated by a tool. + // libvips version: {0} + // + // Changes to this file may cause incorrect behavior and will be lost if + // the code is regenerated. + // + //------------------------------------------------------------------------------ + """; var stringBuilder = new StringBuilder(string.Format(preamble, @@ -860,15 +850,17 @@ private string Generate(string indent = " ") /// The `MutableImage.Generated.cs` as string. private string GenerateMutable(string indent = " ") { - const string preamble = @"//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// libvips version: {0} -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------"; + const string preamble = """ + //------------------------------------------------------------------------------ + // + // This code was generated by a tool. + // libvips version: {0} + // + // Changes to this file may cause incorrect behavior and will be lost if + // the code is regenerated. + // + //------------------------------------------------------------------------------ + """; var stringBuilder = new StringBuilder(string.Format(preamble, diff --git a/samples/NetVips.Samples/Samples/GenerateImageOperators.cs b/samples/NetVips.Samples/Samples/GenerateImageOperators.cs index 8edf4144..f9356a4d 100644 --- a/samples/NetVips.Samples/Samples/GenerateImageOperators.cs +++ b/samples/NetVips.Samples/Samples/GenerateImageOperators.cs @@ -12,12 +12,14 @@ public class GenerateImageOperators : ISample private const string Indent = " "; - private readonly string _docstring = $@"{Indent}/// -{Indent}/// This operation {{0}}. -{Indent}/// -{Indent}/// {{1}}. -{Indent}/// {{2}}. -{Indent}/// A new ."; + private const string Docstring = $$""" + {{Indent}}/// + {{Indent}}/// This operation {0}. + {{Indent}}/// + {{Indent}}/// {1}. + {{Indent}}/// {2}. + {{Indent}}/// A new . + """; /// /// Make a C#-style docstring + operator overload. @@ -228,13 +230,13 @@ private string GenerateOverload(string operatorStr, string type, bool invert = f throw new ArgumentOutOfRangeException(nameof(type), type, "Type out of range"); } - if (operatorStr == "==" || operatorStr == "!=") + if (operatorStr is "==" or "!=") { leftDesc += " to compare"; rightDesc += " to compare"; } - var result = new StringBuilder(string.Format(_docstring, summary, leftDesc, rightDesc)); + var result = new StringBuilder(string.Format(Docstring, summary, leftDesc, rightDesc)); result .AppendLine() @@ -283,14 +285,16 @@ public string GenerateOperators() {">=", new[] {"Image", "double", "double[]", "int[]"}} }; - const string preamble = @"//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------"; + const string preamble = """ + //------------------------------------------------------------------------------ + // + // This code was generated by a tool. + // + // Changes to this file may cause incorrect behavior and will be lost if + // the code is regenerated. + // + //------------------------------------------------------------------------------ + """; var stringBuilder = new StringBuilder(preamble); stringBuilder.AppendLine() @@ -314,7 +318,7 @@ public string GenerateOperators() // We only generate the inverted types of the `==` and `!=` operators // to avoid conflicts with `null` checks (for e.g. `image == null`). // See: `Equal()` and `NotEqual()` for comparison with the other types. - if (operatorStr == "==" || operatorStr == "!=") + if (operatorStr is "==" or "!=") { continue; } diff --git a/samples/NetVips.Samples/Samples/IdentifyExtension.cs b/samples/NetVips.Samples/Samples/IdentifyExtension.cs index a17b912e..d022164a 100644 --- a/samples/NetVips.Samples/Samples/IdentifyExtension.cs +++ b/samples/NetVips.Samples/Samples/IdentifyExtension.cs @@ -2,7 +2,6 @@ namespace NetVips.Samples { using System; using System.IO; - using System.Text; public class IdentifyExtension : ISample { @@ -72,10 +71,10 @@ public void Execute(string[] args) Console.WriteLine(GetExtensionNonTruncated(File.ReadAllBytes("images/lichtenstein.jpg"))); Console.WriteLine("FindLoad function (truncated buffer)"); - Console.WriteLine(GetExtension(Encoding.UTF8.GetBytes("GIF89a"))); + Console.WriteLine(GetExtension("GIF89a"u8.ToArray())); Console.WriteLine("vips-loader function (truncated buffer)"); - Console.WriteLine(GetExtensionNonTruncated(Encoding.UTF8.GetBytes("GIF89a"))); + Console.WriteLine(GetExtensionNonTruncated("GIF89a"u8.ToArray())); } } } \ No newline at end of file diff --git a/samples/NetVips.Samples/Samples/NetworkStream.cs b/samples/NetVips.Samples/Samples/NetworkStream.cs index 9e7333a5..60e655e7 100644 --- a/samples/NetVips.Samples/Samples/NetworkStream.cs +++ b/samples/NetVips.Samples/Samples/NetworkStream.cs @@ -3,7 +3,6 @@ namespace NetVips.Samples using System; using System.IO; using System.Net.Http; - using System.Threading.Tasks; public class NetworkStream : ISample { @@ -39,7 +38,7 @@ public async void Execute(string[] args) using var image = Image.NewFromSource(source, access: Enums.Access.Sequential); Console.WriteLine(image.ToString()); - using var output = File.OpenWrite("stream-network.jpg"); + await using var output = File.OpenWrite("stream-network.jpg"); image.WriteToStream(output, ".jpg"); Console.WriteLine("See stream-network.jpg"); diff --git a/samples/NetVips.Samples/Samples/OnePointMosaic.cs b/samples/NetVips.Samples/Samples/OnePointMosaic.cs index 135b3b85..0bb820c0 100644 --- a/samples/NetVips.Samples/Samples/OnePointMosaic.cs +++ b/samples/NetVips.Samples/Samples/OnePointMosaic.cs @@ -22,7 +22,7 @@ public Point(int x, int y) } } - public List Images = new List + public List Images = new() { "images/cd1.1.jpg", "images/cd1.2.jpg", @@ -34,7 +34,7 @@ public Point(int x, int y) "images/cd4.2.jpg" }; - public List HorizontalMarks = new List + public List HorizontalMarks = new() { new Point(489, 140), new Point(66, 141), @@ -46,7 +46,7 @@ public Point(int x, int y) new Point(40, 57) }; - public List VerticalMarks = new List + public List VerticalMarks = new() { new Point(364, 346), new Point(388, 44), diff --git a/samples/NetVips.Samples/Samples/OperationRef.cs b/samples/NetVips.Samples/Samples/OperationRef.cs index 000d3c53..70f8a4f6 100644 --- a/samples/NetVips.Samples/Samples/OperationRef.cs +++ b/samples/NetVips.Samples/Samples/OperationRef.cs @@ -26,7 +26,7 @@ public void Execute(string[] args) for (var i = 0; i < 1000; i++) { using var crop = image.Crop(0, 0, 256, 256); - var _ = crop.Avg(); + _ = crop.Avg(); Console.WriteLine($"reference count: {image.RefCount}"); @@ -45,7 +45,7 @@ public void Execute(string[] args) using var crop = image.Crop(0, 0, 256, 256); lock (locker) { - var _ = crop.Avg(); + _ = crop.Avg(); Console.WriteLine($"reference count: {image.RefCount} with {count} active threads"); diff --git a/samples/NetVips.Samples/Samples/PostClose.cs b/samples/NetVips.Samples/Samples/PostClose.cs index 670def68..d737e73f 100644 --- a/samples/NetVips.Samples/Samples/PostClose.cs +++ b/samples/NetVips.Samples/Samples/PostClose.cs @@ -19,7 +19,7 @@ public void Execute(string[] args) // Avoid reusing the image after subsequent use Cache.Max = 0; - Action action = OnPostClose; + var action = OnPostClose; var im = Image.NewFromFile(Filename, access: Enums.Access.Sequential); im.OnPostClose += action; diff --git a/samples/NetVips.Samples/Samples/Progress.cs b/samples/NetVips.Samples/Samples/Progress.cs index 32c57537..22420f1d 100644 --- a/samples/NetVips.Samples/Samples/Progress.cs +++ b/samples/NetVips.Samples/Samples/Progress.cs @@ -24,7 +24,7 @@ public void Execute(string[] args) test.SignalConnect(Enums.Signals.Eval, EvalHandler); test.SignalConnect(Enums.Signals.PostEval, PostEvalHandler); - var avg = test.Avg(); + _ = test.Avg(); } private void ProgressPrint(Enums.Signals signal, VipsProgress progress) diff --git a/samples/NetVips.Samples/Samples/RandomCropper.cs b/samples/NetVips.Samples/Samples/RandomCropper.cs index cf32ed35..9c38800b 100644 --- a/samples/NetVips.Samples/Samples/RandomCropper.cs +++ b/samples/NetVips.Samples/Samples/RandomCropper.cs @@ -16,7 +16,7 @@ public class RandomCropper : ISample public const string Filename = "images/equus_quagga.jpg"; - public static readonly Random Rnd = new Random(); + public static readonly Random Rnd = new(); public Image RandomCrop(Image image, int tileSize) { diff --git a/samples/NetVips.Samples/Samples/ShapeCropping.cs b/samples/NetVips.Samples/Samples/ShapeCropping.cs index 2ae8db3d..bcd00887 100644 --- a/samples/NetVips.Samples/Samples/ShapeCropping.cs +++ b/samples/NetVips.Samples/Samples/ShapeCropping.cs @@ -308,8 +308,7 @@ public static int MaximumImageAlpha(Enums.Interpretation interpretation) /// otherwise, public static bool Is16Bit(Enums.Interpretation interpretation) { - return interpretation == Enums.Interpretation.Rgb16 || - interpretation == Enums.Interpretation.Grey16; + return interpretation is Enums.Interpretation.Rgb16 or Enums.Interpretation.Grey16; } #endregion diff --git a/src/NetVips.Extensions/BitmapConverter.cs b/src/NetVips.Extensions/BitmapConverter.cs index 48546d2f..528dd77b 100644 --- a/src/NetVips.Extensions/BitmapConverter.cs +++ b/src/NetVips.Extensions/BitmapConverter.cs @@ -21,30 +21,26 @@ public static class BitmapConverter /// The number of bands. private static int GuessBands(PixelFormat pixelFormat) { - switch (pixelFormat) + return pixelFormat switch { - case PixelFormat.Format8bppIndexed: + PixelFormat.Format8bppIndexed => /* Note: Maplut below will create a 3-band image */ - return 1; - /*case PixelFormat.Format16bppGrayScale: - return 2;*/ - /*case PixelFormat.Format1bppIndexed:*/ - /*case PixelFormat.Format4bppIndexed:*/ - /*case PixelFormat.Format16bppRgb555:*/ - /*case PixelFormat.Format16bppRgb565:*/ - case PixelFormat.Format24bppRgb: - /*case PixelFormat.Format32bppRgb:*/ - case PixelFormat.Format48bppRgb: - return 3; - /*case PixelFormat.Format16bppArgb1555:*/ - case PixelFormat.Format32bppArgb: - case PixelFormat.Format32bppPArgb: - case PixelFormat.Format64bppArgb: - case PixelFormat.Format64bppPArgb: - return 4; - default: - throw new NotImplementedException($"GuessBands({pixelFormat}) is not yet implemented."); - } + 1, + //PixelFormat.Format16bppGrayScale => 2, + //PixelFormat.Format1bppIndexed => 3, + //PixelFormat.Format4bppIndexed => 3, + //PixelFormat.Format16bppRgb555 => 3, + //PixelFormat.Format16bppRgb565 => 3, + PixelFormat.Format24bppRgb => 3, + //PixelFormat.Format32bppRgb => 3, + PixelFormat.Format48bppRgb => 3, + //PixelFormat.Format16bppArgb1555 => 4, + PixelFormat.Format32bppArgb => 4, + PixelFormat.Format32bppPArgb => 4, + PixelFormat.Format64bppArgb => 4, + PixelFormat.Format64bppPArgb => 4, + _ => throw new NotImplementedException($"GuessBands({pixelFormat}) is not yet implemented.") + }; } /// @@ -57,27 +53,24 @@ private static int GuessBands(PixelFormat pixelFormat) /// The . private static Enums.BandFormat GuessBandFormat(PixelFormat pixelFormat) { - switch (pixelFormat) + return pixelFormat switch { - /*case PixelFormat.Format1bppIndexed:*/ - /*case PixelFormat.Format4bppIndexed:*/ - case PixelFormat.Format8bppIndexed: - /*case PixelFormat.Format16bppGrayScale:*/ - /*case PixelFormat.Format16bppRgb555:*/ - /*case PixelFormat.Format16bppRgb565:*/ - case PixelFormat.Format24bppRgb: - /*case PixelFormat.Format32bppRgb:*/ - /*case PixelFormat.Format16bppArgb1555:*/ - case PixelFormat.Format32bppArgb: - case PixelFormat.Format32bppPArgb: - return Enums.BandFormat.Uchar; - case PixelFormat.Format48bppRgb: - case PixelFormat.Format64bppArgb: - case PixelFormat.Format64bppPArgb: - return Enums.BandFormat.Ushort; - default: - throw new NotImplementedException($"GuessBandFormat({pixelFormat}) is not yet implemented."); - } + //PixelFormat.Format1bppIndexed => Enums.BandFormat.Uchar, + //PixelFormat.Format4bppIndexed => Enums.BandFormat.Uchar, + PixelFormat.Format8bppIndexed => Enums.BandFormat.Uchar, + //PixelFormat.Format16bppGrayScale => Enums.BandFormat.Uchar, + //PixelFormat.Format16bppRgb555 => Enums.BandFormat.Uchar, + //PixelFormat.Format16bppRgb565 => Enums.BandFormat.Uchar, + PixelFormat.Format24bppRgb => Enums.BandFormat.Uchar, + //PixelFormat.Format32bppRgb => Enums.BandFormat.Uchar, + //PixelFormat.Format16bppArgb1555 => Enums.BandFormat.Uchar, + PixelFormat.Format32bppArgb => Enums.BandFormat.Uchar, + PixelFormat.Format32bppPArgb => Enums.BandFormat.Uchar, + PixelFormat.Format48bppRgb => Enums.BandFormat.Ushort, + PixelFormat.Format64bppArgb => Enums.BandFormat.Ushort, + PixelFormat.Format64bppPArgb => Enums.BandFormat.Ushort, + _ => throw new NotImplementedException($"GuessBandFormat({pixelFormat}) is not yet implemented.") + }; } /// @@ -95,9 +88,7 @@ public static Image ToVips(this Bitmap src) // 8 bits are not used anyway) images. This is faster than the pixel // loops commented below and simplifies the code considerably. var pf = - src.PixelFormat == PixelFormat.Format1bppIndexed || - src.PixelFormat == PixelFormat.Format4bppIndexed || - src.PixelFormat == PixelFormat.Format32bppRgb + src.PixelFormat is PixelFormat.Format1bppIndexed or PixelFormat.Format4bppIndexed or PixelFormat.Format32bppRgb ? PixelFormat.Format24bppRgb : src.PixelFormat; @@ -355,7 +346,7 @@ public static Bitmap ToBitmap(this Image src) $"Number of bands must be 1 or in the in the range of 3 to 4. Got: {src.Bands}"); } - if (src.Format != Enums.BandFormat.Uchar || src.Format != Enums.BandFormat.Ushort) + if (src.Format is not (Enums.BandFormat.Uchar or Enums.BandFormat.Ushort)) { // Pixel formats other than uchar and ushort needs to be casted to uint8 (unsigned char) using (src) diff --git a/src/NetVips/Cache.cs b/src/NetVips/Cache.cs index 7032636d..9e19d235 100644 --- a/src/NetVips/Cache.cs +++ b/src/NetVips/Cache.cs @@ -21,7 +21,7 @@ public static int Max /// public static ulong MaxMem { - get => (ulong) Vips.CacheGetMaxMem(); + get => Vips.CacheGetMaxMem(); set => Vips.CacheSetMaxMem(value); } diff --git a/src/NetVips/ExtensionMethods.cs b/src/NetVips/ExtensionMethods.cs index ea43ef0a..d525c3a2 100644 --- a/src/NetVips/ExtensionMethods.cs +++ b/src/NetVips/ExtensionMethods.cs @@ -104,7 +104,7 @@ internal static object[] PrependImage(this T[] args, Image image) /// If set to , free the GLib string. /// Size of the GLib string, use 0 to read until the null character. /// The managed string. - internal static string ToUtf8String(this IntPtr utf8Str, bool freePtr = false, int size = 0) + internal static string ToUtf8String(this nint utf8Str, bool freePtr = false, int size = 0) { if (utf8Str == IntPtr.Zero) { diff --git a/src/NetVips/GObject.cs b/src/NetVips/GObject.cs index 749b6bf2..db51748b 100644 --- a/src/NetVips/GObject.cs +++ b/src/NetVips/GObject.cs @@ -11,8 +11,6 @@ namespace NetVips /// public class GObject : SafeHandle { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// We have to record all of the delegates to /// prevent them from being re-located or disposed of by the garbage collector. @@ -46,7 +44,6 @@ internal GObject(IntPtr pointer) SetHandle(pointer); // NObjects++; - // logger.Debug($"GObject = {pointer}"); } /// @@ -61,7 +58,7 @@ internal GObject(IntPtr pointer) /// Data to pass to handler calls. /// The handler id. /// If it failed to connect the signal. - public ulong SignalConnect(string detailedSignal, T callback, IntPtr data = default) + public ulong SignalConnect(string detailedSignal, T callback, nint data = default) where T : notnull { // add a weak reference callback to ensure all handles are released on finalization @@ -110,7 +107,7 @@ public void SignalHandlerDisconnect(ulong handlerId) /// The func of the handlers. /// The data of the handlers. /// The number of handlers that matched. - public uint SignalHandlersDisconnectByFunc(T func, IntPtr data = default) + public uint SignalHandlersDisconnectByFunc(T func, nint data = default) where T : notnull { var funcPtr = Marshal.GetFunctionPointerForDelegate(func); @@ -124,7 +121,7 @@ public uint SignalHandlersDisconnectByFunc(T func, IntPtr data = default) /// /// The data of the handlers. /// The number of handlers that matched. - public uint SignalHandlersDisconnectByData(IntPtr data) + public uint SignalHandlersDisconnectByData(nint data) { return GSignal.HandlersDisconnectMatched(this, GSignalMatchType.G_SIGNAL_MATCH_DATA, @@ -139,7 +136,6 @@ public uint SignalHandlersDisconnectByData(IntPtr data) /// in the event of a catastrophic failure, . protected override bool ReleaseHandle() { - // logger.Debug($"Unref: GObject = {handle}"); if (!IsInvalid) { Internal.GObject.Unref(handle); @@ -157,7 +153,7 @@ protected override bool ReleaseHandle() /// /// Data that was provided when the weak reference was established. /// The object being disposed. - internal void ReleaseDelegates(IntPtr data, IntPtr objectPointer) + internal void ReleaseDelegates(nint data, nint objectPointer) { foreach (var gcHandle in _handles) { @@ -181,9 +177,8 @@ internal void ReleaseDelegates(IntPtr data, IntPtr objectPointer) /// /// Increases the reference count of object. /// - internal IntPtr ObjectRef() + internal nint ObjectRef() { - // logger.Debug($"Ref: GObject = {handle}"); return Internal.GObject.Ref(handle); } diff --git a/src/NetVips/GValue.cs b/src/NetVips/GValue.cs index 5dd4ebe6..cb632a3e 100644 --- a/src/NetVips/GValue.cs +++ b/src/NetVips/GValue.cs @@ -21,8 +21,6 @@ namespace NetVips /// public class GValue : IDisposable { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// The specified struct to wrap around. /// @@ -43,92 +41,87 @@ public class GValue : IDisposable /// /// The fundamental type corresponding to gboolean. /// - public static readonly IntPtr GBoolType = new IntPtr(5 << FundamentalShift); + public static readonly nint GBoolType = 5 << FundamentalShift; /// /// The fundamental type corresponding to gint. /// - public static readonly IntPtr GIntType = new IntPtr(6 << FundamentalShift); + public static readonly nint GIntType = 6 << FundamentalShift; /// /// The fundamental type corresponding to guint64. /// - public static readonly IntPtr GUint64Type = new IntPtr(11 << FundamentalShift); + public static readonly nint GUint64Type = 11 << FundamentalShift; /// /// The fundamental type from which all enumeration types are derived. /// - public static readonly IntPtr GEnumType = new IntPtr(12 << FundamentalShift); + public static readonly nint GEnumType = 12 << FundamentalShift; /// /// The fundamental type from which all flags types are derived. /// - public static readonly IntPtr GFlagsType = new IntPtr(13 << FundamentalShift); + public static readonly nint GFlagsType = 13 << FundamentalShift; /// /// The fundamental type corresponding to gdouble. /// - public static readonly IntPtr GDoubleType = new IntPtr(15 << FundamentalShift); + public static readonly nint GDoubleType = 15 << FundamentalShift; /// /// The fundamental type corresponding to null-terminated C strings. /// - public static readonly IntPtr GStrType = new IntPtr(16 << FundamentalShift); + public static readonly nint GStrType = 16 << FundamentalShift; /// /// The fundamental type for GObject. /// - public static readonly IntPtr GObjectType = new IntPtr(20 << FundamentalShift); + public static readonly nint GObjectType = 20 << FundamentalShift; /// /// The fundamental type for VipsImage. /// - public static readonly IntPtr ImageType = NetVips.TypeFromName("VipsImage"); + public static readonly nint ImageType = NetVips.TypeFromName("VipsImage"); /// /// The fundamental type for VipsArrayInt. /// - public static readonly IntPtr ArrayIntType = NetVips.TypeFromName("VipsArrayInt"); + public static readonly nint ArrayIntType = NetVips.TypeFromName("VipsArrayInt"); /// /// The fundamental type for VipsArrayDouble. /// - public static readonly IntPtr ArrayDoubleType = NetVips.TypeFromName("VipsArrayDouble"); + public static readonly nint ArrayDoubleType = NetVips.TypeFromName("VipsArrayDouble"); /// /// The fundamental type for VipsArrayImage. /// - public static readonly IntPtr ArrayImageType = NetVips.TypeFromName("VipsArrayImage"); + public static readonly nint ArrayImageType = NetVips.TypeFromName("VipsArrayImage"); /// /// The fundamental type for VipsRefString. /// - public static readonly IntPtr RefStrType = NetVips.TypeFromName("VipsRefString"); + public static readonly nint RefStrType = NetVips.TypeFromName("VipsRefString"); /// /// The fundamental type for VipsBlob. /// - public static readonly IntPtr BlobType = NetVips.TypeFromName("VipsBlob"); - - /// - /// The fundamental type for VipsBandFormat. See . - /// - public static readonly IntPtr BandFormatType = Vips.BandFormatGetType(); + public static readonly nint BlobType = NetVips.TypeFromName("VipsBlob"); /// /// The fundamental type for VipsBlendMode. See . /// - public static readonly IntPtr BlendModeType; + public static readonly nint BlendModeType; /// /// The fundamental type for VipsSource. See . /// - public static readonly IntPtr SourceType; + public static readonly nint SourceType; /// /// The fundamental type for VipsTarget. See . /// - public static readonly IntPtr TargetType; + public static readonly nint TargetType; /// /// Hint of how much native memory is actually occupied by the object. @@ -155,7 +148,6 @@ static GValue() public GValue() { Struct = new Internal.GValue.Struct(); - // logger.Debug($"GValue = {Struct}"); } /// @@ -166,7 +158,6 @@ public GValue() internal GValue(Internal.GValue.Struct value) { Struct = value; - // logger.Debug($"GValue = {Struct}"); } /// @@ -180,7 +171,7 @@ internal GValue(Internal.GValue.Struct value) /// TypeFind. /// /// Type the GValue should hold values of. - public void SetType(IntPtr gtype) + public void SetType(nint gtype) { Internal.GValue.Init(ref Struct, gtype); } @@ -214,7 +205,6 @@ private void AddMemoryPressure(long bytesAllocated) /// Value to be set. public void Set(object value) { - // logger.Debug($"Set: value = {value}"); var gtype = GetTypeOf(); var fundamental = GType.Fundamental(gtype); if (gtype == GBoolType) @@ -258,53 +248,37 @@ public void Set(object value) } else if (gtype == ArrayIntType) { - if (!(value is IEnumerable)) + if (value is not IEnumerable) { value = new[] { value }; } - int[] integers; - switch (value) + var integers = value switch { - case int[] ints: - integers = ints; - break; - case double[] doubles: - integers = Array.ConvertAll(doubles, Convert.ToInt32); - break; - case object[] objects: - integers = Array.ConvertAll(objects, Convert.ToInt32); - break; - default: - throw new ArgumentException( - $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}"); - } + int[] ints => ints, + double[] doubles => Array.ConvertAll(doubles, Convert.ToInt32), + object[] objects => Array.ConvertAll(objects, Convert.ToInt32), + _ => throw new ArgumentException( + $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}") + }; VipsValue.SetArrayInt(ref Struct, integers, integers.Length); } else if (gtype == ArrayDoubleType) { - if (!(value is IEnumerable)) + if (value is not IEnumerable) { value = new[] { value }; } - double[] doubles; - switch (value) + var doubles = value switch { - case double[] dbls: - doubles = dbls; - break; - case int[] ints: - doubles = Array.ConvertAll(ints, Convert.ToDouble); - break; - case object[] objects: - doubles = Array.ConvertAll(objects, Convert.ToDouble); - break; - default: - throw new ArgumentException( - $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}"); - } + double[] dbls => dbls, + int[] ints => Array.ConvertAll(ints, Convert.ToDouble), + object[] objects => Array.ConvertAll(objects, Convert.ToDouble), + _ => throw new ArgumentException( + $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}") + }; VipsValue.SetArrayDouble(ref Struct, doubles, doubles.Length); } @@ -332,23 +306,14 @@ public void Set(object value) } else if (gtype == BlobType) { - byte[] memory; - - switch (value) + var memory = value switch { - case string strValue: - memory = Encoding.UTF8.GetBytes(strValue); - break; - case char[] charArrValue: - memory = Encoding.UTF8.GetBytes(charArrValue); - break; - case byte[] byteArrValue: - memory = byteArrValue; - break; - default: - throw new ArgumentException( - $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}"); - } + string strValue => Encoding.UTF8.GetBytes(strValue), + char[] charArrValue => Encoding.UTF8.GetBytes(charArrValue), + byte[] byteArrValue => byteArrValue, + _ => throw new ArgumentException( + $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}") + }; // We need to set the blob to a copy of the string that vips can own var ptr = GLib.GMalloc((ulong)memory.Length); @@ -362,7 +327,7 @@ public void Set(object value) } else { - int FreeFn(IntPtr a, IntPtr b) + int FreeFn(nint a, nint b) { GLib.GFree(a); @@ -388,7 +353,6 @@ int FreeFn(IntPtr a, IntPtr b) /// The contents of this GValue. public object Get() { - // logger.Debug($"Get: this = {this}"); var gtype = GetTypeOf(); var fundamental = GType.Fundamental(gtype); @@ -491,7 +455,7 @@ public object Get() /// Get the GType of this GValue. /// /// The GType of this GValue. - public IntPtr GetTypeOf() + public nint GetTypeOf() { return Struct.GType; } @@ -516,8 +480,6 @@ public IntPtr GetTypeOf() /// to release only unmanaged resources. protected void Dispose(bool disposing) { - // logger.Debug($"GC: GValue = {Struct}"); - // Check to see if Dispose has already been called. if (!_disposed) { @@ -533,8 +495,6 @@ protected void Dispose(bool disposing) // Note disposing has been done. _disposed = true; } - - // logger.Debug($"GC: GValue = {Struct}"); } /// diff --git a/src/NetVips/Image.cs b/src/NetVips/Image.cs index 24266805..be7d3cf7 100644 --- a/src/NetVips/Image.cs +++ b/src/NetVips/Image.cs @@ -14,8 +14,6 @@ namespace NetVips /// public partial class Image : VipsObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// A evaluation delegate that can be used on the /// , and @@ -30,13 +28,12 @@ public partial class Image : VipsObject /// Internal marshaller delegate for . /// [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void EvalMarshalDelegate(IntPtr imagePtr, VipsProgress progress, IntPtr userDataPtr); + internal delegate void EvalMarshalDelegate(nint imagePtr, VipsProgress progress, nint userDataPtr); /// internal Image(IntPtr pointer) : base(pointer) { - // logger.Debug($"VipsImage = {pointer}"); } #region helpers @@ -109,28 +106,18 @@ private static Image RunCmplx(Func func, Image image) /// A new . public static Image Imageize(Image matchImage, object value) { - // logger.Debug($"Imageize: value = {value}"); // careful! this can be None if value is a 2D array - switch (value) - { - case Image image: - return image; - case double[,] doubleArray: - return NewFromArray(doubleArray); - case int[,] intArray: - return NewFromArray(intArray); - case double[] doubles: - return matchImage.NewFromImage(doubles); - case int[] ints: - return matchImage.NewFromImage(ints); - case double doubleValue: - return matchImage.NewFromImage(doubleValue); - case int intValue: - return matchImage.NewFromImage(intValue); - default: - throw new ArgumentException( - $"unsupported value type {value.GetType()} for Imageize"); - } + return value switch + { + Image image => image, + double[,] doubleArray => NewFromArray(doubleArray), + int[,] intArray => NewFromArray(intArray), + double[] doubles => matchImage.NewFromImage(doubles), + int[] ints => matchImage.NewFromImage(ints), + double doubleValue => matchImage.NewFromImage(doubleValue), + int intValue => matchImage.NewFromImage(intValue), + _ => throw new ArgumentException($"unsupported value type {value.GetType()} for Imageize") + }; } /// @@ -450,7 +437,7 @@ public static Image NewFromSource( using var blob = new VipsBlob(ptr); var buf = blob.GetData(out var length); - operationName = Marshal.PtrToStringAnsi(VipsForeign.FindLoadBuffer(buf, (ulong)length)); + operationName = Marshal.PtrToStringAnsi(VipsForeign.FindLoadBuffer(buf, length)); if (operationName == null) { throw new VipsException("unable to load from source"); @@ -521,13 +508,12 @@ public static Image NewFromArray(T[,] array, double scale = 1.0, double offse { for (var x = 0; x < width; x++) { - ref var value = ref a[x + (y * width)]; + ref var value = ref a[x + y * width]; value = Convert.ToDouble(array[y, x]); } } var vi = VipsImage.NewMatrixFromArray(width, height, a, n); - if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from matrix"); @@ -569,13 +555,12 @@ public static Image NewFromArray(T[][] array, double scale = 1.0, double offs { for (var x = 0; x < width; x++) { - ref var value = ref a[x + (y * width)]; + ref var value = ref a[x + y * width]; value = Convert.ToDouble(array[y][x]); } } var vi = VipsImage.NewMatrixFromArray(width, height, a, n); - if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from matrix"); @@ -618,7 +603,6 @@ public static Image NewFromArray(T[] array, double scale = 1.0, double offset } var vi = VipsImage.NewMatrixFromArray(1, height, a, height); - if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from matrix"); @@ -669,9 +653,8 @@ public static Image NewFromMemory( Enums.BandFormat format) { var handle = GCHandle.Alloc(data, GCHandleType.Pinned); - var vi = VipsImage.NewFromMemory(handle.AddrOfPinnedObject(), (UIntPtr)data.Length, width, height, bands, + var vi = VipsImage.NewFromMemory(handle.AddrOfPinnedObject(), (nuint)data.Length, width, height, bands, format); - if (vi == IntPtr.Zero) { if (handle.IsAllocated) @@ -713,15 +696,14 @@ public static Image NewFromMemory( /// A new . /// If unable to make image from . public static Image NewFromMemory( - IntPtr data, + nint data, ulong size, int width, int height, int bands, Enums.BandFormat format) { - var vi = VipsImage.NewFromMemory(data, (UIntPtr)size, width, height, bands, format); - + var vi = VipsImage.NewFromMemory(data, (nuint)size, width, height, bands, format); if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from memory"); @@ -731,7 +713,7 @@ public static Image NewFromMemory( } /// - /// Like , but libvips + /// Like , but libvips /// will make a copy of the memory area. This means more memory use and an extra copy /// operation, but is much simpler and safer. /// @@ -744,15 +726,14 @@ public static Image NewFromMemory( /// A new . /// If unable to make image from . public static Image NewFromMemoryCopy( - IntPtr data, + nint data, ulong size, int width, int height, int bands, Enums.BandFormat format) { - var vi = VipsImage.NewFromMemoryCopy(data, (UIntPtr)size, width, height, bands, format); - + var vi = VipsImage.NewFromMemoryCopy(data, (nuint)size, width, height, bands, format); if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from memory"); @@ -1008,7 +989,7 @@ public byte[] WriteToBuffer(string formatString, VOption kwargs = null) operationName = Marshal.PtrToStringAnsi(VipsForeign.FindSaveBuffer(bytes)); if (operationName == null) { - throw new VipsException($"unable to write to buffer"); + throw new VipsException("unable to write to buffer"); } return this.Call(operationName, kwargs) as byte[]; @@ -1082,9 +1063,9 @@ public void WriteToStream(Stream stream, string formatString, VOption kwargs = n /// The caller is responsible for freeing this memory with . /// /// Output buffer length. - /// A pointing to an unformatted C-style array. + /// A pointing to an unformatted C-style array. /// If unable to write to memory. - public IntPtr WriteToMemory(out ulong size) + public nint WriteToMemory(out ulong size) { var pointer = VipsImage.WriteToMemory(this, out size); if (pointer == IntPtr.Zero) @@ -1153,9 +1134,9 @@ public void Write(Image other) /// item does not exist. See . /// /// The name of the piece of metadata to get the type of. - /// A new instance of initialized to the GType or + /// A new instance of initialized to the GType or /// if the property does not exist. - public new IntPtr GetTypeOf(string name) + public new nint GetTypeOf(string name) { // on libvips before 8.5, property types must be fetched separately, // since built-in enums were reported as ints @@ -1245,7 +1226,7 @@ public string[] GetFields() var names = new List(); var count = 0; - IntPtr strPtr; + nint strPtr; while ((strPtr = Marshal.ReadIntPtr(ptrArr, count * IntPtr.Size)) != IntPtr.Zero) { var name = Marshal.PtrToStringAnsi(strPtr); @@ -2045,7 +2026,7 @@ public Image AddAlpha() return new Image(vi); } - var maxAlpha = Interpretation == Enums.Interpretation.Grey16 || Interpretation == Enums.Interpretation.Rgb16 + var maxAlpha = Interpretation is Enums.Interpretation.Grey16 or Enums.Interpretation.Rgb16 ? 65535 : 255; return Bandjoin(maxAlpha); @@ -2101,9 +2082,9 @@ public void SetKill(bool kill) /// Data to pass to handler calls. /// The handler id. /// If it failed to connect the signal. - public ulong SignalConnect(Enums.Signals signal, EvalDelegate callback, IntPtr data = default) + public ulong SignalConnect(Enums.Signals signal, EvalDelegate callback, nint data = default) { - void EvalMarshal(IntPtr imagePtr, VipsProgress progress, IntPtr userDataPtr) + void EvalMarshal(nint imagePtr, VipsProgress progress, nint userDataPtr) { if (imagePtr == IntPtr.Zero) { @@ -2116,18 +2097,14 @@ void EvalMarshal(IntPtr imagePtr, VipsProgress progress, IntPtr userDataPtr) callback.Invoke(image, progress); } - switch (signal) - { - case Enums.Signals.PreEval: - return SignalConnect("preeval", EvalMarshal, data); - case Enums.Signals.Eval: - return SignalConnect("eval", EvalMarshal, data); - case Enums.Signals.PostEval: - return SignalConnect("posteval", EvalMarshal, data); - default: - throw new ArgumentOutOfRangeException(nameof(signal), signal, - $"The value of argument '{nameof(signal)}' ({signal}) is invalid for enum type '{nameof(Enums.Signals)}'."); - } + return signal switch + { + Enums.Signals.PreEval => SignalConnect("preeval", EvalMarshal, data), + Enums.Signals.Eval => SignalConnect("eval", EvalMarshal, data), + Enums.Signals.PostEval => SignalConnect("posteval", EvalMarshal, data), + _ => throw new ArgumentOutOfRangeException(nameof(signal), signal, + $"The value of argument '{nameof(signal)}' ({signal}) is invalid for enum type '{nameof(Enums.Signals)}'.") + }; } /// diff --git a/src/NetVips/Internal/GLib.cs b/src/NetVips/Internal/GLib.cs index a7f1467f..0c7e0398 100644 --- a/src/NetVips/Internal/GLib.cs +++ b/src/NetVips/Internal/GLib.cs @@ -1,6 +1,5 @@ namespace NetVips.Internal { - using System; using System.Runtime.InteropServices; using System.Security; using Interop; @@ -9,24 +8,24 @@ namespace NetVips.Internal internal static class GLib { [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void LogFuncNative(IntPtr logDomain, LogLevelFlags flags, IntPtr message, - IntPtr userData); + internal delegate void LogFuncNative(nint logDomain, LogLevelFlags flags, nint message, + nint userData); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GLib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_free")] - internal static extern void GFree(IntPtr mem); + internal static extern void GFree(nint mem); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GLib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_malloc")] - internal static extern IntPtr GMalloc(ulong nBytes); + internal static extern nint GMalloc(ulong nBytes); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GLib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_log_set_handler")] internal static extern uint GLogSetHandler([MarshalAs(UnmanagedType.LPStr)] string logDomain, - LogLevelFlags flags, LogFuncNative logFunc, IntPtr userData); + LogLevelFlags flags, LogFuncNative logFunc, nint userData); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GLib, CallingConvention = CallingConvention.Cdecl, diff --git a/src/NetVips/Internal/GObject.cs b/src/NetVips/Internal/GObject.cs index 1c764726..63d9e7c3 100644 --- a/src/NetVips/Internal/GObject.cs +++ b/src/NetVips/Internal/GObject.cs @@ -1,6 +1,5 @@ namespace NetVips.Internal { - using System; using System.Runtime.InteropServices; using System.Security; using Interop; @@ -8,7 +7,7 @@ namespace NetVips.Internal using VipsBlobManaged = global::NetVips.VipsBlob; [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void GWeakNotify(IntPtr data, IntPtr objectPointer); + internal delegate void GWeakNotify(nint data, nint objectPointer); internal static class GObject { @@ -19,7 +18,7 @@ internal struct Struct internal uint RefCount; - internal IntPtr QData; + internal nint QData; } [SuppressUnmanagedCodeSecurity] @@ -37,17 +36,17 @@ internal static extern void GetProperty(GObjectManaged @object, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_object_ref")] - internal static extern IntPtr Ref(IntPtr @object); + internal static extern nint Ref(nint @object); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_object_unref")] - internal static extern void Unref(IntPtr @object); + internal static extern void Unref(nint @object); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_object_weak_ref")] - internal static extern void WeakRef(GObjectManaged @object, GWeakNotify notify, IntPtr data); + internal static extern void WeakRef(GObjectManaged @object, GWeakNotify notify, nint data); } [StructLayout(LayoutKind.Sequential)] @@ -65,13 +64,13 @@ internal struct GEnumValue [StructLayout(LayoutKind.Sequential)] internal struct GEnumClass { - internal IntPtr GTypeClass; + internal nint GTypeClass; internal int Minimum; internal int Maximum; internal uint NValues; - internal IntPtr Values; + internal nint Values; } internal static class GType @@ -79,28 +78,28 @@ internal static class GType [StructLayout(LayoutKind.Sequential)] internal struct Instance { - internal IntPtr GClass; + internal nint GClass; } [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_type_name")] - internal static extern IntPtr Name(IntPtr type); + internal static extern nint Name(nint type); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_type_from_name")] - internal static extern IntPtr FromName([MarshalAs(UnmanagedType.LPStr)] string name); + internal static extern nint FromName([MarshalAs(UnmanagedType.LPStr)] string name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_type_fundamental")] - internal static extern IntPtr Fundamental(IntPtr typeId); + internal static extern nint Fundamental(nint typeId); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_type_class_ref")] - internal static extern IntPtr ClassRef(IntPtr type); + internal static extern nint ClassRef(nint type); } internal static class GValue @@ -109,17 +108,17 @@ internal static class GValue internal struct Struct { [FieldOffset(0)] - internal IntPtr GType; + internal nint GType; [FieldOffset(8)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - internal IntPtr[] Data; + internal nint[] Data; } [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_value_init")] - internal static extern IntPtr Init(ref Struct value, IntPtr gType); + internal static extern nint Init(ref Struct value, nint gType); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, @@ -175,7 +174,7 @@ internal struct Struct [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_value_get_string")] - internal static extern IntPtr GetString(in Struct value); + internal static extern nint GetString(in Struct value); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, @@ -205,7 +204,7 @@ internal struct Struct [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_value_get_object")] - internal static extern IntPtr GetObject(in Struct value); + internal static extern nint GetObject(in Struct value); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, @@ -220,15 +219,15 @@ internal struct Struct { internal GType.Instance GTypeInstance; - internal IntPtr Name; + internal nint Name; internal Enums.GParamFlags Flags; - internal IntPtr ValueType; - internal IntPtr OwnerType; + internal nint ValueType; + internal nint OwnerType; - internal IntPtr Nick; - internal IntPtr Blurb; - internal IntPtr QData; + internal nint Nick; + internal nint Blurb; + internal nint QData; internal uint RefCount; internal uint ParamId; } @@ -236,11 +235,11 @@ internal struct Struct [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_param_spec_get_blurb")] - internal static extern IntPtr GetBlurb(in Struct pspec); + internal static extern nint GetBlurb(in Struct pspec); } [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void GClosureNotify(IntPtr data, IntPtr closure); + internal delegate void GClosureNotify(nint data, nint closure); internal static class GSignal { @@ -249,7 +248,7 @@ internal static class GSignal EntryPoint = "g_signal_connect_data")] internal static extern ulong ConnectData(GObjectManaged instance, [MarshalAs(UnmanagedType.LPStr)] string detailedSignal, - IntPtr cHandler, IntPtr data, + nint cHandler, nint data, GClosureNotify destroyData, Enums.GConnectFlags connectFlags); [SuppressUnmanagedCodeSecurity] @@ -261,7 +260,7 @@ internal static extern ulong ConnectData(GObjectManaged instance, [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_signal_handlers_disconnect_matched")] internal static extern uint HandlersDisconnectMatched(GObjectManaged instance, - Enums.GSignalMatchType mask, uint signalId, uint detail, IntPtr closure, - IntPtr func, IntPtr data); + Enums.GSignalMatchType mask, uint signalId, uint detail, nint closure, + nint func, nint data); } } \ No newline at end of file diff --git a/src/NetVips/Internal/Vips.cs b/src/NetVips/Internal/Vips.cs index fe1572fe..176ccbba 100644 --- a/src/NetVips/Internal/Vips.cs +++ b/src/NetVips/Internal/Vips.cs @@ -1,6 +1,5 @@ namespace NetVips.Internal { - using System; using System.Runtime.InteropServices; using System.Security; using System.Text; @@ -14,14 +13,14 @@ namespace NetVips.Internal internal static class Vips { [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr TypeMap2Fn(IntPtr type, IntPtr a, IntPtr b); + internal delegate nint TypeMap2Fn(nint type, nint a, nint b); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr ArgumentMapFn(IntPtr @object, GParamSpec.Struct pspec, VipsArgumentClass argumentClass, - VipsArgumentInstance argumentInstance, IntPtr a, IntPtr b); + internal delegate nint ArgumentMapFn(nint @object, GParamSpec.Struct pspec, VipsArgumentClass argumentClass, + VipsArgumentInstance argumentInstance, nint a, nint b); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int CallbackFn(IntPtr a, IntPtr b); + internal delegate int CallbackFn(nint a, nint b); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -56,7 +55,7 @@ internal delegate IntPtr ArgumentMapFn(IntPtr @object, GParamSpec.Struct pspec, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_cache_get_max_mem")] - internal static extern UIntPtr CacheGetMaxMem(); + internal static extern nuint CacheGetMaxMem(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -137,7 +136,7 @@ internal delegate IntPtr ArgumentMapFn(IntPtr @object, GParamSpec.Struct pspec, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_error_buffer")] - internal static extern IntPtr ErrorBuffer(); + internal static extern nint ErrorBuffer(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -157,59 +156,59 @@ internal delegate IntPtr ArgumentMapFn(IntPtr @object, GParamSpec.Struct pspec, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_path_filename7")] - internal static extern IntPtr PathFilename7(byte[] path); + internal static extern nint PathFilename7(byte[] path); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_path_mode7")] - internal static extern IntPtr PathMode7(byte[] path); + internal static extern nint PathMode7(byte[] path); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_filename_get_filename")] - internal static extern IntPtr GetFilename(byte[] vipsFilename); + internal static extern nint GetFilename(byte[] vipsFilename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_filename_get_options")] - internal static extern IntPtr GetOptions(byte[] vipsFilename); + internal static extern nint GetOptions(byte[] vipsFilename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_blend_mode_get_type")] - internal static extern IntPtr BlendModeGetType(); + internal static extern nint BlendModeGetType(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_interpretation_get_type")] - internal static extern IntPtr InterpretationGetType(); + internal static extern nint InterpretationGetType(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_band_format_get_type")] - internal static extern IntPtr BandFormatGetType(); + internal static extern nint BandFormatGetType(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_argument_map")] - internal static extern IntPtr ArgumentMap(VipsObjectManaged @object, ArgumentMapFn fn, IntPtr a, - IntPtr b); + internal static extern nint ArgumentMap(VipsObjectManaged @object, ArgumentMapFn fn, nint a, + nint b); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_type_map")] - internal static extern IntPtr TypeMap(IntPtr @base, TypeMap2Fn fn, IntPtr a, IntPtr b); + internal static extern nint TypeMap(nint @base, TypeMap2Fn fn, nint a, nint b); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_type_find")] - internal static extern IntPtr TypeFind([MarshalAs(UnmanagedType.LPStr)] string basename, + internal static extern nint TypeFind([MarshalAs(UnmanagedType.LPStr)] string basename, [MarshalAs(UnmanagedType.LPStr)] string nickname); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_nickname_find")] - internal static extern IntPtr NicknameFind(IntPtr type); + internal static extern nint NicknameFind(nint type); internal static string PathFilename7(string path) { @@ -228,7 +227,7 @@ internal static class VipsObject { [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_object_get_args")] - internal static extern int GetArgs(VipsObjectManaged @object, out IntPtr names, out IntPtr flags, + internal static extern int GetArgs(VipsObjectManaged @object, out nint names, out nint flags, out int nArgs); [SuppressUnmanagedCodeSecurity] @@ -236,7 +235,7 @@ internal static extern int GetArgs(VipsObjectManaged @object, out IntPtr names, EntryPoint = "vips_object_get_argument")] internal static extern int GetArgument(VipsObjectManaged @object, [MarshalAs(UnmanagedType.LPStr)] string name, - out IntPtr pspec, out VipsArgumentClass argumentClass, + out nint pspec, out VipsArgumentClass argumentClass, out VipsArgumentInstance argumentInstance); [SuppressUnmanagedCodeSecurity] @@ -257,20 +256,20 @@ internal static extern int SetFromString(VipsObjectManaged @object, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_object_get_description")] - internal static extern IntPtr GetDescription(VipsObjectManaged @object); + internal static extern nint GetDescription(VipsObjectManaged @object); } [StructLayout(LayoutKind.Sequential)] internal struct VipsArgument { - internal IntPtr Pspec; + internal nint Pspec; } [StructLayout(LayoutKind.Sequential)] internal struct VipsArgumentClass { internal VipsArgument Parent; - internal IntPtr ObjectClass; + internal nint ObjectClass; internal ArgumentFlags Flags; internal int Priority; @@ -281,8 +280,8 @@ internal struct VipsArgumentClass internal struct VipsArgumentInstance { internal VipsArgument Parent; - internal IntPtr ArgumentClass; - internal IntPtr Object; + internal nint ArgumentClass; + internal nint Object; [MarshalAs(UnmanagedType.Bool)] internal bool Assigned; @@ -294,7 +293,7 @@ internal static class VipsBlob { [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_blob_get")] - internal static extern IntPtr Get(VipsBlobManaged blob, out UIntPtr length); + internal static extern nint Get(VipsBlobManaged blob, out nuint length); } internal static class VipsArea @@ -302,26 +301,26 @@ internal static class VipsArea [StructLayout(LayoutKind.Sequential)] internal struct Struct { - internal IntPtr Data; - internal UIntPtr Length; + internal nint Data; + internal nuint Length; internal int N; // private internal int Count; - internal IntPtr Lock; + internal nint Lock; internal Vips.CallbackFn FreeFn; - internal IntPtr Client; + internal nint Client; - internal IntPtr Type; - internal UIntPtr SizeofType; + internal nint Type; + internal nuint SizeofType; } [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_area_unref")] - internal static extern IntPtr Unref(IntPtr blob); + internal static extern nint Unref(nint blob); } internal static class VipsValue @@ -329,7 +328,7 @@ internal static class VipsValue [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_ref_string")] - internal static extern IntPtr GetRefString(in GValue.Struct value, out ulong length); + internal static extern nint GetRefString(in GValue.Struct value, out ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -339,24 +338,24 @@ internal static class VipsValue [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_blob")] - internal static extern IntPtr GetBlob(in GValue.Struct value, out ulong length); + internal static extern nint GetBlob(in GValue.Struct value, out ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_set_blob")] internal static extern void SetBlob(ref GValue.Struct value, Vips.CallbackFn freeFn, - IntPtr data, ulong length); + nint data, ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_set_blob_free")] - internal static extern void SetBlobFree(ref GValue.Struct value, IntPtr data, + internal static extern void SetBlobFree(ref GValue.Struct value, nint data, ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_array_double")] - internal static extern IntPtr GetArrayDouble(in GValue.Struct value, out int n); + internal static extern nint GetArrayDouble(in GValue.Struct value, out int n); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -368,7 +367,7 @@ internal static extern void SetArrayDouble(ref GValue.Struct value, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_array_int")] - internal static extern IntPtr GetArrayInt(in GValue.Struct value, out int n); + internal static extern nint GetArrayInt(in GValue.Struct value, out int n); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -380,7 +379,7 @@ internal static extern void SetArrayInt(ref GValue.Struct value, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_array_image")] - internal static extern IntPtr GetArrayImage(in GValue.Struct value, out int n); + internal static extern nint GetArrayImage(in GValue.Struct value, out int n); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -419,24 +418,24 @@ internal static class VipsImage [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_new_from_memory")] - internal static extern IntPtr NewFromMemory(IntPtr data, UIntPtr size, int width, int height, + internal static extern nint NewFromMemory(nint data, nuint size, int width, int height, int bands, BandFormat format); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_new_from_memory_copy")] - internal static extern IntPtr NewFromMemoryCopy(IntPtr data, UIntPtr size, int width, int height, + internal static extern nint NewFromMemoryCopy(nint data, nuint size, int width, int height, int bands, BandFormat format); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_new_matrix_from_array")] - internal static extern IntPtr NewMatrixFromArray(int width, int height, double[] array, int size); + internal static extern nint NewMatrixFromArray(int width, int height, double[] array, int size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_new_temp_file")] - internal static extern IntPtr NewTempFile(byte[] format); + internal static extern nint NewTempFile(byte[] format); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -446,7 +445,7 @@ internal static extern IntPtr NewFromMemoryCopy(IntPtr data, UIntPtr size, int w [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_write_to_memory")] - internal static extern IntPtr WriteToMemory(Image @in, out ulong size); + internal static extern nint WriteToMemory(Image @in, out ulong size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -457,12 +456,12 @@ internal static extern IntPtr NewFromMemoryCopy(IntPtr data, UIntPtr size, int w [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_addalpha")] - internal static extern int AddAlpha(Image image, out IntPtr @out); + internal static extern int AddAlpha(Image image, out nint @out); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_copy_memory")] - internal static extern IntPtr CopyMemory(Image image); + internal static extern nint CopyMemory(Image image); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_set")] @@ -477,7 +476,7 @@ internal static extern int Get(Image image, [MarshalAs(UnmanagedType.LPStr)] str [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_get_typeof")] - internal static extern IntPtr GetTypeof(Image image, [MarshalAs(UnmanagedType.LPStr)] string name); + internal static extern nint GetTypeof(Image image, [MarshalAs(UnmanagedType.LPStr)] string name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -488,7 +487,7 @@ internal static extern int Get(Image image, [MarshalAs(UnmanagedType.LPStr)] str [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_get_fields")] - internal static extern IntPtr GetFields(Image image); + internal static extern nint GetFields(Image image); } internal static class VipsInterpolate @@ -496,7 +495,7 @@ internal static class VipsInterpolate [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_interpolate_new")] - internal static extern IntPtr New([MarshalAs(UnmanagedType.LPStr)] string nickname); + internal static extern nint New([MarshalAs(UnmanagedType.LPStr)] string nickname); } internal static class VipsRegion @@ -504,12 +503,12 @@ internal static class VipsRegion [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_region_new")] - internal static extern IntPtr New(Image image); + internal static extern nint New(Image image); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_region_fetch")] - internal static extern IntPtr Fetch(Region region, int left, int top, int width, int height, out ulong length); + internal static extern nint Fetch(Region region, int left, int top, int width, int height, out ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -532,17 +531,17 @@ internal static class VipsOperation [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_operation_new")] - internal static extern IntPtr New([MarshalAs(UnmanagedType.LPStr)] string name); + internal static extern nint New([MarshalAs(UnmanagedType.LPStr)] string name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_cache_operation_build")] - internal static extern IntPtr Build(Operation operation); + internal static extern nint Build(Operation operation); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_operation_flags_get_type")] - internal static extern IntPtr FlagsGetType(); + internal static extern nint FlagsGetType(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -556,47 +555,47 @@ internal static class VipsForeign [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load")] - internal static extern IntPtr FindLoad(IntPtr filename); + internal static extern nint FindLoad(nint filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load")] - internal static extern IntPtr FindLoad(byte[] filename); + internal static extern nint FindLoad(byte[] filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load_buffer")] - internal static extern IntPtr FindLoadBuffer(byte[] data, ulong size); + internal static extern nint FindLoadBuffer(byte[] data, ulong size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load_buffer")] - internal static extern IntPtr FindLoadBuffer(IntPtr data, ulong size); + internal static extern nint FindLoadBuffer(nint data, ulong size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load_source")] - internal static extern IntPtr FindLoadSource(Source stream); + internal static extern nint FindLoadSource(Source stream); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_save")] - internal static extern IntPtr FindSave(IntPtr filename); + internal static extern nint FindSave(nint filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_save_buffer")] - internal static extern IntPtr FindSaveBuffer(byte[] name); + internal static extern nint FindSaveBuffer(byte[] name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_save_target")] - internal static extern IntPtr FindSaveTarget(byte[] name); + internal static extern nint FindSaveTarget(byte[] name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_get_suffixes")] - internal static extern IntPtr GetSuffixes(); + internal static extern nint GetSuffixes(); } internal static class VipsConnection @@ -604,11 +603,11 @@ internal static class VipsConnection [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_connection_filename")] - internal static extern IntPtr FileName(Connection connection); + internal static extern nint FileName(Connection connection); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_connection_nick")] - internal static extern IntPtr Nick(Connection connection); + internal static extern nint Nick(Connection connection); } internal static class VipsSource @@ -616,21 +615,21 @@ internal static class VipsSource [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_new_from_descriptor")] - internal static extern IntPtr NewFromDescriptor(int descriptor); + internal static extern nint NewFromDescriptor(int descriptor); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_new_from_file")] - internal static extern IntPtr NewFromFile(byte[] filename); + internal static extern nint NewFromFile(byte[] filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_new_from_memory")] - internal static extern IntPtr NewFromMemory(IntPtr data, UIntPtr size); + internal static extern nint NewFromMemory(nint data, nuint size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_map_blob")] - internal static extern IntPtr MapBlob(Source source); + internal static extern nint MapBlob(Source source); } internal static class VipsSourceCustom @@ -638,13 +637,13 @@ internal static class VipsSourceCustom [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_custom_new")] - internal static extern IntPtr New(); + internal static extern nint New(); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long ReadSignal(IntPtr sourcePtr, IntPtr buffer, long length, IntPtr userDataPtr); + internal delegate long ReadSignal(nint sourcePtr, nint buffer, long length, nint userDataPtr); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long SeekSignal(IntPtr sourcePtr, long offset, int whence, IntPtr userDataPtr); + internal delegate long SeekSignal(nint sourcePtr, long offset, int whence, nint userDataPtr); } internal static class VipsTarget @@ -652,17 +651,17 @@ internal static class VipsTarget [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_target_new_to_descriptor")] - internal static extern IntPtr NewToDescriptor(int descriptor); + internal static extern nint NewToDescriptor(int descriptor); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_target_new_to_file")] - internal static extern IntPtr NewToFile(byte[] filename); + internal static extern nint NewToFile(byte[] filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_target_new_to_memory")] - internal static extern IntPtr NewToMemory(); + internal static extern nint NewToMemory(); } internal static class VipsTargetCustom @@ -670,20 +669,20 @@ internal static class VipsTargetCustom [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_target_custom_new")] - internal static extern IntPtr New(); + internal static extern nint New(); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long WriteSignal(IntPtr targetPtr, + internal delegate long WriteSignal(nint targetPtr, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] - byte[] buffer, int length, IntPtr userDataPtr); + byte[] buffer, int length, nint userDataPtr); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long ReadSignal(IntPtr targetPtr, IntPtr buffer, long length, IntPtr userDataPtr); + internal delegate long ReadSignal(nint targetPtr, nint buffer, long length, nint userDataPtr); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long SeekSignal(IntPtr targetPtr, long offset, int whence, IntPtr userDataPtr); + internal delegate long SeekSignal(nint targetPtr, long offset, int whence, nint userDataPtr); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int EndSignal(IntPtr targetPtr, IntPtr userDataPtr); + internal delegate int EndSignal(nint targetPtr, nint userDataPtr); } } \ No newline at end of file diff --git a/src/NetVips/Interpolate.cs b/src/NetVips/Interpolate.cs index df0777a3..df1c1e0c 100644 --- a/src/NetVips/Interpolate.cs +++ b/src/NetVips/Interpolate.cs @@ -8,12 +8,9 @@ namespace NetVips /// public class Interpolate : VipsObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - private Interpolate(IntPtr pointer) : base(pointer) { - // logger.Debug($"VipsInterpolate = {pointer}"); } /// @@ -36,7 +33,6 @@ private Interpolate(IntPtr pointer) /// If unable to make a new interpolator from . public static Interpolate NewFromName(string name) { - // logger.Debug($"Interpolate.NewFromName: name = {name}"); var vi = VipsInterpolate.New(name); if (vi == IntPtr.Zero) { diff --git a/src/NetVips/Introspect.cs b/src/NetVips/Introspect.cs index e329af14..a717808e 100644 --- a/src/NetVips/Introspect.cs +++ b/src/NetVips/Introspect.cs @@ -15,13 +15,10 @@ namespace NetVips /// public class Introspect { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// A cache for introspection data. /// - private static readonly ConcurrentDictionary IntrospectCache = - new ConcurrentDictionary(); + private static readonly ConcurrentDictionary IntrospectCache = new(); /// /// An object structure that encapsulates the metadata @@ -42,7 +39,7 @@ public struct Argument /// /// The GType for this argument. /// - public IntPtr Type; + public nint Type; } /// @@ -53,27 +50,27 @@ public struct Argument /// /// A bool indicating if this operation is mutable. /// - public bool Mutable; + public readonly bool Mutable; /// /// The required input for this operation. /// - public List RequiredInput = new List(); + public readonly List RequiredInput = new(); /// /// The optional input for this operation. /// - public Dictionary OptionalInput = new Dictionary(); + public readonly Dictionary OptionalInput = new(); /// /// The required output for this operation. /// - public List RequiredOutput = new List(); + public readonly List RequiredOutput = new(); /// /// The optional output for this operation. /// - public Dictionary OptionalOutput = new Dictionary(); + public readonly Dictionary OptionalOutput = new(); /// /// Build introspection data for a specified operation name. @@ -81,7 +78,6 @@ public struct Argument /// The operation name to introspect. private Introspect(string operationName) { - // logger.Debug($"Introspect = {operationName}"); using var op = Operation.NewFromName(operationName); var arguments = GetArgs(op); @@ -189,8 +185,8 @@ void AddArg(string name, Enums.ArgumentFlags flags) } else { - IntPtr AddConstruct(IntPtr self, GParamSpec.Struct pspec, VipsArgumentClass argumentClass, - VipsArgumentInstance argumentInstance, IntPtr a, IntPtr b) + nint AddConstruct(nint self, GParamSpec.Struct pspec, VipsArgumentClass argumentClass, + VipsArgumentInstance argumentInstance, nint a, nint b) { var flags = argumentClass.Flags; if ((flags & Enums.ArgumentFlags.CONSTRUCT) == 0) diff --git a/src/NetVips/Log.cs b/src/NetVips/Log.cs index 4d488a86..223c9d3b 100644 --- a/src/NetVips/Log.cs +++ b/src/NetVips/Log.cs @@ -21,8 +21,8 @@ public static class Log /// The message to process. public delegate void LogDelegate(string logDomain, Enums.LogLevelFlags logLevel, string message); - private static void NativeCallback(IntPtr logDomainNative, Enums.LogLevelFlags flags, IntPtr messageNative, - IntPtr userData) + private static void NativeCallback(nint logDomainNative, Enums.LogLevelFlags flags, nint messageNative, + nint userData) { if (userData == IntPtr.Zero) { @@ -38,7 +38,7 @@ private static void NativeCallback(IntPtr logDomainNative, Enums.LogLevelFlags f } } - private static readonly ConcurrentDictionary _handlers = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary Handlers = new(); /// /// Sets the log handler for a domain and a set of log levels. @@ -52,8 +52,8 @@ public static uint SetLogHandler(string logDomain, Enums.LogLevelFlags flags, Lo _nativeHandler ??= NativeCallback; var gch = GCHandle.Alloc(logFunc); - var result = GLib.GLogSetHandler(logDomain, flags, _nativeHandler, (IntPtr)gch); - _handlers.AddOrUpdate(result, gch, (k, v) => gch); + var result = GLib.GLogSetHandler(logDomain, flags, _nativeHandler, (nint)gch); + Handlers.AddOrUpdate(result, gch, (_, _) => gch); return result; } @@ -64,9 +64,9 @@ public static uint SetLogHandler(string logDomain, Enums.LogLevelFlags flags, Lo /// The id of the handler, which was returned in . public static void RemoveLogHandler(string logDomain, uint handlerId) { - if (_handlers != null && - _handlers.ContainsKey(handlerId) && - _handlers.TryRemove(handlerId, out var handler)) + if (Handlers != null && + Handlers.ContainsKey(handlerId) && + Handlers.TryRemove(handlerId, out var handler)) { handler.Free(); } diff --git a/src/NetVips/ModuleInitializer.cs b/src/NetVips/ModuleInitializer.cs index e428d4c7..e78fa8d4 100644 --- a/src/NetVips/ModuleInitializer.cs +++ b/src/NetVips/ModuleInitializer.cs @@ -36,8 +36,7 @@ public static class ModuleInitializer /// /// A cache for . /// - internal static readonly Dictionary DllImportCache = - new Dictionary(); + internal static readonly Dictionary DllImportCache = new(); internal static string RemapLibraryName(string libraryName) { @@ -64,7 +63,7 @@ internal static string RemapLibraryName(string libraryName) : "libvips.so.42"; } - internal static IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) + internal static nint DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) { libraryName = RemapLibraryName(libraryName); if (DllImportCache.TryGetValue(libraryName, out var cachedHandle)) diff --git a/src/NetVips/MutableImage.cs b/src/NetVips/MutableImage.cs index cebac667..cc44a804 100644 --- a/src/NetVips/MutableImage.cs +++ b/src/NetVips/MutableImage.cs @@ -41,7 +41,7 @@ internal MutableImage(Image copiedImage) : base(copiedImage.ObjectRef()) /// The name of the piece of metadata to create. /// The value to set as a C# value. It is /// converted to the GType, if possible. - public new void Set(IntPtr gtype, string name, object value) + public new void Set(nint gtype, string name, object value) { using var gv = new GValue(); gv.SetType(gtype); @@ -66,7 +66,7 @@ public void Set(string name, object value) if (gtype == IntPtr.Zero) { throw new ArgumentException( - $"metadata item {name} does not exist - use the Set(IntPtr, string, object) overload to create and set"); + $"metadata item {name} does not exist - use the Set(nint, string, object) overload to create and set"); } Set(gtype, name, value); diff --git a/src/NetVips/NetVips.cs b/src/NetVips/NetVips.cs index c99f1100..75aacd0e 100644 --- a/src/NetVips/NetVips.cs +++ b/src/NetVips/NetVips.cs @@ -257,7 +257,7 @@ public static int Version(int flag, bool fromModule = true) } } - if (flag < 0 || flag > 2) + if (flag is < 0 or > 2) { throw new ArgumentOutOfRangeException(nameof(flag), "Flag must be in the range of 0 to 2"); } @@ -308,7 +308,7 @@ public static string[] GetSuffixes() var names = new List(); var count = 0; - IntPtr strPtr; + nint strPtr; while ((strPtr = Marshal.ReadIntPtr(ptrArr, count * IntPtr.Size)) != IntPtr.Zero) { var name = Marshal.PtrToStringAnsi(strPtr); @@ -391,7 +391,7 @@ internal static void VipsOperationFlagsGetType() /// Name of base class. /// Search for a class with this nickname. /// The GType of the class, or if the class is not found. - public static IntPtr TypeFind(string basename, string nickname) + public static nint TypeFind(string basename, string nickname) { return Vips.TypeFind(basename, nickname); } @@ -401,7 +401,7 @@ public static IntPtr TypeFind(string basename, string nickname) /// /// Type to return name for. /// Type name. - public static string TypeName(IntPtr type) + public static string TypeName(nint type) { return Marshal.PtrToStringAnsi(GType.Name(type)); } @@ -411,7 +411,7 @@ public static string TypeName(IntPtr type) /// /// Type to return nickname for. /// Nickname. - public static string NicknameFind(IntPtr type) + public static string NicknameFind(nint type) { return Marshal.PtrToStringAnsi(Vips.NicknameFind(type)); } @@ -428,7 +428,7 @@ public static List GetOperations() var allNickNames = new List(); var handle = GCHandle.Alloc(allNickNames); - IntPtr TypeMap(IntPtr type, IntPtr a, IntPtr b) + nint TypeMap(nint type, nint a, nint b) { var nickname = NicknameFind(type); @@ -469,7 +469,7 @@ public static List GetEnums() var allEnums = new List(); var handle = GCHandle.Alloc(allEnums); - IntPtr TypeMap(IntPtr type, IntPtr a, IntPtr b) + nint TypeMap(nint type, nint a, nint b) { var nickname = TypeName(type); @@ -499,7 +499,7 @@ IntPtr TypeMap(IntPtr type, IntPtr a, IntPtr b) /// /// Type to return enum values for. /// A list of values. - public static Dictionary ValuesForEnum(IntPtr type) + public static Dictionary ValuesForEnum(nint type) { var typeClass = GType.ClassRef(type); var enumClass = Marshal.PtrToStructure(typeClass); @@ -525,7 +525,7 @@ public static Dictionary ValuesForEnum(IntPtr type) /// /// Type name to lookup. /// Corresponding type ID or . - public static IntPtr TypeFromName(string name) + public static nint TypeFromName(string name) { return GType.FromName(name); } @@ -535,7 +535,7 @@ public static IntPtr TypeFromName(string name) /// /// A valid type ID. /// Fundamental type ID. - public static IntPtr FundamentalType(IntPtr type) + public static nint FundamentalType(nint type) { return GType.Fundamental(type); } @@ -547,7 +547,7 @@ public static IntPtr FundamentalType(IntPtr type) /// This is needed for . /// /// The memory to free. - public static void Free(IntPtr mem) + public static void Free(nint mem) { GLib.GFree(mem); } diff --git a/src/NetVips/Operation.cs b/src/NetVips/Operation.cs index 05fc4615..d7778618 100644 --- a/src/NetVips/Operation.cs +++ b/src/NetVips/Operation.cs @@ -8,13 +8,10 @@ namespace NetVips /// public class Operation : VipsObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// private Operation(IntPtr pointer) : base(pointer) { - // logger.Debug($"Operation = {pointer}"); } /// @@ -45,10 +42,8 @@ public static Operation NewFromName(string operationName) /// A used as guide. /// The value. /// The GType of the property. - private void Set(IntPtr gtype, Image matchImage, string name, object value) + private void Set(nint gtype, Image matchImage, string name, object value) { - // logger.Debug($"Operation.Set: name = {name}, matchImage = {matchImage}, value = {value}"); - // if the object wants an image and we have a constant, Imageize it // // if the object wants an image array, Imageize any constants in the @@ -61,7 +56,7 @@ private void Set(IntPtr gtype, Image matchImage, string name, object value) } else if (gtype == GValue.ArrayImageType) { - if (!(value is Array values) || values.Rank != 1) + if (value is not Array { Rank: 1 } values) { throw new ArgumentException( $"unsupported value type {value.GetType()} for VipsArrayImage"); @@ -138,14 +133,9 @@ public static object Call(string operationName, VOption kwargs = null, params ob public static object Call(string operationName, VOption kwargs = null, Image matchImage = null, params object[] args) { - // logger.Debug($"Operation.call: operationName = {operationName}"); - // logger.Debug($"Operation.call: matchImage = {matchImage}"); - // logger.Debug($"Operation.call: args = {args}, kwargs = {kwargs}"); - // pull out the special string_options kwarg object stringOptions = null; kwargs?.Remove("string_options", out stringOptions); - // logger.Debug($"Operation.call: stringOptions = {stringOptions}"); var intro = Introspect.Get(operationName); if (intro.RequiredInput.Count != args.Length) @@ -159,7 +149,7 @@ public static object Call(string operationName, VOption kwargs = null, Image mat throw new VipsException($"unable to call {operationName}: operation must be mutable"); } - IntPtr vop; + nint vop; using (var op = NewFromName(operationName)) { // set any string options before any args so they can't be @@ -248,8 +238,6 @@ public static object Call(string operationName, VOption kwargs = null, Image mat Internal.VipsObject.UnrefOutputs(op); } - // logger.Debug($"Operation.call: result = {result}"); - return results.Length == 1 ? results[0] : results; } diff --git a/src/NetVips/Region.cs b/src/NetVips/Region.cs index 54b3adf8..47e6649f 100644 --- a/src/NetVips/Region.cs +++ b/src/NetVips/Region.cs @@ -14,12 +14,9 @@ namespace NetVips /// public class Region : VipsObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - private Region(IntPtr pointer) : base(pointer) { - // logger.Debug($"Region = {pointer}"); } /// @@ -30,7 +27,6 @@ private Region(IntPtr pointer) /// If unable to make a new region on . public static Region New(Image image) { - // logger.Debug($"Region.New: image = {image}"); var vi = VipsRegion.New(image); if (vi == IntPtr.Zero) { diff --git a/src/NetVips/Source.cs b/src/NetVips/Source.cs index 7695020f..d53d344c 100644 --- a/src/NetVips/Source.cs +++ b/src/NetVips/Source.cs @@ -9,8 +9,6 @@ namespace NetVips /// public class Source : Connection { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Secret ref for . /// @@ -39,8 +37,6 @@ internal Source(IntPtr pointer) /// If unable to create a new from . public static Source NewFromDescriptor(int descriptor) { - // logger.Debug($"Source.NewFromDescriptor: descriptor = {descriptor}"); - var pointer = Internal.VipsSource.NewFromDescriptor(descriptor); if (pointer == IntPtr.Zero) { @@ -65,8 +61,6 @@ public static Source NewFromDescriptor(int descriptor) /// If unable to create a new from . public static Source NewFromFile(string filename) { - // logger.Debug($"Source.NewFromFile: filename = {filename}"); - var bytes = Encoding.UTF8.GetBytes(filename + char.MinValue); // Ensure null-terminated string var pointer = Internal.VipsSource.NewFromFile(bytes); if (pointer == IntPtr.Zero) @@ -92,11 +86,8 @@ public static Source NewFromFile(string filename) /// If unable to create a new from . public static Source NewFromMemory(byte[] data) { - // logger.Debug($"Source.NewFromMemory"); - var handle = GCHandle.Alloc(data, GCHandleType.Pinned); - var pointer = Internal.VipsSource.NewFromMemory(handle.AddrOfPinnedObject(), (UIntPtr)data.Length); - + var pointer = Internal.VipsSource.NewFromMemory(handle.AddrOfPinnedObject(), (nuint)data.Length); if (pointer == IntPtr.Zero) { if (handle.IsAllocated) diff --git a/src/NetVips/SourceCustom.cs b/src/NetVips/SourceCustom.cs index 59ede810..b9f428c3 100644 --- a/src/NetVips/SourceCustom.cs +++ b/src/NetVips/SourceCustom.cs @@ -1,6 +1,5 @@ namespace NetVips { - using System; using System.IO; using System.Buffers; using System.Runtime.InteropServices; @@ -10,8 +9,6 @@ namespace NetVips /// public class SourceCustom : Source { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// A read delegate. /// @@ -69,7 +66,7 @@ public SourceCustom() : base(Internal.VipsSourceCustom.New()) /// The maximum number of bytes to be read. /// User data associated with the source. /// The total number of bytes read into the buffer. - internal long ReadHandler(IntPtr sourcePtr, IntPtr buffer, long length, IntPtr userDataPtr) + internal long ReadHandler(nint sourcePtr, nint buffer, long length, nint userDataPtr) { if (length <= 0) { @@ -112,7 +109,7 @@ internal long ReadHandler(IntPtr sourcePtr, IntPtr buffer, long length, IntPtr u /// reference point used to obtain the new position. /// User data associated with the source. /// The new position within the current source. - internal long SeekHandler(IntPtr sourcePtr, long offset, int whence, IntPtr userDataPtr) + internal long SeekHandler(nint sourcePtr, long offset, int whence, nint userDataPtr) { var newPosition = OnSeek?.Invoke(offset, (SeekOrigin)whence); return newPosition ?? -1; diff --git a/src/NetVips/SourceStream.cs b/src/NetVips/SourceStream.cs index a58f77e7..d8663f8b 100644 --- a/src/NetVips/SourceStream.cs +++ b/src/NetVips/SourceStream.cs @@ -8,8 +8,6 @@ namespace NetVips /// internal class SourceStream : SourceCustom { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Read from this stream. /// @@ -23,7 +21,6 @@ internal class SourceStream : SourceCustom /// internal SourceStream(Stream stream) { - // logger.Debug($"SourceStream: stream = {stream}"); var seekable = stream.CanSeek; _stream = stream; @@ -44,8 +41,6 @@ internal SourceStream(Stream stream) /// If is not readable. internal static SourceStream NewFromStream(Stream stream) { - // logger.Debug($"SourceStream.NewFromStream: stream = {stream}"); - if (!stream.CanRead) { throw new ArgumentException("The stream should be readable.", nameof(stream)); @@ -77,17 +72,13 @@ public long Seek(long offset, SeekOrigin origin) { try { - switch (origin) + return origin switch { - case SeekOrigin.Begin: - return _stream.Seek(_startPosition + offset, SeekOrigin.Begin) - _startPosition; - case SeekOrigin.Current: - return _stream.Seek(offset, SeekOrigin.Current) - _startPosition; - case SeekOrigin.End: - return _stream.Seek(offset, SeekOrigin.End) - _startPosition; - default: - return -1; - } + SeekOrigin.Begin => _stream.Seek(_startPosition + offset, SeekOrigin.Begin) - _startPosition, + SeekOrigin.Current => _stream.Seek(offset, SeekOrigin.Current) - _startPosition, + SeekOrigin.End => _stream.Seek(offset, SeekOrigin.End) - _startPosition, + _ => -1 + }; } catch { diff --git a/src/NetVips/Target.cs b/src/NetVips/Target.cs index 9682cce3..9fb3f80c 100644 --- a/src/NetVips/Target.cs +++ b/src/NetVips/Target.cs @@ -8,8 +8,6 @@ namespace NetVips /// public class Target : Connection { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// internal Target(IntPtr pointer) : base(pointer) { @@ -37,8 +35,6 @@ internal Target(IntPtr pointer) : base(pointer) /// If unable to create a new from . public static Target NewToDescriptor(int descriptor) { - // logger.Debug($"Target.NewToDescriptor: descriptor = {descriptor}"); - var pointer = Internal.VipsTarget.NewToDescriptor(descriptor); if (pointer == IntPtr.Zero) { @@ -63,8 +59,6 @@ public static Target NewToDescriptor(int descriptor) /// If unable to create a new from . public static Target NewToFile(string filename) { - // logger.Debug($"Target.NewToFile: filename = {filename}"); - var bytes = Encoding.UTF8.GetBytes(filename + char.MinValue); // Ensure null-terminated string var pointer = Internal.VipsTarget.NewToFile(bytes); if (pointer == IntPtr.Zero) @@ -94,10 +88,7 @@ public static Target NewToFile(string filename) /// If unable to create a new . public static Target NewToMemory() { - // logger.Debug($"Target.NewToMemory"); - var pointer = Internal.VipsTarget.NewToMemory(); - if (pointer == IntPtr.Zero) { throw new VipsException("can't create output target to memory"); diff --git a/src/NetVips/TargetCustom.cs b/src/NetVips/TargetCustom.cs index 335fb0b9..449bc8ee 100644 --- a/src/NetVips/TargetCustom.cs +++ b/src/NetVips/TargetCustom.cs @@ -1,6 +1,5 @@ namespace NetVips { - using System; using System.IO; using System.Buffers; using System.Runtime.InteropServices; @@ -10,8 +9,6 @@ namespace NetVips /// public class TargetCustom : Target { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// A write delegate. /// @@ -107,7 +104,7 @@ public TargetCustom() : base(Internal.VipsTargetCustom.New()) /// The number of bytes to be written to the current target. /// User data associated with the target. /// The total number of bytes written to the target. - internal long WriteHandler(IntPtr targetPtr, byte[] buffer, int length, IntPtr userDataPtr) + internal long WriteHandler(nint targetPtr, byte[] buffer, int length, nint userDataPtr) { var bytesWritten = OnWrite?.Invoke(buffer, length); return bytesWritten ?? -1; @@ -121,7 +118,7 @@ internal long WriteHandler(IntPtr targetPtr, byte[] buffer, int length, IntPtr u /// The maximum number of bytes to be read. /// User data associated with the target. /// The total number of bytes read into the buffer. - internal long ReadHandler(IntPtr targetPtr, IntPtr buffer, long length, IntPtr userDataPtr) + internal long ReadHandler(nint targetPtr, nint buffer, long length, nint userDataPtr) { if (length <= 0) { @@ -164,7 +161,7 @@ internal long ReadHandler(IntPtr targetPtr, IntPtr buffer, long length, IntPtr u /// reference point used to obtain the new position. /// User data associated with the target. /// The new position within the current target. - internal long SeekHandler(IntPtr targetPtr, long offset, int whence, IntPtr userDataPtr) + internal long SeekHandler(nint targetPtr, long offset, int whence, nint userDataPtr) { var newPosition = OnSeek?.Invoke(offset, (SeekOrigin)whence); return newPosition ?? -1; @@ -176,7 +173,7 @@ internal long SeekHandler(IntPtr targetPtr, long offset, int whence, IntPtr user /// The underlying pointer to the target. /// User data associated with the target. /// 0 on success, -1 on error. - internal int EndHandler(IntPtr targetPtr, IntPtr userDataPtr) + internal int EndHandler(nint targetPtr, nint userDataPtr) { return OnEnd?.Invoke() ?? 0; } diff --git a/src/NetVips/TargetStream.cs b/src/NetVips/TargetStream.cs index 0c6fdd56..23a04377 100644 --- a/src/NetVips/TargetStream.cs +++ b/src/NetVips/TargetStream.cs @@ -8,8 +8,6 @@ namespace NetVips /// internal class TargetStream : TargetCustom { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Write to this stream. /// @@ -23,7 +21,6 @@ internal class TargetStream : TargetCustom /// internal TargetStream(Stream stream) { - // logger.Debug($"TargetStream: stream = {stream}"); var readable = stream.CanRead; var seekable = stream.CanSeek; @@ -50,7 +47,6 @@ internal TargetStream(Stream stream) /// If is not writable. internal static TargetStream NewFromStream(Stream stream) { - // logger.Debug($"TargetStream.NewFromStream: stream = {stream}"); if (!stream.CanWrite) { throw new ArgumentException("The stream should be writable.", nameof(stream)); @@ -102,17 +98,13 @@ public long Seek(long offset, SeekOrigin origin) { try { - switch (origin) + return origin switch { - case SeekOrigin.Begin: - return _stream.Seek(_startPosition + offset, SeekOrigin.Begin) - _startPosition; - case SeekOrigin.Current: - return _stream.Seek(offset, SeekOrigin.Current) - _startPosition; - case SeekOrigin.End: - return _stream.Seek(offset, SeekOrigin.End) - _startPosition; - default: - return -1; - } + SeekOrigin.Begin => _stream.Seek(_startPosition + offset, SeekOrigin.Begin) - _startPosition, + SeekOrigin.Current => _stream.Seek(offset, SeekOrigin.Current) - _startPosition, + SeekOrigin.End => _stream.Seek(offset, SeekOrigin.End) - _startPosition, + _ => -1 + }; } catch { diff --git a/src/NetVips/VOption.cs b/src/NetVips/VOption.cs index 8f963ec5..a573cd9d 100644 --- a/src/NetVips/VOption.cs +++ b/src/NetVips/VOption.cs @@ -10,7 +10,7 @@ namespace NetVips /// public class VOption : IEnumerable> { - private readonly Dictionary _internalDictionary = new Dictionary(); + private readonly Dictionary _internalDictionary = new(); /// /// Returns an enumerator that iterates through the . @@ -86,7 +86,7 @@ public void AddIfPresent(string key, T cls) where T : class [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AddIfPresent(string key, T[] array) where T : struct { - if (array != null && array.Length > 0) + if (array is { Length: > 0 }) { _internalDictionary.Add(key, array); } diff --git a/src/NetVips/VipsBlob.cs b/src/NetVips/VipsBlob.cs index 8404721c..135293b3 100644 --- a/src/NetVips/VipsBlob.cs +++ b/src/NetVips/VipsBlob.cs @@ -8,8 +8,6 @@ namespace NetVips /// internal class VipsBlob : SafeHandle { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Initializes a new instance of the class /// with the specified pointer to wrap around. @@ -20,16 +18,14 @@ internal VipsBlob(IntPtr pointer) { // record the pointer we were given to manage SetHandle(pointer); - - // logger.Debug($"VipsBlob = {pointer}"); } /// /// Get the data from a . /// /// Return number of bytes of data. - /// A containing the data. - internal IntPtr GetData(out UIntPtr length) + /// A containing the data. + internal nint GetData(out nuint length) { return Internal.VipsBlob.Get(this, out length); } @@ -42,7 +38,6 @@ internal IntPtr GetData(out UIntPtr length) /// in the event of a catastrophic failure, . protected override bool ReleaseHandle() { - // logger.Debug($"Unref: VipsBlob = {handle}"); if (!IsInvalid) { // Free the VipsArea @@ -61,7 +56,7 @@ protected override bool ReleaseHandle() /// /// Get the number of bytes of data. /// - internal ulong Length => (ulong)Marshal.PtrToStructure(handle).Length; + internal ulong Length => Marshal.PtrToStructure(handle).Length; /// /// Get the reference count of the blob. Handy for debugging. diff --git a/src/NetVips/VipsObject.cs b/src/NetVips/VipsObject.cs index 38c9d120..94a71fff 100644 --- a/src/NetVips/VipsObject.cs +++ b/src/NetVips/VipsObject.cs @@ -9,8 +9,6 @@ namespace NetVips /// public class VipsObject : GObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Attach a post-close delegate. This is called on finalization. /// @@ -27,7 +25,6 @@ public event Action OnPostClose internal VipsObject(IntPtr pointer) : base(pointer) { - // logger.Debug($"VipsObject = {pointer}"); } /// @@ -46,7 +43,6 @@ internal static void PrintAll() /// The pspec for this arg. private GParamSpec.Struct? GetPspec(string name) { - // logger.Debug($"GetPspec: this = {this}, name = {name}"); var argument = Internal.VipsObject.GetArgument(this, name, out var pspec, out _, out _); return argument != 0 @@ -64,7 +60,6 @@ internal static void PrintAll() /// The GObject property. internal object Get(string name) { - // logger.Debug($"Get: name = {name}"); var pspec = GetPspec(name); if (!pspec.HasValue) { @@ -88,9 +83,8 @@ internal object Get(string name) /// The name of the property to set. /// The value. /// The GType of the property. - internal void Set(IntPtr gtype, string name, object value) + internal void Set(nint gtype, string name, object value) { - // logger.Debug($"Set: gtype = {gtype}, name = {name}, value = {value}"); using var gv = new GValue(); gv.SetType(gtype); gv.Set(value); @@ -118,11 +112,10 @@ internal bool SetString(string stringOptions) /// Get the GType of a GObject property. /// /// The name of the GType to get the type of. - /// A new instance of initialized to the GType or + /// A new instance of initialized to the GType or /// if the property does not exist. - public IntPtr GetTypeOf(string name) + public nint GetTypeOf(string name) { - // logger.Debug($"GetTypeOf: this = {this}, name = {name}"); var pspec = GetPspec(name); if (!pspec.HasValue) diff --git a/src/NetVips/VipsProgress.cs b/src/NetVips/VipsProgress.cs index 1346aaf4..5734b614 100644 --- a/src/NetVips/VipsProgress.cs +++ b/src/NetVips/VipsProgress.cs @@ -1,6 +1,5 @@ namespace NetVips { - using System; using System.Runtime.InteropServices; /// @@ -35,7 +34,7 @@ public struct VipsProgress /// /// Image we are part of. /// - private IntPtr Im; + private nint Im; /// /// Time we have been running. diff --git a/tests/NetVips.Benchmarks/Config.cs b/tests/NetVips.Benchmarks/Config.cs index e7a3e9c1..b8964a2f 100644 --- a/tests/NetVips.Benchmarks/Config.cs +++ b/tests/NetVips.Benchmarks/Config.cs @@ -1,11 +1,11 @@ namespace NetVips.Benchmarks { + using System.Reflection; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Environments; using BenchmarkDotNet.Exporters; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Toolchains.CsProj; - using System.Reflection; public class Config : ManualConfig { @@ -21,7 +21,7 @@ public Config() .WithToolchain(CsProjCoreToolchain.NetCoreApp70) .WithRuntime(NativeAotRuntime.Net70) .WithId(".NET 7.0 CLI (NativeAOT)") -#elif NET8_0 +#elif NET8_0 .WithToolchain(CsProjCoreToolchain.NetCoreApp80) .WithRuntime(NativeAotRuntime.Net80) .WithId(".NET 8.0 CLI (NativeAOT)") diff --git a/tests/NetVips.Benchmarks/ImageSharp/ConvolutionProcessor.cs b/tests/NetVips.Benchmarks/ImageSharp/ConvolutionProcessor.cs index 826b9f1d..38528677 100644 --- a/tests/NetVips.Benchmarks/ImageSharp/ConvolutionProcessor.cs +++ b/tests/NetVips.Benchmarks/ImageSharp/ConvolutionProcessor.cs @@ -40,15 +40,15 @@ public IImageProcessor CreatePixelSpecificProcessor(Configuratio var type = Type.GetType( "SixLabors.ImageSharp.Processing.Processors.Convolution.ConvolutionProcessor`1, SixLabors.ImageSharp"); Type[] typeArgs = { typeof(TPixel) }; - Type genericType = type.MakeGenericType(typeArgs); + var genericType = type.MakeGenericType(typeArgs); Type[] parameterTypes = { configuration.GetType(), KernelXY.GetType().MakeByRefType(), PreserveAlpha.GetType(), source.GetType(), sourceRectangle.GetType() }; - ConstructorInfo ctor = genericType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, + var ctor = genericType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, parameterTypes, null); - object instance = + var instance = ctor.Invoke(new object[] { configuration, KernelXY, PreserveAlpha, source, sourceRectangle }); return (IImageProcessor)instance; diff --git a/tests/NetVips.Tests/ArithmeticTests.cs b/tests/NetVips.Tests/ArithmeticTests.cs index ee83c371..b63e7a23 100644 --- a/tests/NetVips.Tests/ArithmeticTests.cs +++ b/tests/NetVips.Tests/ArithmeticTests.cs @@ -178,7 +178,7 @@ public void TestFloorDiv() { dynamic FloorDiv(dynamic x, dynamic y) { - if (y is Image rightImage && !(x is Image)) + if (y is Image rightImage && x is not Image) { // There's no __rfloordiv__ & __pow__ equivalent in C# :( return (rightImage.Pow(-1) * x).Floor(); @@ -203,7 +203,7 @@ public void TestPow() { dynamic Pow(dynamic x, dynamic y) { - if (y is Image rightImage && !(x is Image)) + if (y is Image rightImage && x is not Image) { // There's no __rpow__ equivalent in C# :( return rightImage.Wop(x); @@ -365,12 +365,12 @@ public void TestEqual() { dynamic Equal(dynamic x, dynamic y) { - if (y is Image rightImage && !(x is Image)) + if (y is Image rightImage && x is not Image) { return x == rightImage; } - if (x is Image leftImage && !(y is Image)) + if (x is Image leftImage && y is not Image) { return y == leftImage; } @@ -392,12 +392,12 @@ public void TestNotEq() { dynamic NotEq(dynamic x, dynamic y) { - if (y is Image rightImage && !(x is Image)) + if (y is Image rightImage && x is not Image) { return x != rightImage; } - if (x is Image leftImage && !(y is Image)) + if (x is Image leftImage && y is not Image) { return y != leftImage; } @@ -684,7 +684,7 @@ public void TestHoughCircle() var y = (int)maxPos[2]; var vec = hough[x, y]; - var r = Array.IndexOf(vec, vec.Min(d => v)) + 35; + var r = Array.IndexOf(vec, vec.Min(_ => v)) + 35; Assert.Equal(50, x); Assert.Equal(50, y); diff --git a/tests/NetVips.Tests/ColourTests.cs b/tests/NetVips.Tests/ColourTests.cs index 5d21f424..8c03c727 100644 --- a/tests/NetVips.Tests/ColourTests.cs +++ b/tests/NetVips.Tests/ColourTests.cs @@ -96,11 +96,11 @@ public void TestColourspace() var alphaBefore = pixelBefore[1]; var pixelAfter = im[10, 10]; var alphaAfter = pixelAfter[1]; - Assert.True(Math.Abs(alphaAfter - alphaBefore) < 1); + Assert.Equal(alphaBefore, alphaAfter, 1.0); // GREY16 can wind up rather different due to rounding but 8-bit we should hit exactly - Assert.True( - Math.Abs(pixelAfter[0] - pixelBefore[0]) < (monoFmt == Enums.Interpretation.Grey16 ? 30 : 1)); + Assert.Equal(pixelBefore[0], pixelAfter[0], + monoFmt == Enums.Interpretation.Grey16 ? 30.0 : 1.0); } if (NetVips.AtLeastLibvips(8, 8)) @@ -171,7 +171,7 @@ public void TestDECMC() var difference = reference.DECMC(sample); var diffPixel = difference[10, 10]; - Assert.True(Math.Abs(diffPixel[0] - 4.97) < 0.5); + Assert.Equal(4.97, diffPixel[0], 0.5); Assert.Equal(42.0, diffPixel[1], 3); } diff --git a/tests/NetVips.Tests/ConversionTests.cs b/tests/NetVips.Tests/ConversionTests.cs index 2f236ef6..95477fff 100644 --- a/tests/NetVips.Tests/ConversionTests.cs +++ b/tests/NetVips.Tests/ConversionTests.cs @@ -351,11 +351,10 @@ public void TestGravity() {Enums.CompassDirection.NorthWest, new[] {0, 0}} }; - foreach (var kvp in positions) + foreach (var (direction, value) in positions) { - var direction = kvp.Key; - var x = kvp.Value[0]; - var y = kvp.Value[1]; + var x = value[0]; + var y = value[1]; var im2 = im.Gravity(direction, 3, 3); Assert.Equal(new double[] { 255 }, im2[x, y]); Assert.Equal(255.0 / 9.0, im2.Avg()); @@ -489,7 +488,7 @@ public void TestFlatten() // we use float arithetic for int and uint, so the rounding // differs ... don't require huge accuracy - Assert.True(Math.Abs(x - y) < 2); + Assert.Equal(x, y, 2.0); } im = test.Flatten(background: new double[] { 100, 100, 100 }); @@ -506,7 +505,7 @@ public void TestFlatten() var x = zip[0]; var y = zip[1]; - Assert.True(Math.Abs(x - y) < 2); + Assert.Equal(x, y, 2.0); } } } @@ -540,7 +539,7 @@ public void TestPremultiply() // we use float arithetic for int and uint, so the rounding // differs ... don't require huge accuracy - Assert.True(Math.Abs(x - y) < 2); + Assert.Equal(x, y, 2.0); } } } @@ -587,7 +586,7 @@ public void TestUnpremultiply() // we use float arithetic for int and uint, so the rounding // differs ... don't require huge accuracy - Assert.True(Math.Abs(x - y) < 2); + Assert.Equal(x, y, 2.0); } } } @@ -631,7 +630,7 @@ public void TestGamma() // ie. less than 1% error, rounding on 7-bit images // means this is all we can expect - Assert.True(Math.Abs(a - b) < mx / 100.0); + Assert.Equal(a, b, mx / 100.0); } } @@ -653,7 +652,7 @@ public void TestGamma() // ie. less than 1% error, rounding on 7-bit images // means this is all we can expect - Assert.True(Math.Abs(a - b) < mx / 100.0); + Assert.Equal(a, b, mx / 100.0); } } } diff --git a/tests/NetVips.Tests/CreateTests.cs b/tests/NetVips.Tests/CreateTests.cs index 2723a3c4..9bb74c26 100644 --- a/tests/NetVips.Tests/CreateTests.cs +++ b/tests/NetVips.Tests/CreateTests.cs @@ -503,7 +503,7 @@ public void TestText() // quite a large threshold, since we need to work with a huge range of // text rendering systems - Assert.True(Math.Abs(im.Width - 500) < 50); + Assert.Equal(500, im.Width, 50.0); } } diff --git a/tests/NetVips.Tests/ExtensionsTests.cs b/tests/NetVips.Tests/ExtensionsTests.cs index f8821b48..024f1903 100644 --- a/tests/NetVips.Tests/ExtensionsTests.cs +++ b/tests/NetVips.Tests/ExtensionsTests.cs @@ -1,12 +1,12 @@ namespace NetVips.Tests { - using Xunit; - using Xunit.Abstractions; using System; using System.Drawing; using System.Drawing.Imaging; - using System.Runtime.Versioning; using System.Runtime.InteropServices; + using System.Runtime.Versioning; + using Xunit; + using Xunit.Abstractions; using Extensions; using Image = Image; @@ -83,9 +83,7 @@ private static void AssertPixelValue(byte[] expected, Bitmap actual) // Switch from BGR(A) to RGB(A) if (expected.Length > 2) { - var t = pixels[0]; - pixels[0] = pixels[2]; - pixels[2] = t; + (pixels[0], pixels[2]) = (pixels[2], pixels[0]); } Assert.Equal(expected, pixels); diff --git a/tests/NetVips.Tests/ForeignTests.cs b/tests/NetVips.Tests/ForeignTests.cs index 0eb14c3e..06d6b6ce 100644 --- a/tests/NetVips.Tests/ForeignTests.cs +++ b/tests/NetVips.Tests/ForeignTests.cs @@ -184,7 +184,7 @@ void JpegValid(Image im) SaveLoadStream(".jpg", "", _colour, 80); } - var _ = Image.Jpegload(Helper.JpegFile, out var flags); + _ = Image.Jpegload(Helper.JpegFile, out var flags); Assert.Equal(Enums.ForeignFlags.SEQUENTIAL, flags); // see if we have exif parsing: our test image has this field @@ -321,7 +321,7 @@ public void TestTruncated() // but this should fail with a warning, and knock TRUNCATED_FILE out of // the cache - var _ = im.Avg(); + _ = im.Avg(); // now we should open again, but it won't come from cache, it'll reload im = Image.NewFromFile(Helper.TruncatedFile); @@ -390,7 +390,7 @@ public void TestBufferOverload() Assert.Equal(_colour.Width, x.Width); Assert.Equal(_colour.Height, x.Height); Assert.Equal(_colour.Bands, x.Bands); - Assert.True((_colour - x).Abs().Max() <= 0); + Assert.Equal(0, (_colour - x).Abs().Max()); } [SkippableFact] @@ -689,7 +689,7 @@ void BmpValid(Image im) // we should have rgb or rgba for svg files ... different versions of // IM handle this differently. GM even gives 1 band. var x = Image.Magickload(Helper.SvgFile); - Assert.True(x.Bands == 3 || x.Bands == 4 || x.Bands == 1); + Assert.True(x.Bands is 3 or 4 or 1); // density should change size of generated svg x = Image.Magickload(Helper.SvgFile, density: "100"); @@ -780,7 +780,7 @@ public void TestMagickSave() Assert.Equal(x2.Get(delayName), x1.Get(delayName)); Assert.Equal(x2.Get("page-height"), x1.Get("page-height")); // magicks vary in how they handle this ... just pray we are close - Assert.True(Math.Abs((int)x1.Get("gif-loop") - (int)x2.Get("gif-loop")) < 5); + Assert.Equal((int)x1.Get("gif-loop"), (int)x2.Get("gif-loop"), 5.0); } } @@ -814,7 +814,7 @@ void WebpValid(Image im) var x = Image.NewFromFile(Helper.WebpFile); var buf = x.WebpsaveBuffer(lossless: true); var im2 = Image.NewFromBuffer(buf); - Assert.True(Math.Abs(x.Avg() - im2.Avg()) < 1); + Assert.Equal(0, (x - im2).Abs().Max()); // higher Q should mean a bigger buffer var b1 = x.WebpsaveBuffer(q: 10); @@ -1040,16 +1040,16 @@ void PdfValid(Image im) { {"scale", 2} }); - Assert.True(Math.Abs(x.Width * 2 - y.Width) < 2); - Assert.True(Math.Abs(x.Height * 2 - y.Height) < 2); + Assert.Equal(x.Width * 2, y.Width, 2.0); + Assert.Equal(x.Height * 2, y.Height, 2.0); x = Image.NewFromFile(Helper.PdfFile); y = Image.NewFromFile(Helper.PdfFile, kwargs: new VOption { {"dpi", 144} }); - Assert.True(Math.Abs(x.Width * 2 - y.Width) < 2); - Assert.True(Math.Abs(x.Height * 2 - y.Height) < 2); + Assert.Equal(x.Width * 2, y.Width, 2.0); + Assert.Equal(x.Height * 2, y.Height, 2.0); } [SkippableFact] @@ -1155,16 +1155,16 @@ void SvgValid(Image im) {"scale", 2} }); - Assert.True(Math.Abs(x.Width * 2 - y.Width) < 2); - Assert.True(Math.Abs(x.Height * 2 - y.Height) < 2); + Assert.Equal(x.Width * 2, y.Width, 2.0); + Assert.Equal(x.Height * 2, y.Height, 2.0); x = Image.NewFromFile(Helper.SvgFile); y = Image.NewFromFile(Helper.SvgFile, kwargs: new VOption { {"dpi", 144} }); - Assert.True(Math.Abs(x.Width * 2 - y.Width) < 2); - Assert.True(Math.Abs(x.Height * 2 - y.Height) < 2); + Assert.Equal(x.Width * 2, y.Width, 2.0); + Assert.Equal(x.Height * 2, y.Height, 2.0); } [Fact] @@ -1483,7 +1483,7 @@ public void TestHeifsave() //var im2 = Image.NewFromBuffer(buf); // not in fact quite lossless - //Assert.True(Math.Abs(x.Avg() - im2.Avg()) < 3); + //Assert.Equal(x.Avg(), im2.Avg(), 3.0); // higher Q should mean a bigger buffer, needs libheif >= v1.8.0, // see: https://github.com/libvips/libvips/issues/1757 diff --git a/tests/NetVips.Tests/Helper.cs b/tests/NetVips.Tests/Helper.cs index 30d0e81e..b1fcace6 100644 --- a/tests/NetVips.Tests/Helper.cs +++ b/tests/NetVips.Tests/Helper.cs @@ -110,7 +110,7 @@ public static class Helper .Concat(CmykColourspaces) .ToArray(); - public static readonly Dictionary MaxValue = new Dictionary + public static readonly Dictionary MaxValue = new() { { Enums.BandFormat.Uchar, @@ -154,7 +154,7 @@ public static class Helper } }; - public static readonly Dictionary SizeOfFormat = new Dictionary + public static readonly Dictionary SizeOfFormat = new() { { Enums.BandFormat.Uchar, @@ -248,12 +248,12 @@ public static class Helper public static IEnumerable ZipExpand(object x, object y) { // handle singleton list case - if (x is Array xArray && xArray.Length == 1) + if (x is Array { Length: 1 } xArray) { x = xArray.GetValue(0); } - if (y is Array yArray && yArray.Length == 1) + if (y is Array { Length: 1 } yArray) { y = yArray.GetValue(0); } @@ -343,7 +343,7 @@ public static void RunCmp(Image im, int x, int y, Func func) var im2 = (Image)func(im); var v2 = im2[x, y]; - AssertAlmostEqualObjects(v1 is IEnumerable enumerable ? enumerable : new[] { v1 }, v2); + AssertAlmostEqualObjects(v1 as IEnumerable ?? new[] { v1 }, v2); } /// @@ -364,7 +364,7 @@ public static void RunCmp2(Image left, Image right, int x, int y, Func @@ -447,11 +447,11 @@ public static bool Have(string name) internal class ObjectComparerDelta : IEqualityComparer { - private double delta; + private readonly double _delta; public ObjectComparerDelta(double delta) { - this.delta = delta; + _delta = delta; } public new bool Equals(object x, object y) @@ -459,7 +459,7 @@ public ObjectComparerDelta(double delta) var a = Convert.ToDouble(x); var b = Convert.ToDouble(y); - return Math.Abs(a - b) <= delta; + return Math.Abs(a - b) <= _delta; } public int GetHashCode(object obj) diff --git a/tests/NetVips.Tests/HistogramTests.cs b/tests/NetVips.Tests/HistogramTests.cs index e2cad0d1..03f1545d 100644 --- a/tests/NetVips.Tests/HistogramTests.cs +++ b/tests/NetVips.Tests/HistogramTests.cs @@ -117,10 +117,10 @@ public void TestPercent() var pc = im.Percent(90); var msk = im <= pc; - var nSet = (msk.Avg() * msk.Width * msk.Height) / 255.0; + var nSet = msk.Avg() * msk.Width * msk.Height / 255.0; var pcSet = 100 * nSet / (msk.Width * msk.Height); - Assert.True(Math.Abs(pcSet - 90) < 1); + Assert.Equal(90, pcSet, 0.5); } [Fact] @@ -130,7 +130,7 @@ public void TestHistEntropy() var ent = im.HistFind().HistEntropy(); - Assert.Equal(4.37, ent, 2); + Assert.Equal(4.37, ent, 0.01); } [Fact] diff --git a/tests/NetVips.Tests/IoFuncsTests.cs b/tests/NetVips.Tests/IoFuncsTests.cs index a7901f68..4b58f535 100644 --- a/tests/NetVips.Tests/IoFuncsTests.cs +++ b/tests/NetVips.Tests/IoFuncsTests.cs @@ -34,11 +34,11 @@ string[] Split(string path) var cases = new Dictionary { { - "c:\\silly:dir:name\\fr:ed.tif:jpeg:95,,,,c:\\icc\\srgb.icc", + @"c:\silly:dir:name\fr:ed.tif:jpeg:95,,,,c:\icc\srgb.icc", new[] { - "c:\\silly:dir:name\\fr:ed.tif", - "jpeg:95,,,,c:\\icc\\srgb.icc" + @"c:\silly:dir:name\fr:ed.tif", + @"jpeg:95,,,,c:\icc\srgb.icc" } }, { @@ -58,18 +58,18 @@ string[] Split(string path) } }, { - "c:\\program files\\x:hello", + @"c:\program files\x:hello", new[] { - "c:\\program files\\x", + @"c:\program files\x", "hello" } }, { - "C:\\fixtures\\2569067123_aca715a2ee_o.jpg", + @"C:\fixtures\2569067123_aca715a2ee_o.jpg", new[] { - "C:\\fixtures\\2569067123_aca715a2ee_o.jpg", + @"C:\fixtures\2569067123_aca715a2ee_o.jpg", "" } } @@ -107,7 +107,7 @@ public void TestNewFromImage() [Fact] public void TestNewFromMemory() { - var s = Enumerable.Repeat((byte)0, 200).ToArray(); + var s = new byte[200]; var im = Image.NewFromMemory(s, 20, 10, 1, Enums.BandFormat.Uchar); Assert.Equal(20, im.Width); Assert.Equal(10, im.Height); @@ -181,7 +181,7 @@ public void TestFindLoadUtf8() [Fact] public void TestWriteToMemory() { - var s = Enumerable.Repeat((byte)0, 200).ToArray(); + var s = new byte[200]; var im = Image.NewFromMemory(s, 20, 10, 1, Enums.BandFormat.Uchar); var t = im.WriteToMemory(); Assert.True(s.SequenceEqual(t)); @@ -198,14 +198,14 @@ public void TestRegion() Assert.Equal(10, region.Width); Assert.Equal(10, region.Height); - Assert.True(data.Length == 100); + Assert.Equal(100, data.Length); Assert.True(data.All(p => p == 0)); data = region.Fetch(0, 0, 20, 10); Assert.Equal(20, region.Width); Assert.Equal(10, region.Height); - Assert.True(data.Length == 200); + Assert.Equal(200, data.Length); Assert.True(data.All(p => p == 0)); } diff --git a/tests/NetVips.Tests/MorphologyTests.cs b/tests/NetVips.Tests/MorphologyTests.cs index 16a8b97f..778fa3c5 100644 --- a/tests/NetVips.Tests/MorphologyTests.cs +++ b/tests/NetVips.Tests/MorphologyTests.cs @@ -68,7 +68,7 @@ public void TestDilate() public void TestRank() { var im = Image.Black(100, 100); - im = im.Mutate(x=> x.DrawCircle(new double[] { 255 }, 50, 50, 25, fill: true)); + im = im.Mutate(x => x.DrawCircle(new double[] { 255 }, 50, 50, 25, fill: true)); var im2 = im.Rank(3, 3, 8); Assert.Equal(im.Width, im2.Width); Assert.Equal(im.Height, im2.Height); diff --git a/tests/NetVips.Tests/ResampleTests.cs b/tests/NetVips.Tests/ResampleTests.cs index 89d83a71..677d391d 100644 --- a/tests/NetVips.Tests/ResampleTests.cs +++ b/tests/NetVips.Tests/ResampleTests.cs @@ -22,18 +22,12 @@ public ResampleTests(TestsFixture testsFixture, ITestOutputHelper output) /// public Image RunCmplx(Func func, Image image) { - Enums.BandFormat newFormat; - switch (image.Format) + var newFormat = image.Format switch { - case Enums.BandFormat.Float: - newFormat = Enums.BandFormat.Complex; - break; - case Enums.BandFormat.Double: - newFormat = Enums.BandFormat.Dpcomplex; - break; - default: - throw new Exception("run_cmplx: not float or double"); - } + Enums.BandFormat.Float => Enums.BandFormat.Complex, + Enums.BandFormat.Double => Enums.BandFormat.Dpcomplex, + _ => throw new Exception("run_cmplx: not float or double") + }; // tag as complex, run, revert tagging var cmplx = image.Copy(bands: 1, format: newFormat); @@ -154,8 +148,7 @@ public void TestReduce() var x = im.Cast(fmt); var r = x.Reduce(fac, fac, kernel: kernel); - var d = Math.Abs(r.Avg() - im.Avg()); - Assert.True(d < 2); + Assert.Equal(im.Avg(), r.Avg(), 2.0); } } } @@ -176,8 +169,7 @@ public void TestReduce() // Console.WriteLine($"testing kernel = {kernel}"); // Console.WriteLine($"testing const = {@const}"); var shr = im.Reduce(2, 2, kernel: kernel); - var d = Math.Abs(shr.Avg() - im.Avg()); - Assert.Equal(0, d); + Assert.Equal(im.Avg(), shr.Avg()); } } } @@ -204,12 +196,12 @@ public void TestShrink() var im2 = im.Shrink(4, 4); Assert.Equal(Math.Round(im.Width / 4.0), im2.Width); Assert.Equal(Math.Round(im.Height / 4.0), im2.Height); - Assert.True(Math.Abs(im.Avg() - im2.Avg()) < 1); + Assert.Equal(im.Avg(), im2.Avg(), 1.0); im2 = im.Shrink(2.5, 2.5); Assert.Equal(Math.Round(im.Width / 2.5), im2.Width); Assert.Equal(Math.Round(im.Height / 2.5), im2.Height); - Assert.True(Math.Abs(im.Avg() - im2.Avg()) < 1); + Assert.Equal(im.Avg(), im2.Avg(), 1.0); } [SkippableFact] @@ -223,7 +215,7 @@ public void TestThumbnail() // the average shouldn't move too much var imOrig = Image.NewFromFile(Helper.JpegFile); - Assert.True(Math.Abs(imOrig.Avg() - im.Avg()) < 1); + Assert.Equal(imOrig.Avg(), im.Avg(), 1.0); // make sure we always get the right width for (var width = 1000; width >= 1; width -= 13) @@ -248,7 +240,7 @@ public void TestThumbnail() var im1 = Image.Thumbnail(Helper.JpegFile, 100); var buf = File.ReadAllBytes(Helper.JpegFile); var im2 = Image.ThumbnailBuffer(buf, 100); - Assert.True(Math.Abs(im1.Avg() - im2.Avg()) < 1); + Assert.Equal(im1.Avg(), im2.Avg(), 1.0); // OME-TIFF subifd thumbnail support added in 8.10 if (NetVips.AtLeastLibvips(8, 10)) @@ -265,7 +257,7 @@ public void TestThumbnail() im2 = Image.Thumbnail(Helper.OmeFile + "[page=1]", 100); Assert.Equal(100, im2.Width); Assert.Equal(38, im2.Height); - Assert.True((im - im2).Abs().Max() != 0); + Assert.NotEqual(0, (im - im2).Abs().Max()); // should be able to thumbnail entire many-page tiff as a toilet-roll // image