Skip to content

Commit

Permalink
C# 11 goodies
Browse files Browse the repository at this point in the history
  • Loading branch information
kleisauke committed Jan 21, 2024
1 parent 777d611 commit b40be21
Show file tree
Hide file tree
Showing 45 changed files with 358 additions and 530 deletions.
1 change: 0 additions & 1 deletion build/Shims.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion build/common.props
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<CLSCompliant>false</CLSCompliant>
<ComVisible>false</ComVisible>

<LangVersion>9</LangVersion>
<LangVersion>11</LangVersion>

<Major>2</Major>
<Minor>4</Minor>
Expand Down
2 changes: 1 addition & 1 deletion samples/NetVips.Samples/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ static void Main(string[] args)
string input;
do
{
string[] sampleArgs = Array.Empty<string>();
var sampleArgs = Array.Empty<string>();
if (args.Length > 0)
{
var sampleId = Samples.Select((value, index) => new { Index = index + 1, value.Name })
Expand Down
6 changes: 3 additions & 3 deletions samples/NetVips.Samples/Samples/CaptchaGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
{
Expand Down
84 changes: 37 additions & 47 deletions samples/NetVips.Samples/Samples/GenerateImageClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class GenerateImageClass : ISample
public string Name => "Generate image class";
public string Category => "Internal";

private readonly Dictionary<IntPtr, string> _gTypeToCSharpDict = new Dictionary<IntPtr, string>
private readonly Dictionary<nint, string> _gTypeToCSharpDict = new()
{
{GValue.GBoolType, "bool"},
{GValue.GIntType, "int"},
Expand All @@ -35,12 +35,12 @@ public class GenerateImageClass : ISample
/// <summary>
/// The fundamental type for VipsFailOn. See <see cref="Enums.FailOn"/>.
/// </summary>
public static readonly IntPtr FailOnType = NetVips.TypeFromName("VipsFailOn");
public static readonly nint FailOnType = NetVips.TypeFromName("VipsFailOn");

/// <summary>
/// The fundamental type for VipsForeignKeep. See <see cref="Enums.ForeignKeep"/>.
/// </summary>
public static readonly IntPtr ForeignKeepType = NetVips.TypeFromName("VipsForeignKeep");
public static readonly nint ForeignKeepType = NetVips.TypeFromName("VipsForeignKeep");

public GenerateImageClass()
{
Expand Down Expand Up @@ -119,7 +119,7 @@ public GenerateImageClass()
/// <param name="name">The GType identifier.</param>
/// <param name="gtype">The GType to map.</param>
/// <returns>The C# type we use to represent it.</returns>
private string GTypeToCSharp(string name, IntPtr gtype)
private string GTypeToCSharp(string name, nint gtype)
{
if (_gTypeToCSharpDict.ContainsKey(gtype))
{
Expand Down Expand Up @@ -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)
Expand All @@ -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}/// <summary>\n");
Expand Down Expand Up @@ -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)
Expand Down
14 changes: 8 additions & 6 deletions samples/NetVips.Samples/Samples/GenerateImageOperators.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ public class GenerateImageOperators : ISample

private const string Indent = " ";

private readonly string _docstring = $@"{Indent}/// <summary>
{Indent}/// This operation {{0}}.
{Indent}/// </summary>
{Indent}/// <param name=""left"">{{1}}.</param>
{Indent}/// <param name=""right"">{{2}}.</param>
{Indent}/// <returns>A new <see cref=""Image""/>.</returns>";
private readonly string _docstring = $$"""
{{Indent}}/// <summary>
{{Indent}}/// This operation {0}.
{{Indent}}/// </summary>
{{Indent}}/// <param name="left">{1}.</param>
{{Indent}}/// <param name="right">{2}.</param>
{{Indent}}/// <returns>A new <see cref="Image"/>.</returns>
""";

/// <summary>
/// Make a C#-style docstring + operator overload.
Expand Down
3 changes: 1 addition & 2 deletions samples/NetVips.Samples/Samples/NetworkStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ namespace NetVips.Samples
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

public class NetworkStream : ISample
{
Expand Down Expand Up @@ -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");
Expand Down
6 changes: 3 additions & 3 deletions samples/NetVips.Samples/Samples/OnePointMosaic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public Point(int x, int y)
}
}

public List<string> Images = new List<string>
public List<string> Images = new()
{
"images/cd1.1.jpg",
"images/cd1.2.jpg",
Expand All @@ -34,7 +34,7 @@ public Point(int x, int y)
"images/cd4.2.jpg"
};

public List<Point> HorizontalMarks = new List<Point>
public List<Point> HorizontalMarks = new()
{
new Point(489, 140),
new Point(66, 141),
Expand All @@ -46,7 +46,7 @@ public Point(int x, int y)
new Point(40, 57)
};

public List<Point> VerticalMarks = new List<Point>
public List<Point> VerticalMarks = new()
{
new Point(364, 346),
new Point(388, 44),
Expand Down
2 changes: 1 addition & 1 deletion samples/NetVips.Samples/Samples/PostClose.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion samples/NetVips.Samples/Samples/Progress.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion samples/NetVips.Samples/Samples/RandomCropper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
48 changes: 21 additions & 27 deletions src/NetVips.Extensions/BitmapConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,27 @@ public static class BitmapConverter
/// <returns>The number of bands.</returns>
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.")
};
}

/// <summary>
Expand All @@ -57,27 +54,24 @@ private static int GuessBands(PixelFormat pixelFormat)
/// <returns>The <see cref="Enums.BandFormat"/>.</returns>
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.")
};
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion src/NetVips/Cache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static int Max
/// </summary>
public static ulong MaxMem
{
get => (ulong) Vips.CacheGetMaxMem();
get => Vips.CacheGetMaxMem();
set => Vips.CacheSetMaxMem(value);
}

Expand Down
2 changes: 1 addition & 1 deletion src/NetVips/ExtensionMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ internal static object[] PrependImage<T>(this T[] args, Image image)
/// <param name="freePtr">If set to <see langword="true"/>, free the GLib string.</param>
/// <param name="size">Size of the GLib string, use 0 to read until the null character.</param>
/// <returns>The managed string.</returns>
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)
{
Expand Down
Loading

0 comments on commit b40be21

Please sign in to comment.