From b40be216e4c9d9069b7aa5778b51e5116b55285f 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/Shims.cs | 1 - build/common.props | 2 +- samples/NetVips.Samples/Program.cs | 2 +- .../Samples/CaptchaGenerator.cs | 6 +- .../Samples/GenerateImageClass.cs | 84 ++++----- .../Samples/GenerateImageOperators.cs | 14 +- .../NetVips.Samples/Samples/NetworkStream.cs | 3 +- .../NetVips.Samples/Samples/OnePointMosaic.cs | 6 +- samples/NetVips.Samples/Samples/PostClose.cs | 2 +- samples/NetVips.Samples/Samples/Progress.cs | 2 +- .../NetVips.Samples/Samples/RandomCropper.cs | 2 +- src/NetVips.Extensions/BitmapConverter.cs | 48 +++-- src/NetVips/Cache.cs | 2 +- src/NetVips/ExtensionMethods.cs | 2 +- src/NetVips/GObject.cs | 15 +- src/NetVips/GValue.cs | 126 +++++-------- src/NetVips/Image.cs | 91 ++++------ src/NetVips/Internal/GLib.cs | 11 +- src/NetVips/Internal/GObject.cs | 57 +++--- src/NetVips/Internal/Vips.cs | 165 +++++++++--------- src/NetVips/Interpolate.cs | 4 - src/NetVips/Introspect.cs | 20 +-- src/NetVips/Log.cs | 10 +- src/NetVips/ModuleInitializer.cs | 5 +- src/NetVips/MutableImage.cs | 4 +- src/NetVips/NetVips.cs | 20 +-- src/NetVips/Operation.cs | 18 +- src/NetVips/Region.cs | 4 - src/NetVips/Source.cs | 11 +- src/NetVips/SourceCustom.cs | 7 +- src/NetVips/SourceStream.cs | 21 +-- src/NetVips/Target.cs | 9 - src/NetVips/TargetCustom.cs | 11 +- src/NetVips/TargetStream.cs | 20 +-- src/NetVips/VOption.cs | 2 +- src/NetVips/VipsBlob.cs | 11 +- src/NetVips/VipsObject.cs | 13 +- src/NetVips/VipsProgress.cs | 3 +- .../ImageSharp/ConvolutionProcessor.cs | 6 +- tests/NetVips.Tests/ArithmeticTests.cs | 14 +- tests/NetVips.Tests/ForeignTests.cs | 8 +- tests/NetVips.Tests/Helper.cs | 4 +- tests/NetVips.Tests/IoFuncsTests.cs | 4 +- tests/NetVips.Tests/MorphologyTests.cs | 2 +- tests/NetVips.Tests/ResampleTests.cs | 16 +- 45 files changed, 358 insertions(+), 530 deletions(-) diff --git a/build/Shims.cs b/build/Shims.cs index 83736d48..01849141 100644 --- a/build/Shims.cs +++ b/build/Shims.cs @@ -5,7 +5,6 @@ using System.Xml.Linq; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; -using Nuke.Common; using Nuke.Common.CI; using Nuke.Common.CI.AppVeyor; using Nuke.Common.CI.GitHubActions; diff --git a/build/common.props b/build/common.props index b5ec4f4a..a47aaa20 100644 --- a/build/common.props +++ b/build/common.props @@ -14,7 +14,7 @@ false false - 9 + 11 2 4 diff --git a/samples/NetVips.Samples/Program.cs b/samples/NetVips.Samples/Program.cs index c4796da5..ff62eebf 100644 --- a/samples/NetVips.Samples/Program.cs +++ b/samples/NetVips.Samples/Program.cs @@ -33,7 +33,7 @@ static void Main(string[] args) string input; do { - string[] sampleArgs = Array.Empty(); + var sampleArgs = Array.Empty(); if (args.Length > 0) { var sampleId = Samples.Select((value, index) => new { Index = index + 1, value.Name }) diff --git a/samples/NetVips.Samples/Samples/CaptchaGenerator.cs b/samples/NetVips.Samples/Samples/CaptchaGenerator.cs index df50dbc1..88675208 100644 --- a/samples/NetVips.Samples/Samples/CaptchaGenerator.cs +++ b/samples/NetVips.Samples/Samples/CaptchaGenerator.cs @@ -65,7 +65,7 @@ public void Execute(string[] args) using var wobble = Wobble(similarity); // random colour - var colour = Enumerable.Range(1, 3).Select(i => random.Next(0, 255)).ToArray(); + var colour = Enumerable.Range(1, 3).Select(_ => random.Next(0, 255)).ToArray(); using var ifthenelse = wobble.Ifthenelse(colour, 0, blend: true); // tag as 9-bit srgb @@ -101,10 +101,10 @@ public void Execute(string[] args) textLayer = textLayer.Bandjoin(alpha); } - // make a white background with random speckles + // make a white background with random speckles using var speckles = Image.Gaussnoise(textLayer.Width, textLayer.Height, mean: 400, sigma: 200); using var background = Enumerable.Range(1, 2).Aggregate(speckles, - (a, b) => + (a, _) => { using (a) { diff --git a/samples/NetVips.Samples/Samples/GenerateImageClass.cs b/samples/NetVips.Samples/Samples/GenerateImageClass.cs index 847963ba..26d10c8e 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.ContainsKey(gtype)) { @@ -190,29 +190,22 @@ 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) @@ -226,26 +219,23 @@ string ExplicitCast(string type) 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", + { } enumString when enumString.StartsWith("Enums.") => $"{type}? {name} = null", + _ => throw new Exception($"Unsupported type: {type}") + }; } var result = new StringBuilder($"{indent}/// \n"); @@ -555,7 +545,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) diff --git a/samples/NetVips.Samples/Samples/GenerateImageOperators.cs b/samples/NetVips.Samples/Samples/GenerateImageOperators.cs index 8edf4144..2d2babc0 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 readonly string _docstring = $$""" + {{Indent}}/// + {{Indent}}/// This operation {0}. + {{Indent}}/// + {{Indent}}/// {1}. + {{Indent}}/// {2}. + {{Indent}}/// A new . + """; /// /// Make a C#-style docstring + operator overload. diff --git a/samples/NetVips.Samples/Samples/NetworkStream.cs b/samples/NetVips.Samples/Samples/NetworkStream.cs index 9e7333a5..60e655e7 100644 --- a/samples/NetVips.Samples/Samples/NetworkStream.cs +++ b/samples/NetVips.Samples/Samples/NetworkStream.cs @@ -3,7 +3,6 @@ namespace NetVips.Samples using System; using System.IO; using System.Net.Http; - using System.Threading.Tasks; public class NetworkStream : ISample { @@ -39,7 +38,7 @@ public async void Execute(string[] args) using var image = Image.NewFromSource(source, access: Enums.Access.Sequential); Console.WriteLine(image.ToString()); - using var output = File.OpenWrite("stream-network.jpg"); + await using var output = File.OpenWrite("stream-network.jpg"); image.WriteToStream(output, ".jpg"); Console.WriteLine("See stream-network.jpg"); diff --git a/samples/NetVips.Samples/Samples/OnePointMosaic.cs b/samples/NetVips.Samples/Samples/OnePointMosaic.cs index 135b3b85..0bb820c0 100644 --- a/samples/NetVips.Samples/Samples/OnePointMosaic.cs +++ b/samples/NetVips.Samples/Samples/OnePointMosaic.cs @@ -22,7 +22,7 @@ public Point(int x, int y) } } - public List Images = new List + public List Images = new() { "images/cd1.1.jpg", "images/cd1.2.jpg", @@ -34,7 +34,7 @@ public Point(int x, int y) "images/cd4.2.jpg" }; - public List HorizontalMarks = new List + public List HorizontalMarks = new() { new Point(489, 140), new Point(66, 141), @@ -46,7 +46,7 @@ public Point(int x, int y) new Point(40, 57) }; - public List VerticalMarks = new List + public List VerticalMarks = new() { new Point(364, 346), new Point(388, 44), diff --git a/samples/NetVips.Samples/Samples/PostClose.cs b/samples/NetVips.Samples/Samples/PostClose.cs index 670def68..d737e73f 100644 --- a/samples/NetVips.Samples/Samples/PostClose.cs +++ b/samples/NetVips.Samples/Samples/PostClose.cs @@ -19,7 +19,7 @@ public void Execute(string[] args) // Avoid reusing the image after subsequent use Cache.Max = 0; - Action action = OnPostClose; + var action = OnPostClose; var im = Image.NewFromFile(Filename, access: Enums.Access.Sequential); im.OnPostClose += action; diff --git a/samples/NetVips.Samples/Samples/Progress.cs b/samples/NetVips.Samples/Samples/Progress.cs index 32c57537..22420f1d 100644 --- a/samples/NetVips.Samples/Samples/Progress.cs +++ b/samples/NetVips.Samples/Samples/Progress.cs @@ -24,7 +24,7 @@ public void Execute(string[] args) test.SignalConnect(Enums.Signals.Eval, EvalHandler); test.SignalConnect(Enums.Signals.PostEval, PostEvalHandler); - var avg = test.Avg(); + _ = test.Avg(); } private void ProgressPrint(Enums.Signals signal, VipsProgress progress) diff --git a/samples/NetVips.Samples/Samples/RandomCropper.cs b/samples/NetVips.Samples/Samples/RandomCropper.cs index cf32ed35..9c38800b 100644 --- a/samples/NetVips.Samples/Samples/RandomCropper.cs +++ b/samples/NetVips.Samples/Samples/RandomCropper.cs @@ -16,7 +16,7 @@ public class RandomCropper : ISample public const string Filename = "images/equus_quagga.jpg"; - public static readonly Random Rnd = new Random(); + public static readonly Random Rnd = new(); public Image RandomCrop(Image image, int tileSize) { diff --git a/src/NetVips.Extensions/BitmapConverter.cs b/src/NetVips.Extensions/BitmapConverter.cs index 48546d2f..4e63b074 100644 --- a/src/NetVips.Extensions/BitmapConverter.cs +++ b/src/NetVips.Extensions/BitmapConverter.cs @@ -21,30 +21,27 @@ 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; + 1, /*case PixelFormat.Format16bppGrayScale: return 2;*/ /*case PixelFormat.Format1bppIndexed:*/ /*case PixelFormat.Format4bppIndexed:*/ /*case PixelFormat.Format16bppRgb555:*/ /*case PixelFormat.Format16bppRgb565:*/ - case PixelFormat.Format24bppRgb: + PixelFormat.Format24bppRgb => 3, /*case PixelFormat.Format32bppRgb:*/ - case PixelFormat.Format48bppRgb: - return 3; + PixelFormat.Format48bppRgb => 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."); - } + PixelFormat.Format32bppArgb => 4, + PixelFormat.Format32bppPArgb => 4, + PixelFormat.Format64bppArgb => 4, + PixelFormat.Format64bppPArgb => 4, + _ => throw new NotImplementedException($"GuessBands({pixelFormat}) is not yet implemented.") + }; } /// @@ -57,27 +54,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: + PixelFormat.Format8bppIndexed => Enums.BandFormat.Uchar, /*case PixelFormat.Format16bppGrayScale:*/ /*case PixelFormat.Format16bppRgb555:*/ /*case PixelFormat.Format16bppRgb565:*/ - case PixelFormat.Format24bppRgb: + PixelFormat.Format24bppRgb => Enums.BandFormat.Uchar, /*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.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.") + }; } /// diff --git a/src/NetVips/Cache.cs b/src/NetVips/Cache.cs index 7032636d..9e19d235 100644 --- a/src/NetVips/Cache.cs +++ b/src/NetVips/Cache.cs @@ -21,7 +21,7 @@ public static int Max /// public static ulong MaxMem { - get => (ulong) Vips.CacheGetMaxMem(); + get => Vips.CacheGetMaxMem(); set => Vips.CacheSetMaxMem(value); } diff --git a/src/NetVips/ExtensionMethods.cs b/src/NetVips/ExtensionMethods.cs index ea43ef0a..d525c3a2 100644 --- a/src/NetVips/ExtensionMethods.cs +++ b/src/NetVips/ExtensionMethods.cs @@ -104,7 +104,7 @@ internal static object[] PrependImage(this T[] args, Image image) /// If set to , free the GLib string. /// Size of the GLib string, use 0 to read until the null character. /// The managed string. - internal static string ToUtf8String(this IntPtr utf8Str, bool freePtr = false, int size = 0) + internal static string ToUtf8String(this nint utf8Str, bool freePtr = false, int size = 0) { if (utf8Str == IntPtr.Zero) { diff --git a/src/NetVips/GObject.cs b/src/NetVips/GObject.cs index 749b6bf2..db51748b 100644 --- a/src/NetVips/GObject.cs +++ b/src/NetVips/GObject.cs @@ -11,8 +11,6 @@ namespace NetVips /// public class GObject : SafeHandle { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// We have to record all of the delegates to /// prevent them from being re-located or disposed of by the garbage collector. @@ -46,7 +44,6 @@ internal GObject(IntPtr pointer) SetHandle(pointer); // NObjects++; - // logger.Debug($"GObject = {pointer}"); } /// @@ -61,7 +58,7 @@ internal GObject(IntPtr pointer) /// Data to pass to handler calls. /// The handler id. /// If it failed to connect the signal. - public ulong SignalConnect(string detailedSignal, T callback, IntPtr data = default) + public ulong SignalConnect(string detailedSignal, T callback, nint data = default) where T : notnull { // add a weak reference callback to ensure all handles are released on finalization @@ -110,7 +107,7 @@ public void SignalHandlerDisconnect(ulong handlerId) /// The func of the handlers. /// The data of the handlers. /// The number of handlers that matched. - public uint SignalHandlersDisconnectByFunc(T func, IntPtr data = default) + public uint SignalHandlersDisconnectByFunc(T func, nint data = default) where T : notnull { var funcPtr = Marshal.GetFunctionPointerForDelegate(func); @@ -124,7 +121,7 @@ public uint SignalHandlersDisconnectByFunc(T func, IntPtr data = default) /// /// The data of the handlers. /// The number of handlers that matched. - public uint SignalHandlersDisconnectByData(IntPtr data) + public uint SignalHandlersDisconnectByData(nint data) { return GSignal.HandlersDisconnectMatched(this, GSignalMatchType.G_SIGNAL_MATCH_DATA, @@ -139,7 +136,6 @@ public uint SignalHandlersDisconnectByData(IntPtr data) /// in the event of a catastrophic failure, . protected override bool ReleaseHandle() { - // logger.Debug($"Unref: GObject = {handle}"); if (!IsInvalid) { Internal.GObject.Unref(handle); @@ -157,7 +153,7 @@ protected override bool ReleaseHandle() /// /// Data that was provided when the weak reference was established. /// The object being disposed. - internal void ReleaseDelegates(IntPtr data, IntPtr objectPointer) + internal void ReleaseDelegates(nint data, nint objectPointer) { foreach (var gcHandle in _handles) { @@ -181,9 +177,8 @@ internal void ReleaseDelegates(IntPtr data, IntPtr objectPointer) /// /// Increases the reference count of object. /// - internal IntPtr ObjectRef() + internal nint ObjectRef() { - // logger.Debug($"Ref: GObject = {handle}"); return Internal.GObject.Ref(handle); } diff --git a/src/NetVips/GValue.cs b/src/NetVips/GValue.cs index 5dd4ebe6..cb632a3e 100644 --- a/src/NetVips/GValue.cs +++ b/src/NetVips/GValue.cs @@ -21,8 +21,6 @@ namespace NetVips /// public class GValue : IDisposable { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// The specified struct to wrap around. /// @@ -43,92 +41,87 @@ public class GValue : IDisposable /// /// The fundamental type corresponding to gboolean. /// - public static readonly IntPtr GBoolType = new IntPtr(5 << FundamentalShift); + public static readonly nint GBoolType = 5 << FundamentalShift; /// /// The fundamental type corresponding to gint. /// - public static readonly IntPtr GIntType = new IntPtr(6 << FundamentalShift); + public static readonly nint GIntType = 6 << FundamentalShift; /// /// The fundamental type corresponding to guint64. /// - public static readonly IntPtr GUint64Type = new IntPtr(11 << FundamentalShift); + public static readonly nint GUint64Type = 11 << FundamentalShift; /// /// The fundamental type from which all enumeration types are derived. /// - public static readonly IntPtr GEnumType = new IntPtr(12 << FundamentalShift); + public static readonly nint GEnumType = 12 << FundamentalShift; /// /// The fundamental type from which all flags types are derived. /// - public static readonly IntPtr GFlagsType = new IntPtr(13 << FundamentalShift); + public static readonly nint GFlagsType = 13 << FundamentalShift; /// /// The fundamental type corresponding to gdouble. /// - public static readonly IntPtr GDoubleType = new IntPtr(15 << FundamentalShift); + public static readonly nint GDoubleType = 15 << FundamentalShift; /// /// The fundamental type corresponding to null-terminated C strings. /// - public static readonly IntPtr GStrType = new IntPtr(16 << FundamentalShift); + public static readonly nint GStrType = 16 << FundamentalShift; /// /// The fundamental type for GObject. /// - public static readonly IntPtr GObjectType = new IntPtr(20 << FundamentalShift); + public static readonly nint GObjectType = 20 << FundamentalShift; /// /// The fundamental type for VipsImage. /// - public static readonly IntPtr ImageType = NetVips.TypeFromName("VipsImage"); + public static readonly nint ImageType = NetVips.TypeFromName("VipsImage"); /// /// The fundamental type for VipsArrayInt. /// - public static readonly IntPtr ArrayIntType = NetVips.TypeFromName("VipsArrayInt"); + public static readonly nint ArrayIntType = NetVips.TypeFromName("VipsArrayInt"); /// /// The fundamental type for VipsArrayDouble. /// - public static readonly IntPtr ArrayDoubleType = NetVips.TypeFromName("VipsArrayDouble"); + public static readonly nint ArrayDoubleType = NetVips.TypeFromName("VipsArrayDouble"); /// /// The fundamental type for VipsArrayImage. /// - public static readonly IntPtr ArrayImageType = NetVips.TypeFromName("VipsArrayImage"); + public static readonly nint ArrayImageType = NetVips.TypeFromName("VipsArrayImage"); /// /// The fundamental type for VipsRefString. /// - public static readonly IntPtr RefStrType = NetVips.TypeFromName("VipsRefString"); + public static readonly nint RefStrType = NetVips.TypeFromName("VipsRefString"); /// /// The fundamental type for VipsBlob. /// - public static readonly IntPtr BlobType = NetVips.TypeFromName("VipsBlob"); - - /// - /// The fundamental type for VipsBandFormat. See . - /// - public static readonly IntPtr BandFormatType = Vips.BandFormatGetType(); + public static readonly nint BlobType = NetVips.TypeFromName("VipsBlob"); /// /// The fundamental type for VipsBlendMode. See . /// - public static readonly IntPtr BlendModeType; + public static readonly nint BlendModeType; /// /// The fundamental type for VipsSource. See . /// - public static readonly IntPtr SourceType; + public static readonly nint SourceType; /// /// The fundamental type for VipsTarget. See . /// - public static readonly IntPtr TargetType; + public static readonly nint TargetType; /// /// Hint of how much native memory is actually occupied by the object. @@ -155,7 +148,6 @@ static GValue() public GValue() { Struct = new Internal.GValue.Struct(); - // logger.Debug($"GValue = {Struct}"); } /// @@ -166,7 +158,6 @@ public GValue() internal GValue(Internal.GValue.Struct value) { Struct = value; - // logger.Debug($"GValue = {Struct}"); } /// @@ -180,7 +171,7 @@ internal GValue(Internal.GValue.Struct value) /// TypeFind. /// /// Type the GValue should hold values of. - public void SetType(IntPtr gtype) + public void SetType(nint gtype) { Internal.GValue.Init(ref Struct, gtype); } @@ -214,7 +205,6 @@ private void AddMemoryPressure(long bytesAllocated) /// Value to be set. public void Set(object value) { - // logger.Debug($"Set: value = {value}"); var gtype = GetTypeOf(); var fundamental = GType.Fundamental(gtype); if (gtype == GBoolType) @@ -258,53 +248,37 @@ public void Set(object value) } else if (gtype == ArrayIntType) { - if (!(value is IEnumerable)) + if (value is not IEnumerable) { value = new[] { value }; } - int[] integers; - switch (value) + var integers = value switch { - case int[] ints: - integers = ints; - break; - case double[] doubles: - integers = Array.ConvertAll(doubles, Convert.ToInt32); - break; - case object[] objects: - integers = Array.ConvertAll(objects, Convert.ToInt32); - break; - default: - throw new ArgumentException( - $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}"); - } + int[] ints => ints, + double[] doubles => Array.ConvertAll(doubles, Convert.ToInt32), + object[] objects => Array.ConvertAll(objects, Convert.ToInt32), + _ => throw new ArgumentException( + $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}") + }; VipsValue.SetArrayInt(ref Struct, integers, integers.Length); } else if (gtype == ArrayDoubleType) { - if (!(value is IEnumerable)) + if (value is not IEnumerable) { value = new[] { value }; } - double[] doubles; - switch (value) + var doubles = value switch { - case double[] dbls: - doubles = dbls; - break; - case int[] ints: - doubles = Array.ConvertAll(ints, Convert.ToDouble); - break; - case object[] objects: - doubles = Array.ConvertAll(objects, Convert.ToDouble); - break; - default: - throw new ArgumentException( - $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}"); - } + double[] dbls => dbls, + int[] ints => Array.ConvertAll(ints, Convert.ToDouble), + object[] objects => Array.ConvertAll(objects, Convert.ToDouble), + _ => throw new ArgumentException( + $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}") + }; VipsValue.SetArrayDouble(ref Struct, doubles, doubles.Length); } @@ -332,23 +306,14 @@ public void Set(object value) } else if (gtype == BlobType) { - byte[] memory; - - switch (value) + var memory = value switch { - case string strValue: - memory = Encoding.UTF8.GetBytes(strValue); - break; - case char[] charArrValue: - memory = Encoding.UTF8.GetBytes(charArrValue); - break; - case byte[] byteArrValue: - memory = byteArrValue; - break; - default: - throw new ArgumentException( - $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}"); - } + string strValue => Encoding.UTF8.GetBytes(strValue), + char[] charArrValue => Encoding.UTF8.GetBytes(charArrValue), + byte[] byteArrValue => byteArrValue, + _ => throw new ArgumentException( + $"unsupported value type {value.GetType()} for gtype {NetVips.TypeName(gtype)}") + }; // We need to set the blob to a copy of the string that vips can own var ptr = GLib.GMalloc((ulong)memory.Length); @@ -362,7 +327,7 @@ public void Set(object value) } else { - int FreeFn(IntPtr a, IntPtr b) + int FreeFn(nint a, nint b) { GLib.GFree(a); @@ -388,7 +353,6 @@ int FreeFn(IntPtr a, IntPtr b) /// The contents of this GValue. public object Get() { - // logger.Debug($"Get: this = {this}"); var gtype = GetTypeOf(); var fundamental = GType.Fundamental(gtype); @@ -491,7 +455,7 @@ public object Get() /// Get the GType of this GValue. /// /// The GType of this GValue. - public IntPtr GetTypeOf() + public nint GetTypeOf() { return Struct.GType; } @@ -516,8 +480,6 @@ public IntPtr GetTypeOf() /// to release only unmanaged resources. protected void Dispose(bool disposing) { - // logger.Debug($"GC: GValue = {Struct}"); - // Check to see if Dispose has already been called. if (!_disposed) { @@ -533,8 +495,6 @@ protected void Dispose(bool disposing) // Note disposing has been done. _disposed = true; } - - // logger.Debug($"GC: GValue = {Struct}"); } /// diff --git a/src/NetVips/Image.cs b/src/NetVips/Image.cs index 24266805..928eb26c 100644 --- a/src/NetVips/Image.cs +++ b/src/NetVips/Image.cs @@ -14,8 +14,6 @@ namespace NetVips /// public partial class Image : VipsObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// A evaluation delegate that can be used on the /// , and @@ -30,13 +28,12 @@ public partial class Image : VipsObject /// Internal marshaller delegate for . /// [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void EvalMarshalDelegate(IntPtr imagePtr, VipsProgress progress, IntPtr userDataPtr); + internal delegate void EvalMarshalDelegate(nint imagePtr, VipsProgress progress, nint userDataPtr); /// internal Image(IntPtr pointer) : base(pointer) { - // logger.Debug($"VipsImage = {pointer}"); } #region helpers @@ -109,28 +106,18 @@ private static Image RunCmplx(Func func, Image image) /// A new . public static Image Imageize(Image matchImage, object value) { - // logger.Debug($"Imageize: value = {value}"); // careful! this can be None if value is a 2D array - switch (value) - { - case Image image: - return image; - case double[,] doubleArray: - return NewFromArray(doubleArray); - case int[,] intArray: - return NewFromArray(intArray); - case double[] doubles: - return matchImage.NewFromImage(doubles); - case int[] ints: - return matchImage.NewFromImage(ints); - case double doubleValue: - return matchImage.NewFromImage(doubleValue); - case int intValue: - return matchImage.NewFromImage(intValue); - default: - throw new ArgumentException( - $"unsupported value type {value.GetType()} for Imageize"); - } + return value switch + { + Image image => image, + double[,] doubleArray => NewFromArray(doubleArray), + int[,] intArray => NewFromArray(intArray), + double[] doubles => matchImage.NewFromImage(doubles), + int[] ints => matchImage.NewFromImage(ints), + double doubleValue => matchImage.NewFromImage(doubleValue), + int intValue => matchImage.NewFromImage(intValue), + _ => throw new ArgumentException($"unsupported value type {value.GetType()} for Imageize") + }; } /// @@ -450,7 +437,7 @@ public static Image NewFromSource( using var blob = new VipsBlob(ptr); var buf = blob.GetData(out var length); - operationName = Marshal.PtrToStringAnsi(VipsForeign.FindLoadBuffer(buf, (ulong)length)); + operationName = Marshal.PtrToStringAnsi(VipsForeign.FindLoadBuffer(buf, length)); if (operationName == null) { throw new VipsException("unable to load from source"); @@ -527,7 +514,6 @@ public static Image NewFromArray(T[,] array, double scale = 1.0, double offse } var vi = VipsImage.NewMatrixFromArray(width, height, a, n); - if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from matrix"); @@ -575,7 +561,6 @@ public static Image NewFromArray(T[][] array, double scale = 1.0, double offs } var vi = VipsImage.NewMatrixFromArray(width, height, a, n); - if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from matrix"); @@ -618,7 +603,6 @@ public static Image NewFromArray(T[] array, double scale = 1.0, double offset } var vi = VipsImage.NewMatrixFromArray(1, height, a, height); - if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from matrix"); @@ -669,9 +653,8 @@ public static Image NewFromMemory( Enums.BandFormat format) { var handle = GCHandle.Alloc(data, GCHandleType.Pinned); - var vi = VipsImage.NewFromMemory(handle.AddrOfPinnedObject(), (UIntPtr)data.Length, width, height, bands, + var vi = VipsImage.NewFromMemory(handle.AddrOfPinnedObject(), (nuint)data.Length, width, height, bands, format); - if (vi == IntPtr.Zero) { if (handle.IsAllocated) @@ -713,15 +696,14 @@ public static Image NewFromMemory( /// A new . /// If unable to make image from . public static Image NewFromMemory( - IntPtr data, + nint data, ulong size, int width, int height, int bands, Enums.BandFormat format) { - var vi = VipsImage.NewFromMemory(data, (UIntPtr)size, width, height, bands, format); - + var vi = VipsImage.NewFromMemory(data, (nuint)size, width, height, bands, format); if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from memory"); @@ -731,7 +713,7 @@ public static Image NewFromMemory( } /// - /// Like , but libvips + /// Like , but libvips /// will make a copy of the memory area. This means more memory use and an extra copy /// operation, but is much simpler and safer. /// @@ -744,15 +726,14 @@ public static Image NewFromMemory( /// A new . /// If unable to make image from . public static Image NewFromMemoryCopy( - IntPtr data, + nint data, ulong size, int width, int height, int bands, Enums.BandFormat format) { - var vi = VipsImage.NewFromMemoryCopy(data, (UIntPtr)size, width, height, bands, format); - + var vi = VipsImage.NewFromMemoryCopy(data, (nuint)size, width, height, bands, format); if (vi == IntPtr.Zero) { throw new VipsException("unable to make image from memory"); @@ -1082,9 +1063,9 @@ public void WriteToStream(Stream stream, string formatString, VOption kwargs = n /// The caller is responsible for freeing this memory with . /// /// Output buffer length. - /// A pointing to an unformatted C-style array. + /// A pointing to an unformatted C-style array. /// If unable to write to memory. - public IntPtr WriteToMemory(out ulong size) + public nint WriteToMemory(out ulong size) { var pointer = VipsImage.WriteToMemory(this, out size); if (pointer == IntPtr.Zero) @@ -1153,9 +1134,9 @@ public void Write(Image other) /// item does not exist. See . /// /// The name of the piece of metadata to get the type of. - /// A new instance of initialized to the GType or + /// A new instance of initialized to the GType or /// if the property does not exist. - public new IntPtr GetTypeOf(string name) + public new nint GetTypeOf(string name) { // on libvips before 8.5, property types must be fetched separately, // since built-in enums were reported as ints @@ -1245,7 +1226,7 @@ public string[] GetFields() var names = new List(); var count = 0; - IntPtr strPtr; + nint strPtr; while ((strPtr = Marshal.ReadIntPtr(ptrArr, count * IntPtr.Size)) != IntPtr.Zero) { var name = Marshal.PtrToStringAnsi(strPtr); @@ -2101,9 +2082,9 @@ public void SetKill(bool kill) /// Data to pass to handler calls. /// The handler id. /// If it failed to connect the signal. - public ulong SignalConnect(Enums.Signals signal, EvalDelegate callback, IntPtr data = default) + public ulong SignalConnect(Enums.Signals signal, EvalDelegate callback, nint data = default) { - void EvalMarshal(IntPtr imagePtr, VipsProgress progress, IntPtr userDataPtr) + void EvalMarshal(nint imagePtr, VipsProgress progress, nint userDataPtr) { if (imagePtr == IntPtr.Zero) { @@ -2116,18 +2097,14 @@ void EvalMarshal(IntPtr imagePtr, VipsProgress progress, IntPtr userDataPtr) callback.Invoke(image, progress); } - switch (signal) - { - case Enums.Signals.PreEval: - return SignalConnect("preeval", EvalMarshal, data); - case Enums.Signals.Eval: - return SignalConnect("eval", EvalMarshal, data); - case Enums.Signals.PostEval: - return SignalConnect("posteval", EvalMarshal, data); - default: - throw new ArgumentOutOfRangeException(nameof(signal), signal, - $"The value of argument '{nameof(signal)}' ({signal}) is invalid for enum type '{nameof(Enums.Signals)}'."); - } + return signal switch + { + Enums.Signals.PreEval => SignalConnect("preeval", EvalMarshal, data), + Enums.Signals.Eval => SignalConnect("eval", EvalMarshal, data), + Enums.Signals.PostEval => SignalConnect("posteval", EvalMarshal, data), + _ => throw new ArgumentOutOfRangeException(nameof(signal), signal, + $"The value of argument '{nameof(signal)}' ({signal}) is invalid for enum type '{nameof(Enums.Signals)}'.") + }; } /// diff --git a/src/NetVips/Internal/GLib.cs b/src/NetVips/Internal/GLib.cs index a7f1467f..0c7e0398 100644 --- a/src/NetVips/Internal/GLib.cs +++ b/src/NetVips/Internal/GLib.cs @@ -1,6 +1,5 @@ namespace NetVips.Internal { - using System; using System.Runtime.InteropServices; using System.Security; using Interop; @@ -9,24 +8,24 @@ namespace NetVips.Internal internal static class GLib { [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void LogFuncNative(IntPtr logDomain, LogLevelFlags flags, IntPtr message, - IntPtr userData); + internal delegate void LogFuncNative(nint logDomain, LogLevelFlags flags, nint message, + nint userData); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GLib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_free")] - internal static extern void GFree(IntPtr mem); + internal static extern void GFree(nint mem); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GLib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_malloc")] - internal static extern IntPtr GMalloc(ulong nBytes); + internal static extern nint GMalloc(ulong nBytes); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GLib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_log_set_handler")] internal static extern uint GLogSetHandler([MarshalAs(UnmanagedType.LPStr)] string logDomain, - LogLevelFlags flags, LogFuncNative logFunc, IntPtr userData); + LogLevelFlags flags, LogFuncNative logFunc, nint userData); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GLib, CallingConvention = CallingConvention.Cdecl, diff --git a/src/NetVips/Internal/GObject.cs b/src/NetVips/Internal/GObject.cs index 1c764726..63d9e7c3 100644 --- a/src/NetVips/Internal/GObject.cs +++ b/src/NetVips/Internal/GObject.cs @@ -1,6 +1,5 @@ namespace NetVips.Internal { - using System; using System.Runtime.InteropServices; using System.Security; using Interop; @@ -8,7 +7,7 @@ namespace NetVips.Internal using VipsBlobManaged = global::NetVips.VipsBlob; [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void GWeakNotify(IntPtr data, IntPtr objectPointer); + internal delegate void GWeakNotify(nint data, nint objectPointer); internal static class GObject { @@ -19,7 +18,7 @@ internal struct Struct internal uint RefCount; - internal IntPtr QData; + internal nint QData; } [SuppressUnmanagedCodeSecurity] @@ -37,17 +36,17 @@ internal static extern void GetProperty(GObjectManaged @object, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_object_ref")] - internal static extern IntPtr Ref(IntPtr @object); + internal static extern nint Ref(nint @object); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_object_unref")] - internal static extern void Unref(IntPtr @object); + internal static extern void Unref(nint @object); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_object_weak_ref")] - internal static extern void WeakRef(GObjectManaged @object, GWeakNotify notify, IntPtr data); + internal static extern void WeakRef(GObjectManaged @object, GWeakNotify notify, nint data); } [StructLayout(LayoutKind.Sequential)] @@ -65,13 +64,13 @@ internal struct GEnumValue [StructLayout(LayoutKind.Sequential)] internal struct GEnumClass { - internal IntPtr GTypeClass; + internal nint GTypeClass; internal int Minimum; internal int Maximum; internal uint NValues; - internal IntPtr Values; + internal nint Values; } internal static class GType @@ -79,28 +78,28 @@ internal static class GType [StructLayout(LayoutKind.Sequential)] internal struct Instance { - internal IntPtr GClass; + internal nint GClass; } [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_type_name")] - internal static extern IntPtr Name(IntPtr type); + internal static extern nint Name(nint type); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_type_from_name")] - internal static extern IntPtr FromName([MarshalAs(UnmanagedType.LPStr)] string name); + internal static extern nint FromName([MarshalAs(UnmanagedType.LPStr)] string name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_type_fundamental")] - internal static extern IntPtr Fundamental(IntPtr typeId); + internal static extern nint Fundamental(nint typeId); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_type_class_ref")] - internal static extern IntPtr ClassRef(IntPtr type); + internal static extern nint ClassRef(nint type); } internal static class GValue @@ -109,17 +108,17 @@ internal static class GValue internal struct Struct { [FieldOffset(0)] - internal IntPtr GType; + internal nint GType; [FieldOffset(8)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] - internal IntPtr[] Data; + internal nint[] Data; } [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_value_init")] - internal static extern IntPtr Init(ref Struct value, IntPtr gType); + internal static extern nint Init(ref Struct value, nint gType); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, @@ -175,7 +174,7 @@ internal struct Struct [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_value_get_string")] - internal static extern IntPtr GetString(in Struct value); + internal static extern nint GetString(in Struct value); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, @@ -205,7 +204,7 @@ internal struct Struct [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_value_get_object")] - internal static extern IntPtr GetObject(in Struct value); + internal static extern nint GetObject(in Struct value); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, @@ -220,15 +219,15 @@ internal struct Struct { internal GType.Instance GTypeInstance; - internal IntPtr Name; + internal nint Name; internal Enums.GParamFlags Flags; - internal IntPtr ValueType; - internal IntPtr OwnerType; + internal nint ValueType; + internal nint OwnerType; - internal IntPtr Nick; - internal IntPtr Blurb; - internal IntPtr QData; + internal nint Nick; + internal nint Blurb; + internal nint QData; internal uint RefCount; internal uint ParamId; } @@ -236,11 +235,11 @@ internal struct Struct [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_param_spec_get_blurb")] - internal static extern IntPtr GetBlurb(in Struct pspec); + internal static extern nint GetBlurb(in Struct pspec); } [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate void GClosureNotify(IntPtr data, IntPtr closure); + internal delegate void GClosureNotify(nint data, nint closure); internal static class GSignal { @@ -249,7 +248,7 @@ internal static class GSignal EntryPoint = "g_signal_connect_data")] internal static extern ulong ConnectData(GObjectManaged instance, [MarshalAs(UnmanagedType.LPStr)] string detailedSignal, - IntPtr cHandler, IntPtr data, + nint cHandler, nint data, GClosureNotify destroyData, Enums.GConnectFlags connectFlags); [SuppressUnmanagedCodeSecurity] @@ -261,7 +260,7 @@ internal static extern ulong ConnectData(GObjectManaged instance, [DllImport(Libraries.GObject, CallingConvention = CallingConvention.Cdecl, EntryPoint = "g_signal_handlers_disconnect_matched")] internal static extern uint HandlersDisconnectMatched(GObjectManaged instance, - Enums.GSignalMatchType mask, uint signalId, uint detail, IntPtr closure, - IntPtr func, IntPtr data); + Enums.GSignalMatchType mask, uint signalId, uint detail, nint closure, + nint func, nint data); } } \ No newline at end of file diff --git a/src/NetVips/Internal/Vips.cs b/src/NetVips/Internal/Vips.cs index fe1572fe..176ccbba 100644 --- a/src/NetVips/Internal/Vips.cs +++ b/src/NetVips/Internal/Vips.cs @@ -1,6 +1,5 @@ namespace NetVips.Internal { - using System; using System.Runtime.InteropServices; using System.Security; using System.Text; @@ -14,14 +13,14 @@ namespace NetVips.Internal internal static class Vips { [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr TypeMap2Fn(IntPtr type, IntPtr a, IntPtr b); + internal delegate nint TypeMap2Fn(nint type, nint a, nint b); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate IntPtr ArgumentMapFn(IntPtr @object, GParamSpec.Struct pspec, VipsArgumentClass argumentClass, - VipsArgumentInstance argumentInstance, IntPtr a, IntPtr b); + internal delegate nint ArgumentMapFn(nint @object, GParamSpec.Struct pspec, VipsArgumentClass argumentClass, + VipsArgumentInstance argumentInstance, nint a, nint b); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int CallbackFn(IntPtr a, IntPtr b); + internal delegate int CallbackFn(nint a, nint b); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -56,7 +55,7 @@ internal delegate IntPtr ArgumentMapFn(IntPtr @object, GParamSpec.Struct pspec, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_cache_get_max_mem")] - internal static extern UIntPtr CacheGetMaxMem(); + internal static extern nuint CacheGetMaxMem(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -137,7 +136,7 @@ internal delegate IntPtr ArgumentMapFn(IntPtr @object, GParamSpec.Struct pspec, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_error_buffer")] - internal static extern IntPtr ErrorBuffer(); + internal static extern nint ErrorBuffer(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -157,59 +156,59 @@ internal delegate IntPtr ArgumentMapFn(IntPtr @object, GParamSpec.Struct pspec, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_path_filename7")] - internal static extern IntPtr PathFilename7(byte[] path); + internal static extern nint PathFilename7(byte[] path); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_path_mode7")] - internal static extern IntPtr PathMode7(byte[] path); + internal static extern nint PathMode7(byte[] path); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_filename_get_filename")] - internal static extern IntPtr GetFilename(byte[] vipsFilename); + internal static extern nint GetFilename(byte[] vipsFilename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_filename_get_options")] - internal static extern IntPtr GetOptions(byte[] vipsFilename); + internal static extern nint GetOptions(byte[] vipsFilename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_blend_mode_get_type")] - internal static extern IntPtr BlendModeGetType(); + internal static extern nint BlendModeGetType(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_interpretation_get_type")] - internal static extern IntPtr InterpretationGetType(); + internal static extern nint InterpretationGetType(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_band_format_get_type")] - internal static extern IntPtr BandFormatGetType(); + internal static extern nint BandFormatGetType(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_argument_map")] - internal static extern IntPtr ArgumentMap(VipsObjectManaged @object, ArgumentMapFn fn, IntPtr a, - IntPtr b); + internal static extern nint ArgumentMap(VipsObjectManaged @object, ArgumentMapFn fn, nint a, + nint b); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_type_map")] - internal static extern IntPtr TypeMap(IntPtr @base, TypeMap2Fn fn, IntPtr a, IntPtr b); + internal static extern nint TypeMap(nint @base, TypeMap2Fn fn, nint a, nint b); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_type_find")] - internal static extern IntPtr TypeFind([MarshalAs(UnmanagedType.LPStr)] string basename, + internal static extern nint TypeFind([MarshalAs(UnmanagedType.LPStr)] string basename, [MarshalAs(UnmanagedType.LPStr)] string nickname); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_nickname_find")] - internal static extern IntPtr NicknameFind(IntPtr type); + internal static extern nint NicknameFind(nint type); internal static string PathFilename7(string path) { @@ -228,7 +227,7 @@ internal static class VipsObject { [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_object_get_args")] - internal static extern int GetArgs(VipsObjectManaged @object, out IntPtr names, out IntPtr flags, + internal static extern int GetArgs(VipsObjectManaged @object, out nint names, out nint flags, out int nArgs); [SuppressUnmanagedCodeSecurity] @@ -236,7 +235,7 @@ internal static extern int GetArgs(VipsObjectManaged @object, out IntPtr names, EntryPoint = "vips_object_get_argument")] internal static extern int GetArgument(VipsObjectManaged @object, [MarshalAs(UnmanagedType.LPStr)] string name, - out IntPtr pspec, out VipsArgumentClass argumentClass, + out nint pspec, out VipsArgumentClass argumentClass, out VipsArgumentInstance argumentInstance); [SuppressUnmanagedCodeSecurity] @@ -257,20 +256,20 @@ internal static extern int SetFromString(VipsObjectManaged @object, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_object_get_description")] - internal static extern IntPtr GetDescription(VipsObjectManaged @object); + internal static extern nint GetDescription(VipsObjectManaged @object); } [StructLayout(LayoutKind.Sequential)] internal struct VipsArgument { - internal IntPtr Pspec; + internal nint Pspec; } [StructLayout(LayoutKind.Sequential)] internal struct VipsArgumentClass { internal VipsArgument Parent; - internal IntPtr ObjectClass; + internal nint ObjectClass; internal ArgumentFlags Flags; internal int Priority; @@ -281,8 +280,8 @@ internal struct VipsArgumentClass internal struct VipsArgumentInstance { internal VipsArgument Parent; - internal IntPtr ArgumentClass; - internal IntPtr Object; + internal nint ArgumentClass; + internal nint Object; [MarshalAs(UnmanagedType.Bool)] internal bool Assigned; @@ -294,7 +293,7 @@ internal static class VipsBlob { [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_blob_get")] - internal static extern IntPtr Get(VipsBlobManaged blob, out UIntPtr length); + internal static extern nint Get(VipsBlobManaged blob, out nuint length); } internal static class VipsArea @@ -302,26 +301,26 @@ internal static class VipsArea [StructLayout(LayoutKind.Sequential)] internal struct Struct { - internal IntPtr Data; - internal UIntPtr Length; + internal nint Data; + internal nuint Length; internal int N; // private internal int Count; - internal IntPtr Lock; + internal nint Lock; internal Vips.CallbackFn FreeFn; - internal IntPtr Client; + internal nint Client; - internal IntPtr Type; - internal UIntPtr SizeofType; + internal nint Type; + internal nuint SizeofType; } [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_area_unref")] - internal static extern IntPtr Unref(IntPtr blob); + internal static extern nint Unref(nint blob); } internal static class VipsValue @@ -329,7 +328,7 @@ internal static class VipsValue [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_ref_string")] - internal static extern IntPtr GetRefString(in GValue.Struct value, out ulong length); + internal static extern nint GetRefString(in GValue.Struct value, out ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -339,24 +338,24 @@ internal static class VipsValue [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_blob")] - internal static extern IntPtr GetBlob(in GValue.Struct value, out ulong length); + internal static extern nint GetBlob(in GValue.Struct value, out ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_set_blob")] internal static extern void SetBlob(ref GValue.Struct value, Vips.CallbackFn freeFn, - IntPtr data, ulong length); + nint data, ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_set_blob_free")] - internal static extern void SetBlobFree(ref GValue.Struct value, IntPtr data, + internal static extern void SetBlobFree(ref GValue.Struct value, nint data, ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_array_double")] - internal static extern IntPtr GetArrayDouble(in GValue.Struct value, out int n); + internal static extern nint GetArrayDouble(in GValue.Struct value, out int n); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -368,7 +367,7 @@ internal static extern void SetArrayDouble(ref GValue.Struct value, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_array_int")] - internal static extern IntPtr GetArrayInt(in GValue.Struct value, out int n); + internal static extern nint GetArrayInt(in GValue.Struct value, out int n); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -380,7 +379,7 @@ internal static extern void SetArrayInt(ref GValue.Struct value, [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_value_get_array_image")] - internal static extern IntPtr GetArrayImage(in GValue.Struct value, out int n); + internal static extern nint GetArrayImage(in GValue.Struct value, out int n); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -419,24 +418,24 @@ internal static class VipsImage [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_new_from_memory")] - internal static extern IntPtr NewFromMemory(IntPtr data, UIntPtr size, int width, int height, + internal static extern nint NewFromMemory(nint data, nuint size, int width, int height, int bands, BandFormat format); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_new_from_memory_copy")] - internal static extern IntPtr NewFromMemoryCopy(IntPtr data, UIntPtr size, int width, int height, + internal static extern nint NewFromMemoryCopy(nint data, nuint size, int width, int height, int bands, BandFormat format); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_new_matrix_from_array")] - internal static extern IntPtr NewMatrixFromArray(int width, int height, double[] array, int size); + internal static extern nint NewMatrixFromArray(int width, int height, double[] array, int size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_new_temp_file")] - internal static extern IntPtr NewTempFile(byte[] format); + internal static extern nint NewTempFile(byte[] format); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -446,7 +445,7 @@ internal static extern IntPtr NewFromMemoryCopy(IntPtr data, UIntPtr size, int w [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_write_to_memory")] - internal static extern IntPtr WriteToMemory(Image @in, out ulong size); + internal static extern nint WriteToMemory(Image @in, out ulong size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -457,12 +456,12 @@ internal static extern IntPtr NewFromMemoryCopy(IntPtr data, UIntPtr size, int w [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_addalpha")] - internal static extern int AddAlpha(Image image, out IntPtr @out); + internal static extern int AddAlpha(Image image, out nint @out); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_copy_memory")] - internal static extern IntPtr CopyMemory(Image image); + internal static extern nint CopyMemory(Image image); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_set")] @@ -477,7 +476,7 @@ internal static extern int Get(Image image, [MarshalAs(UnmanagedType.LPStr)] str [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_get_typeof")] - internal static extern IntPtr GetTypeof(Image image, [MarshalAs(UnmanagedType.LPStr)] string name); + internal static extern nint GetTypeof(Image image, [MarshalAs(UnmanagedType.LPStr)] string name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -488,7 +487,7 @@ internal static extern int Get(Image image, [MarshalAs(UnmanagedType.LPStr)] str [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_image_get_fields")] - internal static extern IntPtr GetFields(Image image); + internal static extern nint GetFields(Image image); } internal static class VipsInterpolate @@ -496,7 +495,7 @@ internal static class VipsInterpolate [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_interpolate_new")] - internal static extern IntPtr New([MarshalAs(UnmanagedType.LPStr)] string nickname); + internal static extern nint New([MarshalAs(UnmanagedType.LPStr)] string nickname); } internal static class VipsRegion @@ -504,12 +503,12 @@ internal static class VipsRegion [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_region_new")] - internal static extern IntPtr New(Image image); + internal static extern nint New(Image image); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_region_fetch")] - internal static extern IntPtr Fetch(Region region, int left, int top, int width, int height, out ulong length); + internal static extern nint Fetch(Region region, int left, int top, int width, int height, out ulong length); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -532,17 +531,17 @@ internal static class VipsOperation [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_operation_new")] - internal static extern IntPtr New([MarshalAs(UnmanagedType.LPStr)] string name); + internal static extern nint New([MarshalAs(UnmanagedType.LPStr)] string name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_cache_operation_build")] - internal static extern IntPtr Build(Operation operation); + internal static extern nint Build(Operation operation); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_operation_flags_get_type")] - internal static extern IntPtr FlagsGetType(); + internal static extern nint FlagsGetType(); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, @@ -556,47 +555,47 @@ internal static class VipsForeign [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load")] - internal static extern IntPtr FindLoad(IntPtr filename); + internal static extern nint FindLoad(nint filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load")] - internal static extern IntPtr FindLoad(byte[] filename); + internal static extern nint FindLoad(byte[] filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load_buffer")] - internal static extern IntPtr FindLoadBuffer(byte[] data, ulong size); + internal static extern nint FindLoadBuffer(byte[] data, ulong size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load_buffer")] - internal static extern IntPtr FindLoadBuffer(IntPtr data, ulong size); + internal static extern nint FindLoadBuffer(nint data, ulong size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_load_source")] - internal static extern IntPtr FindLoadSource(Source stream); + internal static extern nint FindLoadSource(Source stream); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_save")] - internal static extern IntPtr FindSave(IntPtr filename); + internal static extern nint FindSave(nint filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_save_buffer")] - internal static extern IntPtr FindSaveBuffer(byte[] name); + internal static extern nint FindSaveBuffer(byte[] name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_find_save_target")] - internal static extern IntPtr FindSaveTarget(byte[] name); + internal static extern nint FindSaveTarget(byte[] name); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_foreign_get_suffixes")] - internal static extern IntPtr GetSuffixes(); + internal static extern nint GetSuffixes(); } internal static class VipsConnection @@ -604,11 +603,11 @@ internal static class VipsConnection [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_connection_filename")] - internal static extern IntPtr FileName(Connection connection); + internal static extern nint FileName(Connection connection); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_connection_nick")] - internal static extern IntPtr Nick(Connection connection); + internal static extern nint Nick(Connection connection); } internal static class VipsSource @@ -616,21 +615,21 @@ internal static class VipsSource [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_new_from_descriptor")] - internal static extern IntPtr NewFromDescriptor(int descriptor); + internal static extern nint NewFromDescriptor(int descriptor); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_new_from_file")] - internal static extern IntPtr NewFromFile(byte[] filename); + internal static extern nint NewFromFile(byte[] filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_new_from_memory")] - internal static extern IntPtr NewFromMemory(IntPtr data, UIntPtr size); + internal static extern nint NewFromMemory(nint data, nuint size); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_map_blob")] - internal static extern IntPtr MapBlob(Source source); + internal static extern nint MapBlob(Source source); } internal static class VipsSourceCustom @@ -638,13 +637,13 @@ internal static class VipsSourceCustom [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_source_custom_new")] - internal static extern IntPtr New(); + internal static extern nint New(); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long ReadSignal(IntPtr sourcePtr, IntPtr buffer, long length, IntPtr userDataPtr); + internal delegate long ReadSignal(nint sourcePtr, nint buffer, long length, nint userDataPtr); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long SeekSignal(IntPtr sourcePtr, long offset, int whence, IntPtr userDataPtr); + internal delegate long SeekSignal(nint sourcePtr, long offset, int whence, nint userDataPtr); } internal static class VipsTarget @@ -652,17 +651,17 @@ internal static class VipsTarget [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_target_new_to_descriptor")] - internal static extern IntPtr NewToDescriptor(int descriptor); + internal static extern nint NewToDescriptor(int descriptor); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_target_new_to_file")] - internal static extern IntPtr NewToFile(byte[] filename); + internal static extern nint NewToFile(byte[] filename); [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_target_new_to_memory")] - internal static extern IntPtr NewToMemory(); + internal static extern nint NewToMemory(); } internal static class VipsTargetCustom @@ -670,20 +669,20 @@ internal static class VipsTargetCustom [SuppressUnmanagedCodeSecurity] [DllImport(Libraries.Vips, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vips_target_custom_new")] - internal static extern IntPtr New(); + internal static extern nint New(); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long WriteSignal(IntPtr targetPtr, + internal delegate long WriteSignal(nint targetPtr, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] - byte[] buffer, int length, IntPtr userDataPtr); + byte[] buffer, int length, nint userDataPtr); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long ReadSignal(IntPtr targetPtr, IntPtr buffer, long length, IntPtr userDataPtr); + internal delegate long ReadSignal(nint targetPtr, nint buffer, long length, nint userDataPtr); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate long SeekSignal(IntPtr targetPtr, long offset, int whence, IntPtr userDataPtr); + internal delegate long SeekSignal(nint targetPtr, long offset, int whence, nint userDataPtr); [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointer(CallingConvention.Cdecl)] - internal delegate int EndSignal(IntPtr targetPtr, IntPtr userDataPtr); + internal delegate int EndSignal(nint targetPtr, nint userDataPtr); } } \ No newline at end of file diff --git a/src/NetVips/Interpolate.cs b/src/NetVips/Interpolate.cs index df0777a3..df1c1e0c 100644 --- a/src/NetVips/Interpolate.cs +++ b/src/NetVips/Interpolate.cs @@ -8,12 +8,9 @@ namespace NetVips /// public class Interpolate : VipsObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - private Interpolate(IntPtr pointer) : base(pointer) { - // logger.Debug($"VipsInterpolate = {pointer}"); } /// @@ -36,7 +33,6 @@ private Interpolate(IntPtr pointer) /// If unable to make a new interpolator from . public static Interpolate NewFromName(string name) { - // logger.Debug($"Interpolate.NewFromName: name = {name}"); var vi = VipsInterpolate.New(name); if (vi == IntPtr.Zero) { diff --git a/src/NetVips/Introspect.cs b/src/NetVips/Introspect.cs index e329af14..6addba10 100644 --- a/src/NetVips/Introspect.cs +++ b/src/NetVips/Introspect.cs @@ -15,13 +15,10 @@ namespace NetVips /// public class Introspect { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// A cache for introspection data. /// - private static readonly ConcurrentDictionary IntrospectCache = - new ConcurrentDictionary(); + private static readonly ConcurrentDictionary IntrospectCache = new(); /// /// An object structure that encapsulates the metadata @@ -42,7 +39,7 @@ public struct Argument /// /// The GType for this argument. /// - public IntPtr Type; + public nint Type; } /// @@ -58,22 +55,22 @@ public struct Argument /// /// The required input for this operation. /// - public List RequiredInput = new List(); + public List RequiredInput = new(); /// /// The optional input for this operation. /// - public Dictionary OptionalInput = new Dictionary(); + public Dictionary OptionalInput = new(); /// /// The required output for this operation. /// - public List RequiredOutput = new List(); + public List RequiredOutput = new(); /// /// The optional output for this operation. /// - public Dictionary OptionalOutput = new Dictionary(); + public Dictionary OptionalOutput = new(); /// /// Build introspection data for a specified operation name. @@ -81,7 +78,6 @@ public struct Argument /// The operation name to introspect. private Introspect(string operationName) { - // logger.Debug($"Introspect = {operationName}"); using var op = Operation.NewFromName(operationName); var arguments = GetArgs(op); @@ -189,8 +185,8 @@ void AddArg(string name, Enums.ArgumentFlags flags) } else { - IntPtr AddConstruct(IntPtr self, GParamSpec.Struct pspec, VipsArgumentClass argumentClass, - VipsArgumentInstance argumentInstance, IntPtr a, IntPtr b) + nint AddConstruct(nint self, GParamSpec.Struct pspec, VipsArgumentClass argumentClass, + VipsArgumentInstance argumentInstance, nint a, nint b) { var flags = argumentClass.Flags; if ((flags & Enums.ArgumentFlags.CONSTRUCT) == 0) diff --git a/src/NetVips/Log.cs b/src/NetVips/Log.cs index 4d488a86..6d9f74a9 100644 --- a/src/NetVips/Log.cs +++ b/src/NetVips/Log.cs @@ -21,8 +21,8 @@ public static class Log /// The message to process. public delegate void LogDelegate(string logDomain, Enums.LogLevelFlags logLevel, string message); - private static void NativeCallback(IntPtr logDomainNative, Enums.LogLevelFlags flags, IntPtr messageNative, - IntPtr userData) + private static void NativeCallback(nint logDomainNative, Enums.LogLevelFlags flags, nint messageNative, + nint userData) { if (userData == IntPtr.Zero) { @@ -38,7 +38,7 @@ private static void NativeCallback(IntPtr logDomainNative, Enums.LogLevelFlags f } } - private static readonly ConcurrentDictionary _handlers = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary _handlers = new(); /// /// Sets the log handler for a domain and a set of log levels. @@ -52,8 +52,8 @@ public static uint SetLogHandler(string logDomain, Enums.LogLevelFlags flags, Lo _nativeHandler ??= NativeCallback; var gch = GCHandle.Alloc(logFunc); - var result = GLib.GLogSetHandler(logDomain, flags, _nativeHandler, (IntPtr)gch); - _handlers.AddOrUpdate(result, gch, (k, v) => gch); + var result = GLib.GLogSetHandler(logDomain, flags, _nativeHandler, (nint)gch); + _handlers.AddOrUpdate(result, gch, (_, _) => gch); return result; } diff --git a/src/NetVips/ModuleInitializer.cs b/src/NetVips/ModuleInitializer.cs index e428d4c7..e78fa8d4 100644 --- a/src/NetVips/ModuleInitializer.cs +++ b/src/NetVips/ModuleInitializer.cs @@ -36,8 +36,7 @@ public static class ModuleInitializer /// /// A cache for . /// - internal static readonly Dictionary DllImportCache = - new Dictionary(); + internal static readonly Dictionary DllImportCache = new(); internal static string RemapLibraryName(string libraryName) { @@ -64,7 +63,7 @@ internal static string RemapLibraryName(string libraryName) : "libvips.so.42"; } - internal static IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) + internal static nint DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) { libraryName = RemapLibraryName(libraryName); if (DllImportCache.TryGetValue(libraryName, out var cachedHandle)) diff --git a/src/NetVips/MutableImage.cs b/src/NetVips/MutableImage.cs index cebac667..cc44a804 100644 --- a/src/NetVips/MutableImage.cs +++ b/src/NetVips/MutableImage.cs @@ -41,7 +41,7 @@ internal MutableImage(Image copiedImage) : base(copiedImage.ObjectRef()) /// The name of the piece of metadata to create. /// The value to set as a C# value. It is /// converted to the GType, if possible. - public new void Set(IntPtr gtype, string name, object value) + public new void Set(nint gtype, string name, object value) { using var gv = new GValue(); gv.SetType(gtype); @@ -66,7 +66,7 @@ public void Set(string name, object value) if (gtype == IntPtr.Zero) { throw new ArgumentException( - $"metadata item {name} does not exist - use the Set(IntPtr, string, object) overload to create and set"); + $"metadata item {name} does not exist - use the Set(nint, string, object) overload to create and set"); } Set(gtype, name, value); diff --git a/src/NetVips/NetVips.cs b/src/NetVips/NetVips.cs index c99f1100..d69fada3 100644 --- a/src/NetVips/NetVips.cs +++ b/src/NetVips/NetVips.cs @@ -308,7 +308,7 @@ public static string[] GetSuffixes() var names = new List(); var count = 0; - IntPtr strPtr; + nint strPtr; while ((strPtr = Marshal.ReadIntPtr(ptrArr, count * IntPtr.Size)) != IntPtr.Zero) { var name = Marshal.PtrToStringAnsi(strPtr); @@ -391,7 +391,7 @@ internal static void VipsOperationFlagsGetType() /// Name of base class. /// Search for a class with this nickname. /// The GType of the class, or if the class is not found. - public static IntPtr TypeFind(string basename, string nickname) + public static nint TypeFind(string basename, string nickname) { return Vips.TypeFind(basename, nickname); } @@ -401,7 +401,7 @@ public static IntPtr TypeFind(string basename, string nickname) /// /// Type to return name for. /// Type name. - public static string TypeName(IntPtr type) + public static string TypeName(nint type) { return Marshal.PtrToStringAnsi(GType.Name(type)); } @@ -411,7 +411,7 @@ public static string TypeName(IntPtr type) /// /// Type to return nickname for. /// Nickname. - public static string NicknameFind(IntPtr type) + public static string NicknameFind(nint type) { return Marshal.PtrToStringAnsi(Vips.NicknameFind(type)); } @@ -428,7 +428,7 @@ public static List GetOperations() var allNickNames = new List(); var handle = GCHandle.Alloc(allNickNames); - IntPtr TypeMap(IntPtr type, IntPtr a, IntPtr b) + nint TypeMap(nint type, nint a, nint b) { var nickname = NicknameFind(type); @@ -469,7 +469,7 @@ public static List GetEnums() var allEnums = new List(); var handle = GCHandle.Alloc(allEnums); - IntPtr TypeMap(IntPtr type, IntPtr a, IntPtr b) + nint TypeMap(nint type, nint a, nint b) { var nickname = TypeName(type); @@ -499,7 +499,7 @@ IntPtr TypeMap(IntPtr type, IntPtr a, IntPtr b) /// /// Type to return enum values for. /// A list of values. - public static Dictionary ValuesForEnum(IntPtr type) + public static Dictionary ValuesForEnum(nint type) { var typeClass = GType.ClassRef(type); var enumClass = Marshal.PtrToStructure(typeClass); @@ -525,7 +525,7 @@ public static Dictionary ValuesForEnum(IntPtr type) /// /// Type name to lookup. /// Corresponding type ID or . - public static IntPtr TypeFromName(string name) + public static nint TypeFromName(string name) { return GType.FromName(name); } @@ -535,7 +535,7 @@ public static IntPtr TypeFromName(string name) /// /// A valid type ID. /// Fundamental type ID. - public static IntPtr FundamentalType(IntPtr type) + public static nint FundamentalType(nint type) { return GType.Fundamental(type); } @@ -547,7 +547,7 @@ public static IntPtr FundamentalType(IntPtr type) /// This is needed for . /// /// The memory to free. - public static void Free(IntPtr mem) + public static void Free(nint mem) { GLib.GFree(mem); } diff --git a/src/NetVips/Operation.cs b/src/NetVips/Operation.cs index 05fc4615..d7778618 100644 --- a/src/NetVips/Operation.cs +++ b/src/NetVips/Operation.cs @@ -8,13 +8,10 @@ namespace NetVips /// public class Operation : VipsObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// private Operation(IntPtr pointer) : base(pointer) { - // logger.Debug($"Operation = {pointer}"); } /// @@ -45,10 +42,8 @@ public static Operation NewFromName(string operationName) /// A used as guide. /// The value. /// The GType of the property. - private void Set(IntPtr gtype, Image matchImage, string name, object value) + private void Set(nint gtype, Image matchImage, string name, object value) { - // logger.Debug($"Operation.Set: name = {name}, matchImage = {matchImage}, value = {value}"); - // if the object wants an image and we have a constant, Imageize it // // if the object wants an image array, Imageize any constants in the @@ -61,7 +56,7 @@ private void Set(IntPtr gtype, Image matchImage, string name, object value) } else if (gtype == GValue.ArrayImageType) { - if (!(value is Array values) || values.Rank != 1) + if (value is not Array { Rank: 1 } values) { throw new ArgumentException( $"unsupported value type {value.GetType()} for VipsArrayImage"); @@ -138,14 +133,9 @@ public static object Call(string operationName, VOption kwargs = null, params ob public static object Call(string operationName, VOption kwargs = null, Image matchImage = null, params object[] args) { - // logger.Debug($"Operation.call: operationName = {operationName}"); - // logger.Debug($"Operation.call: matchImage = {matchImage}"); - // logger.Debug($"Operation.call: args = {args}, kwargs = {kwargs}"); - // pull out the special string_options kwarg object stringOptions = null; kwargs?.Remove("string_options", out stringOptions); - // logger.Debug($"Operation.call: stringOptions = {stringOptions}"); var intro = Introspect.Get(operationName); if (intro.RequiredInput.Count != args.Length) @@ -159,7 +149,7 @@ public static object Call(string operationName, VOption kwargs = null, Image mat throw new VipsException($"unable to call {operationName}: operation must be mutable"); } - IntPtr vop; + nint vop; using (var op = NewFromName(operationName)) { // set any string options before any args so they can't be @@ -248,8 +238,6 @@ public static object Call(string operationName, VOption kwargs = null, Image mat Internal.VipsObject.UnrefOutputs(op); } - // logger.Debug($"Operation.call: result = {result}"); - return results.Length == 1 ? results[0] : results; } diff --git a/src/NetVips/Region.cs b/src/NetVips/Region.cs index 54b3adf8..47e6649f 100644 --- a/src/NetVips/Region.cs +++ b/src/NetVips/Region.cs @@ -14,12 +14,9 @@ namespace NetVips /// public class Region : VipsObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - private Region(IntPtr pointer) : base(pointer) { - // logger.Debug($"Region = {pointer}"); } /// @@ -30,7 +27,6 @@ private Region(IntPtr pointer) /// If unable to make a new region on . public static Region New(Image image) { - // logger.Debug($"Region.New: image = {image}"); var vi = VipsRegion.New(image); if (vi == IntPtr.Zero) { diff --git a/src/NetVips/Source.cs b/src/NetVips/Source.cs index 7695020f..d53d344c 100644 --- a/src/NetVips/Source.cs +++ b/src/NetVips/Source.cs @@ -9,8 +9,6 @@ namespace NetVips /// public class Source : Connection { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Secret ref for . /// @@ -39,8 +37,6 @@ internal Source(IntPtr pointer) /// If unable to create a new from . public static Source NewFromDescriptor(int descriptor) { - // logger.Debug($"Source.NewFromDescriptor: descriptor = {descriptor}"); - var pointer = Internal.VipsSource.NewFromDescriptor(descriptor); if (pointer == IntPtr.Zero) { @@ -65,8 +61,6 @@ public static Source NewFromDescriptor(int descriptor) /// If unable to create a new from . public static Source NewFromFile(string filename) { - // logger.Debug($"Source.NewFromFile: filename = {filename}"); - var bytes = Encoding.UTF8.GetBytes(filename + char.MinValue); // Ensure null-terminated string var pointer = Internal.VipsSource.NewFromFile(bytes); if (pointer == IntPtr.Zero) @@ -92,11 +86,8 @@ public static Source NewFromFile(string filename) /// If unable to create a new from . public static Source NewFromMemory(byte[] data) { - // logger.Debug($"Source.NewFromMemory"); - var handle = GCHandle.Alloc(data, GCHandleType.Pinned); - var pointer = Internal.VipsSource.NewFromMemory(handle.AddrOfPinnedObject(), (UIntPtr)data.Length); - + var pointer = Internal.VipsSource.NewFromMemory(handle.AddrOfPinnedObject(), (nuint)data.Length); if (pointer == IntPtr.Zero) { if (handle.IsAllocated) diff --git a/src/NetVips/SourceCustom.cs b/src/NetVips/SourceCustom.cs index 59ede810..b9f428c3 100644 --- a/src/NetVips/SourceCustom.cs +++ b/src/NetVips/SourceCustom.cs @@ -1,6 +1,5 @@ namespace NetVips { - using System; using System.IO; using System.Buffers; using System.Runtime.InteropServices; @@ -10,8 +9,6 @@ namespace NetVips /// public class SourceCustom : Source { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// A read delegate. /// @@ -69,7 +66,7 @@ public SourceCustom() : base(Internal.VipsSourceCustom.New()) /// The maximum number of bytes to be read. /// User data associated with the source. /// The total number of bytes read into the buffer. - internal long ReadHandler(IntPtr sourcePtr, IntPtr buffer, long length, IntPtr userDataPtr) + internal long ReadHandler(nint sourcePtr, nint buffer, long length, nint userDataPtr) { if (length <= 0) { @@ -112,7 +109,7 @@ internal long ReadHandler(IntPtr sourcePtr, IntPtr buffer, long length, IntPtr u /// reference point used to obtain the new position. /// User data associated with the source. /// The new position within the current source. - internal long SeekHandler(IntPtr sourcePtr, long offset, int whence, IntPtr userDataPtr) + internal long SeekHandler(nint sourcePtr, long offset, int whence, nint userDataPtr) { var newPosition = OnSeek?.Invoke(offset, (SeekOrigin)whence); return newPosition ?? -1; diff --git a/src/NetVips/SourceStream.cs b/src/NetVips/SourceStream.cs index a58f77e7..d8663f8b 100644 --- a/src/NetVips/SourceStream.cs +++ b/src/NetVips/SourceStream.cs @@ -8,8 +8,6 @@ namespace NetVips /// internal class SourceStream : SourceCustom { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Read from this stream. /// @@ -23,7 +21,6 @@ internal class SourceStream : SourceCustom /// internal SourceStream(Stream stream) { - // logger.Debug($"SourceStream: stream = {stream}"); var seekable = stream.CanSeek; _stream = stream; @@ -44,8 +41,6 @@ internal SourceStream(Stream stream) /// If is not readable. internal static SourceStream NewFromStream(Stream stream) { - // logger.Debug($"SourceStream.NewFromStream: stream = {stream}"); - if (!stream.CanRead) { throw new ArgumentException("The stream should be readable.", nameof(stream)); @@ -77,17 +72,13 @@ public long Seek(long offset, SeekOrigin origin) { try { - switch (origin) + return origin switch { - case SeekOrigin.Begin: - return _stream.Seek(_startPosition + offset, SeekOrigin.Begin) - _startPosition; - case SeekOrigin.Current: - return _stream.Seek(offset, SeekOrigin.Current) - _startPosition; - case SeekOrigin.End: - return _stream.Seek(offset, SeekOrigin.End) - _startPosition; - default: - return -1; - } + SeekOrigin.Begin => _stream.Seek(_startPosition + offset, SeekOrigin.Begin) - _startPosition, + SeekOrigin.Current => _stream.Seek(offset, SeekOrigin.Current) - _startPosition, + SeekOrigin.End => _stream.Seek(offset, SeekOrigin.End) - _startPosition, + _ => -1 + }; } catch { diff --git a/src/NetVips/Target.cs b/src/NetVips/Target.cs index 9682cce3..9fb3f80c 100644 --- a/src/NetVips/Target.cs +++ b/src/NetVips/Target.cs @@ -8,8 +8,6 @@ namespace NetVips /// public class Target : Connection { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// internal Target(IntPtr pointer) : base(pointer) { @@ -37,8 +35,6 @@ internal Target(IntPtr pointer) : base(pointer) /// If unable to create a new from . public static Target NewToDescriptor(int descriptor) { - // logger.Debug($"Target.NewToDescriptor: descriptor = {descriptor}"); - var pointer = Internal.VipsTarget.NewToDescriptor(descriptor); if (pointer == IntPtr.Zero) { @@ -63,8 +59,6 @@ public static Target NewToDescriptor(int descriptor) /// If unable to create a new from . public static Target NewToFile(string filename) { - // logger.Debug($"Target.NewToFile: filename = {filename}"); - var bytes = Encoding.UTF8.GetBytes(filename + char.MinValue); // Ensure null-terminated string var pointer = Internal.VipsTarget.NewToFile(bytes); if (pointer == IntPtr.Zero) @@ -94,10 +88,7 @@ public static Target NewToFile(string filename) /// If unable to create a new . public static Target NewToMemory() { - // logger.Debug($"Target.NewToMemory"); - var pointer = Internal.VipsTarget.NewToMemory(); - if (pointer == IntPtr.Zero) { throw new VipsException("can't create output target to memory"); diff --git a/src/NetVips/TargetCustom.cs b/src/NetVips/TargetCustom.cs index 335fb0b9..449bc8ee 100644 --- a/src/NetVips/TargetCustom.cs +++ b/src/NetVips/TargetCustom.cs @@ -1,6 +1,5 @@ namespace NetVips { - using System; using System.IO; using System.Buffers; using System.Runtime.InteropServices; @@ -10,8 +9,6 @@ namespace NetVips /// public class TargetCustom : Target { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// A write delegate. /// @@ -107,7 +104,7 @@ public TargetCustom() : base(Internal.VipsTargetCustom.New()) /// The number of bytes to be written to the current target. /// User data associated with the target. /// The total number of bytes written to the target. - internal long WriteHandler(IntPtr targetPtr, byte[] buffer, int length, IntPtr userDataPtr) + internal long WriteHandler(nint targetPtr, byte[] buffer, int length, nint userDataPtr) { var bytesWritten = OnWrite?.Invoke(buffer, length); return bytesWritten ?? -1; @@ -121,7 +118,7 @@ internal long WriteHandler(IntPtr targetPtr, byte[] buffer, int length, IntPtr u /// The maximum number of bytes to be read. /// User data associated with the target. /// The total number of bytes read into the buffer. - internal long ReadHandler(IntPtr targetPtr, IntPtr buffer, long length, IntPtr userDataPtr) + internal long ReadHandler(nint targetPtr, nint buffer, long length, nint userDataPtr) { if (length <= 0) { @@ -164,7 +161,7 @@ internal long ReadHandler(IntPtr targetPtr, IntPtr buffer, long length, IntPtr u /// reference point used to obtain the new position. /// User data associated with the target. /// The new position within the current target. - internal long SeekHandler(IntPtr targetPtr, long offset, int whence, IntPtr userDataPtr) + internal long SeekHandler(nint targetPtr, long offset, int whence, nint userDataPtr) { var newPosition = OnSeek?.Invoke(offset, (SeekOrigin)whence); return newPosition ?? -1; @@ -176,7 +173,7 @@ internal long SeekHandler(IntPtr targetPtr, long offset, int whence, IntPtr user /// The underlying pointer to the target. /// User data associated with the target. /// 0 on success, -1 on error. - internal int EndHandler(IntPtr targetPtr, IntPtr userDataPtr) + internal int EndHandler(nint targetPtr, nint userDataPtr) { return OnEnd?.Invoke() ?? 0; } diff --git a/src/NetVips/TargetStream.cs b/src/NetVips/TargetStream.cs index 0c6fdd56..23a04377 100644 --- a/src/NetVips/TargetStream.cs +++ b/src/NetVips/TargetStream.cs @@ -8,8 +8,6 @@ namespace NetVips /// internal class TargetStream : TargetCustom { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Write to this stream. /// @@ -23,7 +21,6 @@ internal class TargetStream : TargetCustom /// internal TargetStream(Stream stream) { - // logger.Debug($"TargetStream: stream = {stream}"); var readable = stream.CanRead; var seekable = stream.CanSeek; @@ -50,7 +47,6 @@ internal TargetStream(Stream stream) /// If is not writable. internal static TargetStream NewFromStream(Stream stream) { - // logger.Debug($"TargetStream.NewFromStream: stream = {stream}"); if (!stream.CanWrite) { throw new ArgumentException("The stream should be writable.", nameof(stream)); @@ -102,17 +98,13 @@ public long Seek(long offset, SeekOrigin origin) { try { - switch (origin) + return origin switch { - case SeekOrigin.Begin: - return _stream.Seek(_startPosition + offset, SeekOrigin.Begin) - _startPosition; - case SeekOrigin.Current: - return _stream.Seek(offset, SeekOrigin.Current) - _startPosition; - case SeekOrigin.End: - return _stream.Seek(offset, SeekOrigin.End) - _startPosition; - default: - return -1; - } + SeekOrigin.Begin => _stream.Seek(_startPosition + offset, SeekOrigin.Begin) - _startPosition, + SeekOrigin.Current => _stream.Seek(offset, SeekOrigin.Current) - _startPosition, + SeekOrigin.End => _stream.Seek(offset, SeekOrigin.End) - _startPosition, + _ => -1 + }; } catch { diff --git a/src/NetVips/VOption.cs b/src/NetVips/VOption.cs index 6b01a8bc..ffada4b3 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 . diff --git a/src/NetVips/VipsBlob.cs b/src/NetVips/VipsBlob.cs index 8404721c..135293b3 100644 --- a/src/NetVips/VipsBlob.cs +++ b/src/NetVips/VipsBlob.cs @@ -8,8 +8,6 @@ namespace NetVips /// internal class VipsBlob : SafeHandle { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Initializes a new instance of the class /// with the specified pointer to wrap around. @@ -20,16 +18,14 @@ internal VipsBlob(IntPtr pointer) { // record the pointer we were given to manage SetHandle(pointer); - - // logger.Debug($"VipsBlob = {pointer}"); } /// /// Get the data from a . /// /// Return number of bytes of data. - /// A containing the data. - internal IntPtr GetData(out UIntPtr length) + /// A containing the data. + internal nint GetData(out nuint length) { return Internal.VipsBlob.Get(this, out length); } @@ -42,7 +38,6 @@ internal IntPtr GetData(out UIntPtr length) /// in the event of a catastrophic failure, . protected override bool ReleaseHandle() { - // logger.Debug($"Unref: VipsBlob = {handle}"); if (!IsInvalid) { // Free the VipsArea @@ -61,7 +56,7 @@ protected override bool ReleaseHandle() /// /// Get the number of bytes of data. /// - internal ulong Length => (ulong)Marshal.PtrToStructure(handle).Length; + internal ulong Length => Marshal.PtrToStructure(handle).Length; /// /// Get the reference count of the blob. Handy for debugging. diff --git a/src/NetVips/VipsObject.cs b/src/NetVips/VipsObject.cs index 38c9d120..94a71fff 100644 --- a/src/NetVips/VipsObject.cs +++ b/src/NetVips/VipsObject.cs @@ -9,8 +9,6 @@ namespace NetVips /// public class VipsObject : GObject { - // private static Logger logger = LogManager.GetCurrentClassLogger(); - /// /// Attach a post-close delegate. This is called on finalization. /// @@ -27,7 +25,6 @@ public event Action OnPostClose internal VipsObject(IntPtr pointer) : base(pointer) { - // logger.Debug($"VipsObject = {pointer}"); } /// @@ -46,7 +43,6 @@ internal static void PrintAll() /// The pspec for this arg. private GParamSpec.Struct? GetPspec(string name) { - // logger.Debug($"GetPspec: this = {this}, name = {name}"); var argument = Internal.VipsObject.GetArgument(this, name, out var pspec, out _, out _); return argument != 0 @@ -64,7 +60,6 @@ internal static void PrintAll() /// The GObject property. internal object Get(string name) { - // logger.Debug($"Get: name = {name}"); var pspec = GetPspec(name); if (!pspec.HasValue) { @@ -88,9 +83,8 @@ internal object Get(string name) /// The name of the property to set. /// The value. /// The GType of the property. - internal void Set(IntPtr gtype, string name, object value) + internal void Set(nint gtype, string name, object value) { - // logger.Debug($"Set: gtype = {gtype}, name = {name}, value = {value}"); using var gv = new GValue(); gv.SetType(gtype); gv.Set(value); @@ -118,11 +112,10 @@ internal bool SetString(string stringOptions) /// Get the GType of a GObject property. /// /// The name of the GType to get the type of. - /// A new instance of initialized to the GType or + /// A new instance of initialized to the GType or /// if the property does not exist. - public IntPtr GetTypeOf(string name) + public nint GetTypeOf(string name) { - // logger.Debug($"GetTypeOf: this = {this}, name = {name}"); var pspec = GetPspec(name); if (!pspec.HasValue) diff --git a/src/NetVips/VipsProgress.cs b/src/NetVips/VipsProgress.cs index 1346aaf4..5734b614 100644 --- a/src/NetVips/VipsProgress.cs +++ b/src/NetVips/VipsProgress.cs @@ -1,6 +1,5 @@ namespace NetVips { - using System; using System.Runtime.InteropServices; /// @@ -35,7 +34,7 @@ public struct VipsProgress /// /// Image we are part of. /// - private IntPtr Im; + private nint Im; /// /// Time we have been running. diff --git a/tests/NetVips.Benchmarks/ImageSharp/ConvolutionProcessor.cs b/tests/NetVips.Benchmarks/ImageSharp/ConvolutionProcessor.cs index 826b9f1d..38528677 100644 --- a/tests/NetVips.Benchmarks/ImageSharp/ConvolutionProcessor.cs +++ b/tests/NetVips.Benchmarks/ImageSharp/ConvolutionProcessor.cs @@ -40,15 +40,15 @@ public IImageProcessor CreatePixelSpecificProcessor(Configuratio var type = Type.GetType( "SixLabors.ImageSharp.Processing.Processors.Convolution.ConvolutionProcessor`1, SixLabors.ImageSharp"); Type[] typeArgs = { typeof(TPixel) }; - Type genericType = type.MakeGenericType(typeArgs); + var genericType = type.MakeGenericType(typeArgs); Type[] parameterTypes = { configuration.GetType(), KernelXY.GetType().MakeByRefType(), PreserveAlpha.GetType(), source.GetType(), sourceRectangle.GetType() }; - ConstructorInfo ctor = genericType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, + var ctor = genericType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, parameterTypes, null); - object instance = + var instance = ctor.Invoke(new object[] { configuration, KernelXY, PreserveAlpha, source, sourceRectangle }); return (IImageProcessor)instance; diff --git a/tests/NetVips.Tests/ArithmeticTests.cs b/tests/NetVips.Tests/ArithmeticTests.cs index ee83c371..b63e7a23 100644 --- a/tests/NetVips.Tests/ArithmeticTests.cs +++ b/tests/NetVips.Tests/ArithmeticTests.cs @@ -178,7 +178,7 @@ public void TestFloorDiv() { dynamic FloorDiv(dynamic x, dynamic y) { - if (y is Image rightImage && !(x is Image)) + if (y is Image rightImage && x is not Image) { // There's no __rfloordiv__ & __pow__ equivalent in C# :( return (rightImage.Pow(-1) * x).Floor(); @@ -203,7 +203,7 @@ public void TestPow() { dynamic Pow(dynamic x, dynamic y) { - if (y is Image rightImage && !(x is Image)) + if (y is Image rightImage && x is not Image) { // There's no __rpow__ equivalent in C# :( return rightImage.Wop(x); @@ -365,12 +365,12 @@ public void TestEqual() { dynamic Equal(dynamic x, dynamic y) { - if (y is Image rightImage && !(x is Image)) + if (y is Image rightImage && x is not Image) { return x == rightImage; } - if (x is Image leftImage && !(y is Image)) + if (x is Image leftImage && y is not Image) { return y == leftImage; } @@ -392,12 +392,12 @@ public void TestNotEq() { dynamic NotEq(dynamic x, dynamic y) { - if (y is Image rightImage && !(x is Image)) + if (y is Image rightImage && x is not Image) { return x != rightImage; } - if (x is Image leftImage && !(y is Image)) + if (x is Image leftImage && y is not Image) { return y != leftImage; } @@ -684,7 +684,7 @@ public void TestHoughCircle() var y = (int)maxPos[2]; var vec = hough[x, y]; - var r = Array.IndexOf(vec, vec.Min(d => v)) + 35; + var r = Array.IndexOf(vec, vec.Min(_ => v)) + 35; Assert.Equal(50, x); Assert.Equal(50, y); diff --git a/tests/NetVips.Tests/ForeignTests.cs b/tests/NetVips.Tests/ForeignTests.cs index 0eb14c3e..a92195c2 100644 --- a/tests/NetVips.Tests/ForeignTests.cs +++ b/tests/NetVips.Tests/ForeignTests.cs @@ -184,7 +184,7 @@ void JpegValid(Image im) SaveLoadStream(".jpg", "", _colour, 80); } - var _ = Image.Jpegload(Helper.JpegFile, out var flags); + _ = Image.Jpegload(Helper.JpegFile, out var flags); Assert.Equal(Enums.ForeignFlags.SEQUENTIAL, flags); // see if we have exif parsing: our test image has this field @@ -321,7 +321,7 @@ public void TestTruncated() // but this should fail with a warning, and knock TRUNCATED_FILE out of // the cache - var _ = im.Avg(); + _ = im.Avg(); // now we should open again, but it won't come from cache, it'll reload im = Image.NewFromFile(Helper.TruncatedFile); @@ -390,7 +390,7 @@ public void TestBufferOverload() Assert.Equal(_colour.Width, x.Width); Assert.Equal(_colour.Height, x.Height); Assert.Equal(_colour.Bands, x.Bands); - Assert.True((_colour - x).Abs().Max() <= 0); + Assert.Equal(0, (_colour - x).Abs().Max()); } [SkippableFact] @@ -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); diff --git a/tests/NetVips.Tests/Helper.cs b/tests/NetVips.Tests/Helper.cs index 30d0e81e..6c253fdf 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, diff --git a/tests/NetVips.Tests/IoFuncsTests.cs b/tests/NetVips.Tests/IoFuncsTests.cs index a7901f68..3f797228 100644 --- a/tests/NetVips.Tests/IoFuncsTests.cs +++ b/tests/NetVips.Tests/IoFuncsTests.cs @@ -107,7 +107,7 @@ public void TestNewFromImage() [Fact] public void TestNewFromMemory() { - var s = Enumerable.Repeat((byte)0, 200).ToArray(); + var s = new byte[200]; var im = Image.NewFromMemory(s, 20, 10, 1, Enums.BandFormat.Uchar); Assert.Equal(20, im.Width); Assert.Equal(10, im.Height); @@ -181,7 +181,7 @@ public void TestFindLoadUtf8() [Fact] public void TestWriteToMemory() { - var s = Enumerable.Repeat((byte)0, 200).ToArray(); + var s = new byte[200]; var im = Image.NewFromMemory(s, 20, 10, 1, Enums.BandFormat.Uchar); var t = im.WriteToMemory(); Assert.True(s.SequenceEqual(t)); diff --git a/tests/NetVips.Tests/MorphologyTests.cs b/tests/NetVips.Tests/MorphologyTests.cs index 16a8b97f..778fa3c5 100644 --- a/tests/NetVips.Tests/MorphologyTests.cs +++ b/tests/NetVips.Tests/MorphologyTests.cs @@ -68,7 +68,7 @@ public void TestDilate() public void TestRank() { var im = Image.Black(100, 100); - im = im.Mutate(x=> x.DrawCircle(new double[] { 255 }, 50, 50, 25, fill: true)); + im = im.Mutate(x => x.DrawCircle(new double[] { 255 }, 50, 50, 25, fill: true)); var im2 = im.Rank(3, 3, 8); Assert.Equal(im.Width, im2.Width); Assert.Equal(im.Height, im2.Height); diff --git a/tests/NetVips.Tests/ResampleTests.cs b/tests/NetVips.Tests/ResampleTests.cs index 89d83a71..09cd733a 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);