Skip to content

Commit e91083d

Browse files
committed
minor cleanup for code consistency, use more pattern matching
1 parent e5902a6 commit e91083d

19 files changed

+98
-115
lines changed

src/MagicScaler/Core/ImageFileInfo.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public ImageFileInfo(Stream imgStream) : this(imgStream, DateTime.MinValue) { }
6262

6363
public ImageFileInfo(Stream imgStream, DateTime lastModified)
6464
{
65-
if (imgStream == null) throw new ArgumentNullException(nameof(imgStream));
65+
if (imgStream is null) throw new ArgumentNullException(nameof(imgStream));
6666
if (!imgStream.CanSeek || !imgStream.CanRead) throw new ArgumentException("Input Stream must allow Seek and Read", nameof(imgStream));
6767
if (imgStream.Length <= 0 || imgStream.Position >= imgStream.Length) throw new ArgumentException("Input Stream is empty or positioned at its end", nameof(imgStream));
6868

@@ -83,8 +83,8 @@ private void loadInfo(WicDecoder dec, WicProcessingContext ctx)
8383
var frm = new WicFrameReader(ctx);
8484
WicTransforms.AddMetadataReader(ctx, basicOnly: true);
8585

86-
int width = (int)(frm.ExifOrientation.SwapDimensions() ? ctx.Source.Height : ctx.Source.Width);
87-
int height = (int)(frm.ExifOrientation.SwapDimensions() ? ctx.Source.Width : ctx.Source.Height);
86+
int width = (int)(frm.ExifOrientation.RequiresDimensionSwap() ? ctx.Source.Height : ctx.Source.Width);
87+
int height = (int)(frm.ExifOrientation.RequiresDimensionSwap() ? ctx.Source.Width : ctx.Source.Height);
8888
Frames[i] = new FrameInfo(width, height, ctx.Source.Format.AlphaRepresentation != PixelAlphaRepresentation.None, frm.ExifOrientation);
8989
}
9090
}

src/MagicScaler/Core/PixelFormats.cs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -64,15 +64,13 @@ internal struct PixelFormat : IEquatable<PixelFormat>
6464
public override bool Equals(object o) => o is PixelFormat pf ? Equals(pf) : false;
6565
public override int GetHashCode() => FormatGuid.GetHashCode();
6666

67-
public bool IsBinaryCompatibleWith(PixelFormat other)
68-
{
69-
return BitsPerPixel == other.BitsPerPixel &&
70-
ChannelCount == other.ChannelCount &&
71-
NumericRepresentation == other.NumericRepresentation &&
72-
ColorRepresentation == other.ColorRepresentation &&
73-
AlphaRepresentation == other.AlphaRepresentation &&
74-
Colorspace == other.Colorspace;
75-
}
67+
public bool IsBinaryCompatibleWith(PixelFormat other) =>
68+
BitsPerPixel == other.BitsPerPixel &&
69+
ChannelCount == other.ChannelCount &&
70+
NumericRepresentation == other.NumericRepresentation &&
71+
ColorRepresentation == other.ColorRepresentation &&
72+
AlphaRepresentation == other.AlphaRepresentation &&
73+
Colorspace == other.Colorspace;
7674

7775
public static readonly PixelFormat Grey16BppUQ15 = new PixelFormat {
7876
FormatGuid = new Guid(0xC175220D, 0x375B, 0x48C9, 0x8D, 0xD9, 0x1D, 0x28, 0x24, 0xFE, 0x88, 0x9F),
@@ -272,7 +270,7 @@ static PixelFormat()
272270
uint cch = pix.GetFriendlyName(0, null);
273271
var sbn = new StringBuilder((int)cch);
274272
pix.GetFriendlyName(cch, sbn);
275-
var pfn = sbn.ToString();
273+
string pfn = sbn.ToString();
276274

277275
var fmt = new PixelFormat {
278276
FormatGuid = pix.GetFormatGUID(),

src/MagicScaler/Core/ProcessImageSettings.cs

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ namespace PhotoSauce.MagicScaler
1919
public enum CropAnchor { Center = 0, Top = 1, Bottom = 2, Left = 4, Right = 8 }
2020
public enum CropScaleMode { Crop, Max, Stretch, Pad }
2121
public enum HybridScaleMode { FavorQuality, FavorSpeed, Turbo, Off }
22-
public enum GammaMode { Linear, sRGB }
22+
public enum GammaMode { Linear, Companded, [Obsolete]sRGB = 1 }
2323
public enum ChromaSubsampleMode { Default = 0, Subsample420 = 1, Subsample422 = 2, Subsample444 = 3 }
2424
public enum FileFormat { Auto, Jpeg, Png, Png8, Gif, Bmp, Tiff, Unknown = Auto }
2525
public enum OrientationMode { Normalize, Preserve, Ignore = 0xff }
@@ -56,7 +56,7 @@ public readonly struct InterpolationSettings
5656
public static readonly InterpolationSettings Spline36 = new InterpolationSettings(new Spline36Interpolator());
5757

5858
private readonly double blur;
59-
public double Blur => WeightingFunction == null ? default : WeightingFunction.Support * blur < 0.5 ? 1d : blur;
59+
public double Blur => WeightingFunction is null ? default : WeightingFunction.Support * blur < 0.5 ? 1d : blur;
6060

6161
public IInterpolator WeightingFunction { get; }
6262

@@ -182,10 +182,7 @@ public ChromaSubsampleMode JpegSubsampleMode
182182

183183
return JpegQuality >= 95 ? ChromaSubsampleMode.Subsample444 : JpegQuality >= 91 ? ChromaSubsampleMode.Subsample422 : ChromaSubsampleMode.Subsample420;
184184
}
185-
set
186-
{
187-
jpegSubsampling = value;
188-
}
185+
set => jpegSubsampling = value;
189186
}
190187

191188
public InterpolationSettings Interpolation
@@ -207,10 +204,7 @@ public InterpolationSettings Interpolation
207204

208205
return interpolator;
209206
}
210-
set
211-
{
212-
interpolation = value;
213-
}
207+
set => interpolation = value;
214208
}
215209

216210
public UnsharpMaskSettings UnsharpMask
@@ -240,10 +234,7 @@ public UnsharpMaskSettings UnsharpMask
240234
else
241235
return new UnsharpMaskSettings(150, 0.5, 0);
242236
}
243-
set
244-
{
245-
unsharpMask = value;
246-
}
237+
set => unsharpMask = value;
247238
}
248239

249240
public static ProcessImageSettings FromDictionary(IDictionary<string, string> dic)
@@ -280,7 +271,7 @@ public static ProcessImageSettings FromDictionary(IDictionary<string, string> di
280271
s.JpegSubsampleMode = Enum.TryParse(string.Concat("Subsample", cap.Value), true, out ChromaSubsampleMode csub) ? csub : s.JpegSubsampleMode;
281272

282273
string color = dic.GetValueOrDefault("bgcolor") ?? dic.GetValueOrDefault("bg");
283-
if (color != null)
274+
if (!string.IsNullOrWhiteSpace(color))
284275
{
285276
if (hexColorExpression.Value.IsMatch(color))
286277
color = string.Concat('#', color);
@@ -427,7 +418,7 @@ internal void NormalizeFrom(ImageFileInfo img)
427418

428419
var frame = img.Frames[FrameIndex];
429420

430-
Fixup(frame.Width, frame.Height, OrientationMode != OrientationMode.Normalize && frame.ExifOrientation.SwapDimensions());
421+
Fixup(frame.Width, frame.Height, OrientationMode != OrientationMode.Normalize && frame.ExifOrientation.RequiresDimensionSwap());
431422

432423
if (SaveFormat == FileFormat.Auto)
433424
SetSaveFormat(img.ContainerType, frame.HasAlpha);

src/MagicScaler/Interop/PropVariant.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public enum PropVariantMarshalType { Automatic, Ascii, Blob }
6666

6767
private static VarEnum getUnmanagedType(object o, PropVariantMarshalType marshalType)
6868
{
69-
if (o == null) return VarEnum.VT_EMPTY;
69+
if (o is null) return VarEnum.VT_EMPTY;
7070
if (Marshal.IsComObject(o)) return VarEnum.VT_UNKNOWN;
7171
if (o is PropVariant pv) return pv.UnmanagedType;
7272

@@ -182,7 +182,7 @@ public void CleanUpNativeData(IntPtr pNativeData)
182182

183183
unsafe public IntPtr MarshalManagedToNative(object o)
184184
{
185-
if (o == null)
185+
if (o is null)
186186
return IntPtr.Zero;
187187

188188
var marshalType = PropVariantMarshalType.Automatic;
@@ -198,7 +198,7 @@ unsafe public IntPtr MarshalManagedToNative(object o)
198198
var pNativeData = Marshal.AllocCoTaskMem(cbNative);
199199
Unsafe.InitBlock(pNativeData.ToPointer(), default, (uint)cbNative);
200200

201-
if (o == null)
201+
if (o is null)
202202
return pNativeData;
203203

204204
if (!(o is Array))
@@ -262,7 +262,7 @@ unsafe public IntPtr MarshalManagedToNative(object o)
262262

263263
public object MarshalNativeToManaged(IntPtr pNativeData)
264264
{
265-
if ((pNativeData == IntPtr.Zero) || (pv == null))
265+
if ((pNativeData == IntPtr.Zero) || (pv is null))
266266
return null;
267267

268268
var upv = Marshal.PtrToStructure<UnmanagedPropVariant>(pNativeData);

src/MagicScaler/Magic/ConvolutionTransform.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,10 +123,8 @@ unsafe protected override void CopyPixelsInternal(WICRect prc, uint cbStride, ui
123123
}
124124
}
125125

126-
unsafe protected virtual void ConvolveLine(byte* bstart, byte* wstart, byte* tstart, byte* ostart, byte* pmapy, int smapy, int ox, int oy, int ow)
127-
{
126+
unsafe protected virtual void ConvolveLine(byte* bstart, byte* wstart, byte* tstart, byte* ostart, byte* pmapy, int smapy, int ox, int oy, int ow) =>
128127
YProcessor.WriteDestLine(tstart, ostart, ox, ow, pmapy, smapy);
129-
}
130128

131129
unsafe protected void LoadBuffer(byte* bstart, byte* wstart, byte* tstart, byte* mapxstart, int iy)
132130
{

src/MagicScaler/Magic/FormatConversionTransform.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -798,7 +798,13 @@ public sealed class FormatConversionTransform : PixelTransform, IPixelTransformI
798798
{
799799
private readonly Guid outFormat;
800800

801-
public FormatConversionTransform(Guid outFormat) => this.outFormat = outFormat;
801+
public FormatConversionTransform(Guid outFormat)
802+
{
803+
if (outFormat != PixelFormats.Grey8bpp && outFormat != PixelFormats.Bgr24bpp && outFormat != PixelFormats.Bgra32bpp)
804+
throw new NotSupportedException("Unsupported pixel format");
805+
806+
this.outFormat = outFormat;
807+
}
802808

803809
void IPixelTransformInternal.Init(WicProcessingContext ctx)
804810
{

src/MagicScaler/Magic/KernelMap.cs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,21 +26,20 @@ unsafe private static T convertWeight(double d)
2626
{
2727
var w = default(T);
2828
if (typeof(T) == typeof(int))
29-
Unsafe.Write(Unsafe.AsPointer(ref w), MathUtil.Fix15(d));
29+
Unsafe.Write(&w, MathUtil.Fix15(d));
3030
else if (typeof(T) == typeof(float))
31-
Unsafe.Write(Unsafe.AsPointer(ref w), (float)d);
31+
Unsafe.Write(&w, (float)d);
3232

3333
return w;
3434
}
3535

3636
[MethodImpl(MethodImplOptions.AggressiveInlining)]
37-
unsafe private static void addWeight(ref T a, void* b)
37+
unsafe private static void addWeight(T* a, void* b)
3838
{
39-
void* ap = Unsafe.AsPointer(ref a);
4039
if (typeof(T) == typeof(int))
41-
Unsafe.Write(ap, Unsafe.Read<int>(ap) + Unsafe.Read<int>(b));
40+
Unsafe.Write(a, Unsafe.Read<int>(a) + Unsafe.Read<int>(b));
4241
else if (typeof(T) == typeof(float))
43-
Unsafe.Write(ap, Unsafe.Read<float>(ap) + Unsafe.Read<float>(b));
42+
Unsafe.Write(a, Unsafe.Read<float>(a) + Unsafe.Read<float>(b));
4443
}
4544

4645
unsafe private static void fillKernelWeights(IInterpolator interpolator, double* kernel, int ksize, double start, double center, double scale)
@@ -99,7 +98,7 @@ unsafe private KernelMap<T> clamp()
9998
{
10099
var a = default(T);
101100
for (int j = 0; j <= o; j++)
102-
addWeight(ref a, mpw + j * chan + k);
101+
addWeight(&a, mpw + j * chan + k);
103102

104103
Unsafe.Write(mpw + k, a);
105104

@@ -117,7 +116,7 @@ unsafe private KernelMap<T> clamp()
117116
{
118117
var a = default(T);
119118
for (int j = 0; j <= o; j++)
120-
addWeight(ref a, mpw + last * chan - j * chan + k);
119+
addWeight(&a, mpw + last * chan - j * chan + k);
121120

122121
Unsafe.Write(mpw + last * chan + k, a);
123122

src/MagicScaler/Magic/MagicImageProcessor.cs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,20 @@ public static class MagicImageProcessor
1313

1414
private static void checkInStream(Stream imgStream)
1515
{
16-
if (imgStream == null) throw new ArgumentNullException(nameof(imgStream));
16+
if (imgStream is null) throw new ArgumentNullException(nameof(imgStream));
1717
if (!imgStream.CanSeek || !imgStream.CanRead) throw new ArgumentException("Input Stream must allow Seek and Read", nameof(imgStream));
1818
if (imgStream.Length <= 0 || imgStream.Position >= imgStream.Length) throw new ArgumentException("Input Stream is empty or positioned at its end", nameof(imgStream));
1919
}
2020

2121
private static void checkOutStream(Stream outStream)
2222
{
23-
if (outStream == null) throw new ArgumentNullException(nameof(outStream));
23+
if (outStream is null) throw new ArgumentNullException(nameof(outStream));
2424
if (!outStream.CanSeek || !outStream.CanWrite) throw new ArgumentException("Output Stream must allow Seek and Write", nameof(outStream));
2525
}
2626

2727
public static ProcessImageResult ProcessImage(string imgPath, Stream outStream, ProcessImageSettings settings)
2828
{
29-
if (imgPath == null) throw new ArgumentNullException(nameof(imgPath));
29+
if (imgPath is null) throw new ArgumentNullException(nameof(imgPath));
3030
checkOutStream(outStream);
3131

3232
using (var ctx = new WicProcessingContext(settings))
@@ -65,7 +65,7 @@ public static ProcessImageResult ProcessImage(Stream imgStream, Stream outStream
6565

6666
public static ProcessImageResult ProcessImage(IPixelSource imgSource, Stream outStream, ProcessImageSettings settings)
6767
{
68-
if (imgSource == null) throw new ArgumentNullException(nameof(imgSource));
68+
if (imgSource is null) throw new ArgumentNullException(nameof(imgSource));
6969
checkOutStream(outStream);
7070

7171
using (var ctx = new WicProcessingContext(settings))
@@ -78,7 +78,7 @@ public static ProcessImageResult ProcessImage(IPixelSource imgSource, Stream out
7878

7979
public static ProcessingPipeline BuildPipeline(string imgPath, ProcessImageSettings settings)
8080
{
81-
if (imgPath == null) throw new ArgumentNullException(nameof(imgPath));
81+
if (imgPath is null) throw new ArgumentNullException(nameof(imgPath));
8282

8383
var ctx = new WicProcessingContext(settings);
8484
var dec = new WicDecoder(imgPath, ctx);
@@ -108,18 +108,16 @@ public static ProcessingPipeline BuildPipeline(Stream imgStream, ProcessImageSet
108108

109109
public static ProcessingPipeline BuildPipeline(IPixelSource imgSource, ProcessImageSettings settings)
110110
{
111-
if (imgSource == null) throw new ArgumentNullException(nameof(imgSource));
111+
if (imgSource is null) throw new ArgumentNullException(nameof(imgSource));
112112

113113
var ctx = new WicProcessingContext(settings);
114114
var dec = new WicDecoder(imgSource, ctx);
115115
buildPipeline(ctx, false);
116116
return new ProcessingPipeline(ctx);
117117
}
118118

119-
public static ProcessImageResult ExecutePipeline(this ProcessingPipeline pipeline, Stream outStream)
120-
{
121-
return executePipeline(pipeline.Context, outStream);
122-
}
119+
public static ProcessImageResult ExecutePipeline(this ProcessingPipeline pipeline, Stream outStream) =>
120+
executePipeline(pipeline.Context, outStream);
123121

124122
private static void buildPipeline(WicProcessingContext ctx, bool outputPlanar = true)
125123
{
@@ -136,7 +134,7 @@ private static void buildPipeline(WicProcessingContext ctx, bool outputPlanar =
136134
bool savePlanar = outputPlanar
137135
&& ctx.Settings.SaveFormat == FileFormat.Jpeg
138136
&& ctx.Settings.InnerRect == ctx.Settings.OuterRect
139-
&& ctx.SourceColorContext == null;
137+
&& ctx.SourceColorContext is null;
140138

141139
WicTransforms.AddExifRotator(ctx);
142140
WicTransforms.AddPlanarCache(ctx);

src/MagicScaler/Magic/PadTransform.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ namespace PhotoSauce.MagicScaler
1111
{
1212
internal class PadTransform : PixelSource
1313
{
14-
private readonly int Bpp;
14+
private readonly int bytesPerPixel;
1515
private readonly uint bgra;
1616
private readonly byte fillB;
1717
private readonly byte fillG;
@@ -20,9 +20,9 @@ internal class PadTransform : PixelSource
2020

2121
public PadTransform(PixelSource source, Color color, Rectangle innerRect, Rectangle outerRect) : base(source)
2222
{
23-
Bpp = Format.BitsPerPixel / 8;
23+
bytesPerPixel = Format.BitsPerPixel / 8;
2424

25-
if (Format.NumericRepresentation != PixelNumericRepresentation.UnsignedInteger || Format.ChannelCount != Bpp)
25+
if (Format.NumericRepresentation != PixelNumericRepresentation.UnsignedInteger || Format.ChannelCount != bytesPerPixel)
2626
throw new NotSupportedException("Pixel format not supported.");
2727

2828
bgra = (uint)color.ToArgb();
@@ -49,9 +49,9 @@ unsafe protected override void CopyPixelsInternal(WICRect prc, uint cbStride, ui
4949

5050
if (trect.Width < prc.Width || cy < irect.Y || cy >= irect.Bottom)
5151
{
52-
if (Bpp == 1)
52+
if (bytesPerPixel == 1)
5353
new Span<byte>(pb, prc.Width).Fill(fillB);
54-
else if (Bpp == 4)
54+
else if (bytesPerPixel == 4)
5555
new Span<uint>(pb, prc.Width).Fill(bgra);
5656
else
5757
{
@@ -70,7 +70,7 @@ unsafe protected override void CopyPixelsInternal(WICRect prc, uint cbStride, ui
7070
{
7171
trect.Y = cy - irect.Y;
7272
Timer.Stop();
73-
Source.CopyPixels(trect, cbStride, cbBufferSize, (IntPtr)(pb + cx * Bpp));
73+
Source.CopyPixels(trect, cbStride, cbBufferSize, (IntPtr)(pb + cx * bytesPerPixel));
7474
Timer.Start();
7575
}
7676
}

src/MagicScaler/Utilities/MiscExtensions.cs

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public static WICBitmapTransformOptions ToWicTransformOptions(this Orientation o
3737
return opt;
3838
}
3939

40-
public static bool SwapDimensions(this Orientation o) => o > Orientation.FlipVertical;
40+
public static bool RequiresDimensionSwap(this Orientation o) => o > Orientation.FlipVertical;
4141

4242
public static bool RequiresCache(this Orientation o) => o > Orientation.FlipHorizontal;
4343

@@ -67,26 +67,22 @@ public static ArraySegment<T> Zero<T>(this ArraySegment<T> a)
6767
return a;
6868
}
6969

70-
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dic, TKey key, Func<TValue> valueFactory = null)
71-
{
72-
return dic.TryGetValue(key, out var value) ? value : valueFactory == null ? default : valueFactory();
73-
}
70+
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dic, TKey key, Func<TValue> valueFactory = null) =>
71+
dic.TryGetValue(key, out var value) ? value : valueFactory is null ? default : valueFactory();
7472

7573
#if NETFRAMEWORK
76-
public static IDictionary<string, string> ToDictionary(this NameValueCollection nv)
77-
{
78-
return nv.AllKeys.Where(k => !string.IsNullOrEmpty(k)).ToDictionary(k => k, k => nv.GetValues(k).LastOrDefault(), StringComparer.OrdinalIgnoreCase);
79-
}
74+
public static IDictionary<string, string> ToDictionary(this NameValueCollection nv) =>
75+
nv.AllKeys.Where(k => !string.IsNullOrEmpty(k)).ToDictionary(k => k, k => nv.GetValues(k).LastOrDefault(), StringComparer.OrdinalIgnoreCase);
8076

81-
public static IDictionary<string, string> ToDictionary(this KeyValueConfigurationCollection kv)
82-
{
83-
return kv.AllKeys.Where(k => !string.IsNullOrEmpty(k)).ToDictionary(k => k, k => kv[k].Value, StringComparer.OrdinalIgnoreCase);
84-
}
77+
public static IDictionary<string, string> ToDictionary(this KeyValueConfigurationCollection kv) =>
78+
kv.AllKeys.Where(k => !string.IsNullOrEmpty(k)).ToDictionary(k => k, k => kv[k].Value, StringComparer.OrdinalIgnoreCase);
8579
#endif
8680

8781
public static IDictionary<TKey, TValue> Coalesce<TKey, TValue>(this IDictionary<TKey, TValue> dic1, IDictionary<TKey, TValue> dic2)
8882
{
89-
dic2.ToList().ForEach(i => dic1[i.Key] = i.Value);
83+
foreach (var kv in dic2)
84+
dic1[kv.Key] = kv.Value;
85+
9086
return dic1;
9187
}
9288

0 commit comments

Comments
 (0)