Skip to content

Commit

Permalink
C# 11 goodies
Browse files Browse the repository at this point in the history
  • Loading branch information
kleisauke committed Oct 14, 2024
1 parent f5d6263 commit ba6c431
Show file tree
Hide file tree
Showing 46 changed files with 465 additions and 548 deletions.
5 changes: 1 addition & 4 deletions build/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,5 @@ public class Configuration : Enumeration
public static Configuration Debug = new() { Value = nameof(Debug) };
public static Configuration Release = new() { Value = nameof(Release) };

public static implicit operator string(Configuration configuration)
{
return configuration.Value;
}
public static implicit operator string(Configuration configuration) => configuration.Value;
}
11 changes: 3 additions & 8 deletions build/Shims.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,13 @@
using Nuke.Common.CI;
using Nuke.Common.CI.AppVeyor;
using Nuke.Common.CI.GitHubActions;
using Serilog;

public partial class Build
{
static void Information(string info)
{
Serilog.Log.Information(info);
}
static void Information(string info) => Log.Information(info);

static void Information(string info, params object[] args)
{
Serilog.Log.Information(info, args);
}
static void Information(string info, params object[] args) => Log.Information(info, args);

public static string GetVersion()
{
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>10</LangVersion>
<LangVersion>11</LangVersion>

<Major>2</Major>
<Minor>4</Minor>
Expand Down
20 changes: 11 additions & 9 deletions samples/NetVips.Samples/Samples/GenerateEnums.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,17 @@ private string Generate()
{
var allEnums = NetVips.GetEnums();

const string preamble = @"//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// libvips version: {0}
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------";
const string preamble = """
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// libvips version: {0}
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
""";

var stringBuilder =
new StringBuilder(string.Format(preamble,
Expand Down
126 changes: 60 additions & 66 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.TryGetValue(gtype, out var value))
{
Expand Down Expand Up @@ -190,62 +190,52 @@ string SafeIdentifier(string name) =>

string SafeCast(string type, string name = "result")
{
switch (type)
{
case "GObject":
case "Image":
case "int[]":
case "double[]":
case "byte[]":
case "Image[]":
case "object[]":
return $" as {type};";
case "bool":
return $" is {type} {name} && {name};";
case "int":
return $" is {type} {name} ? {name} : 0;";
case "ulong":
return $" is {type} {name} ? {name} : 0ul;";
case "double":
return $" is {type} {name} ? {name} : 0d;";
case "string":
return $" is {type} {name} ? {name} : null;";
default:
return ";";
}
return type switch
{
"GObject" => $" as {type};",
"Image" => $" as {type};",
"int[]" => $" as {type};",
"double[]" => $" as {type};",
"byte[]" => $" as {type};",
"Image[]" => $" as {type};",
"object[]" => $" as {type};",
"bool" => $" is {type} {name} && {name};",
"int" => $" is {type} {name} ? {name} : 0;",
"ulong" => $" is {type} {name} ? {name} : 0ul;",
"double" => $" is {type} {name} ? {name} : 0d;",
"string" => $" is {type} {name} ? {name} : null;",
_ => ";"
};
}

string ExplicitCast(string type)
{
return type switch
{
{ } enumString when enumString.StartsWith("Enums.") => $"({type})",
not null when type.StartsWith("Enums.") => $"({type})",
_ => string.Empty
};
}

string ToNullable(string type, string name)
{
switch (type)
return type switch
{
case "Image[]":
case "object[]":
case "int[]":
case "double[]":
case "byte[]":
case "GObject":
case "Image":
case "string":
return $"{type} {name} = null";
case "bool":
case "int":
case "ulong":
case "double":
case { } enumString when enumString.StartsWith("Enums."):
return $"{type}? {name} = null";
default:
throw new Exception($"Unsupported type: {type}");
}
"Image[]" => $"{type} {name} = null",
"object[]" => $"{type} {name} = null",
"int[]" => $"{type} {name} = null",
"double[]" => $"{type} {name} = null",
"byte[]" => $"{type} {name} = null",
"GObject" => $"{type} {name} = null",
"Image" => $"{type} {name} = null",
"string" => $"{type} {name} = null",
"bool" => $"{type}? {name} = null",
"int" => $"{type}? {name} = null",
"ulong" => $"{type}? {name} = null",
"double" => $"{type}? {name} = null",
not null when type.StartsWith("Enums.") => $"{type}? {name} = null",
_ => throw new Exception($"Unsupported type: {type}")
};
}

var result = new StringBuilder($"{indent}/// <summary>\n");
Expand Down Expand Up @@ -553,7 +543,7 @@ string ToCref(string name) =>
result.Append($"{indent}}}")
.AppendLine();

var firstArgType = requiredInput.Length > 0 ? op.GetTypeOf(requiredInput[0].Name) : IntPtr.Zero;
nint firstArgType = requiredInput.Length > 0 ? op.GetTypeOf(requiredInput[0].Name) : IntPtr.Zero;

// Create stream overload if necessary
if (firstArgType == GValue.SourceType || firstArgType == GValue.TargetType)
Expand Down Expand Up @@ -786,15 +776,17 @@ private string Generate(string indent = " ")
// get the list of all nicknames we can generate docstrings for.
var allNickNames = _allNickNames.Where(x => !exclude.Contains(x)).ToList();

const string preamble = @"//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// libvips version: {0}
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------";
const string preamble = """
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// libvips version: {0}
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
""";

var stringBuilder =
new StringBuilder(string.Format(preamble,
Expand Down Expand Up @@ -858,15 +850,17 @@ private string Generate(string indent = " ")
/// <returns>The `MutableImage.Generated.cs` as string.</returns>
private string GenerateMutable(string indent = " ")
{
const string preamble = @"//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// libvips version: {0}
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------";
const string preamble = """
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// libvips version: {0}
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
""";

var stringBuilder =
new StringBuilder(string.Format(preamble,
Expand Down
38 changes: 21 additions & 17 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 const 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 Expand Up @@ -228,13 +230,13 @@ private string GenerateOverload(string operatorStr, string type, bool invert = f
throw new ArgumentOutOfRangeException(nameof(type), type, "Type out of range");
}

if (operatorStr == "==" || operatorStr == "!=")
if (operatorStr is "==" or "!=")
{
leftDesc += " to compare";
rightDesc += " to compare";
}

var result = new StringBuilder(string.Format(_docstring, summary, leftDesc, rightDesc));
var result = new StringBuilder(string.Format(Docstring, summary, leftDesc, rightDesc));

result
.AppendLine()
Expand Down Expand Up @@ -283,14 +285,16 @@ public string GenerateOperators()
{">=", new[] {"Image", "double", "double[]", "int[]"}}
};

const string preamble = @"//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------";
const string preamble = """
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
""";

var stringBuilder = new StringBuilder(preamble);
stringBuilder.AppendLine()
Expand All @@ -314,7 +318,7 @@ public string GenerateOperators()
// We only generate the inverted types of the `==` and `!=` operators
// to avoid conflicts with `null` checks (for e.g. `image == null`).
// See: `Equal()` and `NotEqual()` for comparison with the other types.
if (operatorStr == "==" || operatorStr == "!=")
if (operatorStr is "==" or "!=")
{
continue;
}
Expand Down
5 changes: 2 additions & 3 deletions samples/NetVips.Samples/Samples/IdentifyExtension.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.IO;
using System.Text;

namespace NetVips.Samples;

Expand Down Expand Up @@ -72,9 +71,9 @@ public void Execute(string[] args)
Console.WriteLine(GetExtensionNonTruncated(File.ReadAllBytes("images/lichtenstein.jpg")));

Console.WriteLine("FindLoad function (truncated buffer)");
Console.WriteLine(GetExtension(Encoding.UTF8.GetBytes("GIF89a")));
Console.WriteLine(GetExtension("GIF89a"u8.ToArray()));

Console.WriteLine("vips-loader function (truncated buffer)");
Console.WriteLine(GetExtensionNonTruncated(Encoding.UTF8.GetBytes("GIF89a")));
Console.WriteLine(GetExtensionNonTruncated("GIF89a"u8.ToArray()));
}
}
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/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
3 changes: 1 addition & 2 deletions samples/NetVips.Samples/Samples/ShapeCropping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -308,8 +308,7 @@ public static int MaximumImageAlpha(Enums.Interpretation interpretation)
/// otherwise, <see langword="false"/></returns>
public static bool Is16Bit(Enums.Interpretation interpretation)
{
return interpretation == Enums.Interpretation.Rgb16 ||
interpretation == Enums.Interpretation.Grey16;
return interpretation is Enums.Interpretation.Rgb16 or Enums.Interpretation.Grey16;
}

#endregion
Expand Down
Loading

0 comments on commit ba6c431

Please sign in to comment.