From ba6c431688ff1866c45840fd214cfcd0b76a38d4 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 | 11 +- build/common.props | 2 +- .../NetVips.Samples/Samples/GenerateEnums.cs | 20 ++- .../Samples/GenerateImageClass.cs | 126 +++++++------ .../Samples/GenerateImageOperators.cs | 38 ++-- .../Samples/IdentifyExtension.cs | 5 +- .../NetVips.Samples/Samples/OnePointMosaic.cs | 6 +- .../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/Connection.cs | 4 +- src/NetVips/ExtensionMethods.cs | 2 +- src/NetVips/GObject.cs | 12 +- src/NetVips/GValue.cs | 111 +++++------- src/NetVips/Image.cs | 89 ++++------ src/NetVips/Internal/GLib.cs | 11 +- src/NetVips/Internal/GObject.cs | 59 +++---- src/NetVips/Internal/Vips.cs | 167 +++++++++--------- src/NetVips/Interpolate.cs | 2 +- src/NetVips/Introspect.cs | 19 +- src/NetVips/Log.cs | 8 +- src/NetVips/ModuleInitializer.cs | 5 +- src/NetVips/MutableImage.cs | 4 +- src/NetVips/NetVips.cs | 22 +-- src/NetVips/Operation.cs | 8 +- src/NetVips/Region.cs | 2 +- src/NetVips/Source.cs | 4 +- src/NetVips/SourceCustom.cs | 5 +- src/NetVips/SourceStream.cs | 16 +- src/NetVips/Target.cs | 2 +- src/NetVips/TargetCustom.cs | 9 +- src/NetVips/TargetStream.cs | 16 +- src/NetVips/VOption.cs | 4 +- src/NetVips/VipsBlob.cs | 8 +- src/NetVips/VipsObject.cs | 8 +- src/NetVips/VipsProgress.cs | 5 +- tests/NetVips.Tests/ArithmeticTests.cs | 12 +- tests/NetVips.Tests/ColourTests.cs | 8 +- tests/NetVips.Tests/ConversionTests.cs | 12 +- tests/NetVips.Tests/CreateTests.cs | 2 +- tests/NetVips.Tests/ForeignTests.cs | 26 +-- tests/NetVips.Tests/Helper.cs | 12 +- tests/NetVips.Tests/HistogramTests.cs | 6 +- tests/NetVips.Tests/ResampleTests.cs | 30 ++-- 46 files changed, 465 insertions(+), 548 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 aafd258f..083e5967 100644 --- a/build/Shims.cs +++ b/build/Shims.cs @@ -8,18 +8,13 @@ using Nuke.Common.CI; using Nuke.Common.CI.AppVeyor; using Nuke.Common.CI.GitHubActions; +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 3063a638..ea623163 100644 --- a/build/common.props +++ b/build/common.props @@ -14,7 +14,7 @@ false false - 10 + 11 2 4 diff --git a/samples/NetVips.Samples/Samples/GenerateEnums.cs b/samples/NetVips.Samples/Samples/GenerateEnums.cs index a621568e..7437a9a2 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 a7c014a2..3b337e76 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,7 +119,7 @@ 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.TryGetValue(gtype, out var value)) { @@ -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"); @@ -553,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) @@ -786,15 +776,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, @@ -858,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 0b1fedc0..c1501267 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 e6729e33..a757ba1b 100644 --- a/samples/NetVips.Samples/Samples/IdentifyExtension.cs +++ b/samples/NetVips.Samples/Samples/IdentifyExtension.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using System.Text; namespace NetVips.Samples; @@ -72,9 +71,9 @@ 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/OnePointMosaic.cs b/samples/NetVips.Samples/Samples/OnePointMosaic.cs index 88a9732f..41cc056d 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/RandomCropper.cs b/samples/NetVips.Samples/Samples/RandomCropper.cs index 922527df..c4bdc17f 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 6fbbbd19..0c4c969c 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 e06da2d3..c906b882 100644 --- a/src/NetVips.Extensions/BitmapConverter.cs +++ b/src/NetVips.Extensions/BitmapConverter.cs @@ -20,30 +20,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.") + }; } /// @@ -56,27 +52,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.") + }; } /// @@ -94,9 +87,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; @@ -354,7 +345,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 c17254eb..66e3d1b6 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/Connection.cs b/src/NetVips/Connection.cs index 7a0b45b7..ca250c21 100644 --- a/src/NetVips/Connection.cs +++ b/src/NetVips/Connection.cs @@ -1,5 +1,3 @@ -using System; - namespace NetVips; /// @@ -8,7 +6,7 @@ namespace NetVips; public abstract class Connection : VipsObject { /// - internal Connection(IntPtr pointer) : base(pointer) + internal Connection(nint pointer) : base(pointer) { } diff --git a/src/NetVips/ExtensionMethods.cs b/src/NetVips/ExtensionMethods.cs index 77ea6eee..cb4479b2 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 53836ed8..071a1151 100644 --- a/src/NetVips/GObject.cs +++ b/src/NetVips/GObject.cs @@ -38,7 +38,7 @@ public class GObject : SafeHandle /// instance is garbage-collected, the underlying object is unreferenced. /// /// The pointer to wrap around. - internal GObject(IntPtr pointer) : base(IntPtr.Zero, true) + internal GObject(nint pointer) : base(IntPtr.Zero, true) { // record the pointer we were given to manage SetHandle(pointer); @@ -58,7 +58,7 @@ internal GObject(IntPtr pointer) : base(IntPtr.Zero, true) /// 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 @@ -107,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); @@ -121,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, @@ -153,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) { @@ -177,7 +177,7 @@ internal void ReleaseDelegates(IntPtr data, IntPtr objectPointer) /// /// Increases the reference count of object. /// - internal IntPtr ObjectRef() + internal nint ObjectRef() { return Internal.GObject.Ref(handle); } diff --git a/src/NetVips/GValue.cs b/src/NetVips/GValue.cs index 3ce79a40..74d83436 100644 --- a/src/NetVips/GValue.cs +++ b/src/NetVips/GValue.cs @@ -41,87 +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"); + 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. @@ -171,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); } @@ -250,53 +250,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); } @@ -324,23 +308,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); @@ -354,7 +329,7 @@ public void Set(object value) } else { - int FreeFn(IntPtr a, IntPtr b) + int FreeFn(nint a, nint b) { GLib.GFree(a); @@ -482,7 +457,7 @@ public object Get() /// Get the GType of this GValue. /// /// The GType of this GValue. - public IntPtr GetTypeOf() + public nint GetTypeOf() { return Struct.GType; } diff --git a/src/NetVips/Image.cs b/src/NetVips/Image.cs index 9c614db0..eec4e582 100644 --- a/src/NetVips/Image.cs +++ b/src/NetVips/Image.cs @@ -28,10 +28,10 @@ public partial class Image : VipsObject /// Internal marshaller delegate for . /// [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void EvalMarshalDelegate(IntPtr imagePtr, IntPtr progressPtr, IntPtr userDataPtr); + internal delegate void EvalMarshalDelegate(nint imagePtr, nint progressPtr, nint userDataPtr); /// - internal Image(IntPtr pointer) : base(pointer) + internal Image(nint pointer) : base(pointer) { } @@ -106,26 +106,17 @@ private static Image RunCmplx(Func func, Image image) public static Image Imageize(Image matchImage, object 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") + }; } /// @@ -445,7 +436,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"); @@ -516,7 +507,7 @@ 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]); } } @@ -563,7 +554,7 @@ 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]); } } @@ -661,7 +652,7 @@ 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) { @@ -704,14 +695,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"); @@ -721,7 +712,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. /// @@ -734,14 +725,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"); @@ -1071,9 +1062,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) @@ -1142,9 +1133,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 @@ -1234,7 +1225,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); @@ -2034,7 +2025,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); @@ -2090,9 +2081,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, IntPtr progressPtr, IntPtr userDataPtr) + void EvalMarshal(nint imagePtr, nint progressPtr, nint userDataPtr) { if (imagePtr == IntPtr.Zero || progressPtr == IntPtr.Zero) { @@ -2107,18 +2098,14 @@ void EvalMarshal(IntPtr imagePtr, IntPtr progressPtr, 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 de247c27..a0f6b459 100644 --- a/src/NetVips/Internal/GLib.cs +++ b/src/NetVips/Internal/GLib.cs @@ -1,4 +1,3 @@ -using System; using System.Runtime.InteropServices; using System.Security; using NetVips.Interop; @@ -10,24 +9,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 70a6c8dc..e18b716f 100644 --- a/src/NetVips/Internal/GObject.cs +++ b/src/NetVips/Internal/GObject.cs @@ -1,4 +1,3 @@ -using System; using System.Runtime.InteropServices; using System.Security; using NetVips.Interop; @@ -9,18 +8,18 @@ namespace NetVips.Internal; [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] -internal delegate void GWeakNotify(IntPtr data, IntPtr objectPointer); +internal delegate void GWeakNotify(nint data, nint objectPointer); internal static class GObject { [StructLayout(LayoutKind.Sequential)] internal struct Struct { - internal IntPtr GTypeInstance; + internal nint GTypeInstance; internal uint RefCount; - internal IntPtr QData; + internal nint QData; } [SuppressUnmanagedCodeSecurity] @@ -38,17 +37,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)] @@ -66,13 +65,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 @@ -80,22 +79,22 @@ internal static class GType [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 @@ -104,17 +103,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, @@ -170,7 +169,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, @@ -200,7 +199,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, @@ -213,17 +212,17 @@ internal static class GParamSpec [StructLayout(LayoutKind.Sequential)] internal struct Struct { - internal IntPtr GTypeInstance; + internal nint 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; } @@ -231,11 +230,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 { @@ -244,7 +243,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] @@ -256,6 +255,6 @@ 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 bd296e9c..d85d0919 100644 --- a/src/NetVips/Internal/Vips.cs +++ b/src/NetVips/Internal/Vips.cs @@ -1,4 +1,3 @@ -using System; using System.Runtime.InteropServices; using System.Security; using System.Text; @@ -15,14 +14,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, IntPtr pspec, IntPtr argumentClass, - IntPtr argumentInstance, IntPtr a, IntPtr b); + internal delegate nint ArgumentMapFn(nint @object, nint pspec, nint argumentClass, + nint 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, @@ -57,7 +56,7 @@ internal delegate IntPtr ArgumentMapFn(IntPtr @object, IntPtr pspec, IntPtr argu [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, @@ -138,7 +137,7 @@ internal delegate IntPtr ArgumentMapFn(IntPtr @object, IntPtr pspec, IntPtr argu [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, @@ -158,59 +157,59 @@ internal delegate IntPtr ArgumentMapFn(IntPtr @object, IntPtr pspec, IntPtr argu [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) { @@ -229,7 +228,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] @@ -237,7 +236,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] @@ -258,14 +257,14 @@ 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 VipsArgumentClass { - internal IntPtr Parent; - internal IntPtr ObjectClass; + internal nint Parent; + internal nint ObjectClass; internal ArgumentFlags Flags; internal int Priority; @@ -275,9 +274,9 @@ internal struct VipsArgumentClass [StructLayout(LayoutKind.Sequential)] internal struct VipsArgumentInstance { - internal IntPtr Parent; - internal IntPtr ArgumentClass; - internal IntPtr Object; + internal nint Parent; + internal nint ArgumentClass; + internal nint Object; [MarshalAs(UnmanagedType.Bool)] internal bool Assigned; @@ -289,7 +288,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 @@ -297,26 +296,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 @@ -324,7 +323,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, @@ -334,24 +333,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, @@ -363,7 +362,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, @@ -375,7 +374,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, @@ -414,24 +413,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, @@ -441,7 +440,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, @@ -452,12 +451,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, IntPtr args); + internal static extern int AddAlpha(Image image, out nint @out, nint args); [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")] @@ -472,7 +471,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, @@ -483,7 +482,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 @@ -491,7 +490,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 @@ -499,12 +498,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, @@ -527,17 +526,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, @@ -551,47 +550,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 @@ -599,11 +598,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 @@ -611,21 +610,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 @@ -633,13 +632,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 @@ -647,17 +646,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 @@ -665,19 +664,19 @@ 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 265dc94b..46daf4d2 100644 --- a/src/NetVips/Interpolate.cs +++ b/src/NetVips/Interpolate.cs @@ -8,7 +8,7 @@ namespace NetVips; /// public class Interpolate : VipsObject { - private Interpolate(IntPtr pointer) : base(pointer) + private Interpolate(nint pointer) : base(pointer) { } diff --git a/src/NetVips/Introspect.cs b/src/NetVips/Introspect.cs index 13b3a590..7dc2a210 100644 --- a/src/NetVips/Introspect.cs +++ b/src/NetVips/Introspect.cs @@ -18,8 +18,7 @@ public class Introspect /// /// 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 @@ -40,7 +39,7 @@ public struct Argument /// /// The GType for this argument. /// - public IntPtr Type; + public nint Type; } /// @@ -51,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. @@ -186,8 +185,8 @@ void AddArg(string name, Enums.ArgumentFlags flags) } else { - IntPtr AddConstruct(IntPtr self, IntPtr pspec, IntPtr argumentClass, IntPtr argumentInstance, - IntPtr a, IntPtr b) + nint AddConstruct(nint self, nint pspec, nint argumentClass, nint argumentInstance, + nint a, nint b) { var flags = Marshal.PtrToStructure(argumentClass).Flags; if ((flags & Enums.ArgumentFlags.CONSTRUCT) == 0) diff --git a/src/NetVips/Log.cs b/src/NetVips/Log.cs index b578c283..b235b98d 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,7 +52,7 @@ 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); + var result = GLib.GLogSetHandler(logDomain, flags, _nativeHandler, (nint)gch); Handlers.AddOrUpdate(result, gch, (_, _) => gch); return result; } diff --git a/src/NetVips/ModuleInitializer.cs b/src/NetVips/ModuleInitializer.cs index 98d80b1d..0e210636 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 247624ef..5150397c 100644 --- a/src/NetVips/MutableImage.cs +++ b/src/NetVips/MutableImage.cs @@ -42,7 +42,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); @@ -67,7 +67,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 bc13cffb..ffe83c75 100644 --- a/src/NetVips/NetVips.cs +++ b/src/NetVips/NetVips.cs @@ -129,7 +129,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"); } @@ -180,7 +180,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); @@ -263,7 +263,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); } @@ -273,7 +273,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)); } @@ -283,7 +283,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)); } @@ -300,7 +300,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); @@ -341,7 +341,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); @@ -371,7 +371,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); @@ -397,7 +397,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); } @@ -407,7 +407,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); } @@ -419,7 +419,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 9b3038c0..d95dec7b 100644 --- a/src/NetVips/Operation.cs +++ b/src/NetVips/Operation.cs @@ -9,7 +9,7 @@ namespace NetVips; public class Operation : VipsObject { /// - private Operation(IntPtr pointer) : base(pointer) + private Operation(nint pointer) : base(pointer) { } @@ -41,7 +41,7 @@ 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) { // if the object wants an image and we have a constant, Imageize it // @@ -55,7 +55,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"); @@ -148,7 +148,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 diff --git a/src/NetVips/Region.cs b/src/NetVips/Region.cs index f4a94f05..5cc0670a 100644 --- a/src/NetVips/Region.cs +++ b/src/NetVips/Region.cs @@ -14,7 +14,7 @@ namespace NetVips; /// public class Region : VipsObject { - private Region(IntPtr pointer) : base(pointer) + private Region(nint pointer) : base(pointer) { } diff --git a/src/NetVips/Source.cs b/src/NetVips/Source.cs index c14b8f96..f5aaf643 100644 --- a/src/NetVips/Source.cs +++ b/src/NetVips/Source.cs @@ -15,7 +15,7 @@ public class Source : Connection private GCHandle _dataHandle; /// - internal Source(IntPtr pointer) : base(pointer) + internal Source(nint pointer) : base(pointer) { } @@ -86,7 +86,7 @@ public static Source NewFromFile(string filename) public static Source NewFromMemory(byte[] data) { 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 930bc7e0..f372cf8d 100644 --- a/src/NetVips/SourceCustom.cs +++ b/src/NetVips/SourceCustom.cs @@ -1,4 +1,3 @@ -using System; using System.Buffers; using System.IO; using System.Runtime.InteropServices; @@ -67,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) { @@ -110,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 772d54d4..4fb191b0 100644 --- a/src/NetVips/SourceStream.cs +++ b/src/NetVips/SourceStream.cs @@ -72,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 b296a471..4d66e9af 100644 --- a/src/NetVips/Target.cs +++ b/src/NetVips/Target.cs @@ -9,7 +9,7 @@ namespace NetVips; public class Target : Connection { /// - internal Target(IntPtr pointer) : base(pointer) + internal Target(nint pointer) : base(pointer) { } diff --git a/src/NetVips/TargetCustom.cs b/src/NetVips/TargetCustom.cs index 6330ef37..9722c02e 100644 --- a/src/NetVips/TargetCustom.cs +++ b/src/NetVips/TargetCustom.cs @@ -1,4 +1,3 @@ -using System; using System.Buffers; using System.IO; using System.Runtime.InteropServices; @@ -105,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; @@ -119,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) { @@ -162,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; @@ -174,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 2882d1a1..50afe8cc 100644 --- a/src/NetVips/TargetStream.cs +++ b/src/NetVips/TargetStream.cs @@ -98,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 2de825fe..973fbb2d 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 36394fd8..375f86de 100644 --- a/src/NetVips/VipsBlob.cs +++ b/src/NetVips/VipsBlob.cs @@ -13,7 +13,7 @@ internal class VipsBlob : SafeHandle /// with the specified pointer to wrap around. /// /// The pointer to wrap around. - internal VipsBlob(IntPtr pointer) : base(IntPtr.Zero, true) + internal VipsBlob(nint pointer) : base(IntPtr.Zero, true) { // record the pointer we were given to manage SetHandle(pointer); @@ -23,8 +23,8 @@ internal VipsBlob(IntPtr pointer) : base(IntPtr.Zero, true) /// 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); } @@ -55,7 +55,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 5ad1d9bb..4287cfca 100644 --- a/src/NetVips/VipsObject.cs +++ b/src/NetVips/VipsObject.cs @@ -22,7 +22,7 @@ public event Action OnPostClose } /// - internal VipsObject(IntPtr pointer) : base(pointer) + internal VipsObject(nint pointer) : base(pointer) { } @@ -82,7 +82,7 @@ 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) { using var gv = new GValue(); gv.SetType(gtype); @@ -111,9 +111,9 @@ 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) { var pspec = GetPspec(name); if (!pspec.HasValue) diff --git a/src/NetVips/VipsProgress.cs b/src/NetVips/VipsProgress.cs index 69c90db5..8e692141 100644 --- a/src/NetVips/VipsProgress.cs +++ b/src/NetVips/VipsProgress.cs @@ -1,4 +1,3 @@ -using System; using System.Runtime.InteropServices; namespace NetVips; @@ -36,7 +35,7 @@ public struct VipsProgress /// /// Image we are part of. /// - private IntPtr Im; + private nint Im; /// /// Time we have been running. @@ -66,7 +65,7 @@ public struct VipsProgress /// /// Start time. /// - private IntPtr StartPtr; + private nint StartPtr; /// /// Start time. diff --git a/tests/NetVips.Tests/ArithmeticTests.cs b/tests/NetVips.Tests/ArithmeticTests.cs index 6f4fe96b..dd548932 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; } diff --git a/tests/NetVips.Tests/ColourTests.cs b/tests/NetVips.Tests/ColourTests.cs index 042da781..12d03837 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 56437893..5f33ba3e 100644 --- a/tests/NetVips.Tests/ConversionTests.cs +++ b/tests/NetVips.Tests/ConversionTests.cs @@ -488,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 }); @@ -505,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); } } } @@ -539,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); } } } @@ -586,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); } } } @@ -630,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); } } @@ -652,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 fd04d579..c2092173 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/ForeignTests.cs b/tests/NetVips.Tests/ForeignTests.cs index a9161af6..2ec1df09 100644 --- a/tests/NetVips.Tests/ForeignTests.cs +++ b/tests/NetVips.Tests/ForeignTests.cs @@ -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 24f9adc2..ef168f0b 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 diff --git a/tests/NetVips.Tests/HistogramTests.cs b/tests/NetVips.Tests/HistogramTests.cs index 97813f95..ee894739 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, 1.0); } [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/ResampleTests.cs b/tests/NetVips.Tests/ResampleTests.cs index 2b1e6834..b4139cf3 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))