Skip to content

Commit

Permalink
C# 11 goodies
Browse files Browse the repository at this point in the history
  • Loading branch information
kleisauke committed Mar 9, 2024
1 parent 89d23e5 commit a88c6f0
Show file tree
Hide file tree
Showing 57 changed files with 508 additions and 691 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;
}
12 changes: 3 additions & 9 deletions build/Shims.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,17 @@
using System.Xml.Linq;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
using Nuke.Common;
using Nuke.Common.CI;
using Nuke.Common.CI.AppVeyor;
using Nuke.Common.CI.GitHubActions;
using Nuke.Common.CI.TravisCI;
using Serilog;

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

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

public static string GetVersion()
{
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
7 changes: 4 additions & 3 deletions docs/Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@ namespace NetVips.Docs
using System;
using System.IO;
using System.Threading.Tasks;
using Docfx;
using Docfx.Dotnet;

class Build
internal class Build
{
static async Task Main(string[] args)
private static async Task Main(string[] args)
{
var projectDir =
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\.."));
var currentDirectory = Directory.GetCurrentDirectory();

Directory.SetCurrentDirectory(projectDir);
await DotnetApiCatalog.GenerateManagedReferenceYamlFiles("docfx.json");
await Docfx.Docset.Build("docfx.json");
await Docset.Build("docfx.json");
Directory.SetCurrentDirectory(currentDirectory);
}
}
Expand Down
6 changes: 3 additions & 3 deletions samples/NetVips.Samples/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ namespace NetVips
using System.Reflection;
using System.Text;

class Program
internal class Program
{
private static readonly List<ISample> Samples = Assembly.GetExecutingAssembly().GetTypes()
.Where(x => x.GetInterfaces().Contains(typeof(ISample)) && x.GetConstructor(Type.EmptyTypes) != null)
.Select(x => Activator.CreateInstance(x) as ISample)
.OrderBy(s => s?.Category)
.ToList();

static void Main(string[] args)
private static void Main(string[] args)
{
if (!ModuleInitializer.VipsInitialized)
{
Expand All @@ -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
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
138 changes: 65 additions & 73 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,18 +119,18 @@ 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))
if (_gTypeToCSharpDict.TryGetValue(gtype, out var value))
{
return _gTypeToCSharpDict[gtype];
return value;
}

var fundamental = NetVips.FundamentalType(gtype);

if (_gTypeToCSharpDict.ContainsKey(fundamental))
if (_gTypeToCSharpDict.TryGetValue(fundamental, out var fundamentalValue))
{
return _gTypeToCSharpDict[fundamental];
return fundamentalValue;
}

throw new Exception($"Unsupported type: {gtype} name: {name}");
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 @@ -340,10 +330,8 @@ string ToNullable(string type, string name)
$"{indent}/// <param name=\"{arg.Name.ToPascalCase().FirstLetterToLower()}\">{op.GetBlurb(arg.Name)}.</param>");
}

string outputType;

var outputTypes = requiredOutput.Select(arg => GTypeToCSharp(arg.Name, arg.Type)).ToArray();
outputType = outputTypes.Length switch
var outputType = outputTypes.Length switch
{
0 => "void",
1 => outputTypes[0],
Expand Down Expand Up @@ -555,7 +543,7 @@ string ToCref(string name) =>
result.Append($"{indent}}}")
.AppendLine();

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

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

const string preamble = @"//------------------------------------------------------------------------------
// <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 @@ -860,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
Loading

0 comments on commit a88c6f0

Please sign in to comment.