Skip to content

Commit

Permalink
Replace small dictionaries with switch
Browse files Browse the repository at this point in the history
  • Loading branch information
jnyrup committed Aug 18, 2024
1 parent 5cc4e17 commit 1f3ea4e
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 51 deletions.
20 changes: 10 additions & 10 deletions lib/PuppeteerSharp/BrowserData/InstalledBrowser.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;

namespace PuppeteerSharp.BrowserData
Expand All @@ -9,14 +8,6 @@ namespace PuppeteerSharp.BrowserData
/// </summary>
public class InstalledBrowser
{
private static readonly Dictionary<SupportedBrowser, Func<Platform, string, string>> _executablePathByBrowser = new()
{
[SupportedBrowser.Chrome] = Chrome.RelativeExecutablePath,
[SupportedBrowser.ChromeHeadlessShell] = ChromeHeadlessShell.RelativeExecutablePath,
[SupportedBrowser.Chromium] = Chromium.RelativeExecutablePath,
[SupportedBrowser.Firefox] = Firefox.RelativeExecutablePath,
};

/// <summary>
/// Initializes a new instance of the <see cref="InstalledBrowser"/> class.
/// </summary>
Expand Down Expand Up @@ -62,7 +53,16 @@ public string GetExecutablePath()
var installationDir = Cache.GetInstallationDir(Browser, Platform, BuildId);
return Path.Combine(
installationDir,
_executablePathByBrowser[Browser](Platform, BuildId));
GetExecutablePath(Browser)(Platform, BuildId));
}

private static Func<Platform, string, string> GetExecutablePath(SupportedBrowser browser) => browser switch
{
SupportedBrowser.Chrome => Chrome.RelativeExecutablePath,
SupportedBrowser.ChromeHeadlessShell => ChromeHeadlessShell.RelativeExecutablePath,
SupportedBrowser.Chromium => Chromium.RelativeExecutablePath,
SupportedBrowser.Firefox => Firefox.RelativeExecutablePath,
_ => throw new NotSupportedException(),
};
}
}
21 changes: 11 additions & 10 deletions lib/PuppeteerSharp/BrowserFetcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,6 @@ public sealed class BrowserFetcher : IBrowserFetcher
{
private const string PublishSingleFileLocalApplicationDataFolderName = "PuppeteerSharp";

private static readonly Dictionary<SupportedBrowser, Func<Platform, string, string, string>> _downloadsUrl = new()
{
[SupportedBrowser.Chrome] = Chrome.ResolveDownloadUrl,
[SupportedBrowser.ChromeHeadlessShell] = ChromeHeadlessShell.ResolveDownloadUrl,
[SupportedBrowser.Chromium] = Chromium.ResolveDownloadUrl,
[SupportedBrowser.Firefox] = Firefox.ResolveDownloadUrl,
};

private readonly CustomFileDownloadAction _customFileDownload;
private readonly ILogger<BrowserFetcher> _logger;

Expand Down Expand Up @@ -207,7 +199,16 @@ internal static string GetBrowsersLocation()
}

private static string GetDownloadURL(SupportedBrowser browser, Platform platform, string baseUrl, string buildId)
=> _downloadsUrl[browser](platform, buildId, baseUrl);
=> GetDownloadUrl(browser)(platform, buildId, baseUrl);

private static Func<Platform, string, string, string> GetDownloadUrl(SupportedBrowser browser) => browser switch
{
SupportedBrowser.Chrome => Chrome.ResolveDownloadUrl,
SupportedBrowser.ChromeHeadlessShell => ChromeHeadlessShell.ResolveDownloadUrl,
SupportedBrowser.Chromium => Chromium.ResolveDownloadUrl,
SupportedBrowser.Firefox => Firefox.ResolveDownloadUrl,
_ => throw new NotSupportedException(),
};

private static void ExtractTar(string zipPath, string folderPath)
{
Expand Down Expand Up @@ -236,7 +237,7 @@ private static void ExecuteSetup(string exePath, string folderPath)

private async Task<InstalledBrowser> DownloadAsync(SupportedBrowser browser, string buildId)
{
var url = _downloadsUrl[browser](Platform, buildId, BaseUrl);
var url = GetDownloadURL(browser, Platform, buildId, BaseUrl);
var fileName = url.Split('/').Last();
var cache = new Cache(CacheDir);
var archivePath = Path.Combine(CacheDir, fileName);
Expand Down
21 changes: 11 additions & 10 deletions lib/PuppeteerSharp/Cdp/CdpPage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,6 @@ namespace PuppeteerSharp.Cdp;
/// <inheritdoc />
public class CdpPage : Page
{
private static readonly Dictionary<string, decimal> _unitToPixels = new()
{
["px"] = 1,
["in"] = 96,
["cm"] = 37.8m,
["mm"] = 3.78m,
};

private readonly ConcurrentDictionary<string, CdpWebWorker> _workers = new();
private readonly ITargetManager _targetManager;
private readonly EmulationManager _emulationManager;
Expand Down Expand Up @@ -920,6 +912,15 @@ protected override async Task<string> PerformScreenshotAsync(ScreenshotType type
}
}

private static decimal? GetPixels(string unit) => unit switch
{
"px" => 1,
"in" => 96,
"cm" => 37.8m,
"mm" => 3.78m,
_ => null,
};

private void SetupPrimaryTargetListeners()
{
PrimaryTargetClient.Ready += OnAttachedToTarget;
Expand Down Expand Up @@ -1230,7 +1231,7 @@ private decimal ConvertPrintParameterToInches(object parameter)
var text = parameter.ToString();
var unit = text.Length > 2 ? text.Substring(text.Length - 2).ToLower(CultureInfo.CurrentCulture) : string.Empty;
string valueText;
if (_unitToPixels.ContainsKey(unit))
if (GetPixels(unit) is { })
{
valueText = text.Substring(0, text.Length - 2);
}
Expand All @@ -1244,7 +1245,7 @@ private decimal ConvertPrintParameterToInches(object parameter)

if (decimal.TryParse(valueText, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var number))
{
pixels = number * _unitToPixels[unit];
pixels = number * GetPixels(unit).Value;
}
else
{
Expand Down
20 changes: 10 additions & 10 deletions lib/PuppeteerSharp/Cdp/LifecycleWatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,6 @@ namespace PuppeteerSharp.Cdp
{
internal sealed class LifecycleWatcher : IDisposable
{
private static readonly Dictionary<WaitUntilNavigation, string> _puppeteerToProtocolLifecycle =
new()
{
[WaitUntilNavigation.Load] = "load",
[WaitUntilNavigation.DOMContentLoaded] = "DOMContentLoaded",
[WaitUntilNavigation.Networkidle0] = "networkIdle",
[WaitUntilNavigation.Networkidle2] = "networkAlmostIdle",
};

private static readonly WaitUntilNavigation[] _defaultWaitUntil = [WaitUntilNavigation.Load];

private readonly NetworkManager _networkManager;
Expand All @@ -44,7 +35,7 @@ public LifecycleWatcher(
{
_expectedLifecycle = (waitUntil ?? _defaultWaitUntil).Select(w =>
{
var protocolEvent = _puppeteerToProtocolLifecycle.GetValue(w);
var protocolEvent = GetProtocolEvent(w);
Contract.Assert(protocolEvent != null, $"Unknown value for options.waitUntil: {w}");
return protocolEvent;
});
Expand Down Expand Up @@ -87,6 +78,15 @@ public void Dispose()
_terminationCancellationToken.Dispose();
}

private static string GetProtocolEvent(WaitUntilNavigation waitUntil) => waitUntil switch
{
WaitUntilNavigation.Load => "load",
WaitUntilNavigation.DOMContentLoaded => "DOMContentLoaded",
WaitUntilNavigation.Networkidle0 => "networkIdle",
WaitUntilNavigation.Networkidle2 => "networkAlmostIdle",
_ => null,
};

private void Navigated(object sender, FrameNavigatedEventArgs e)
{
if (e.Type == NavigationType.BackForwardCacheRestore)
Expand Down
19 changes: 8 additions & 11 deletions lib/PuppeteerSharp/ScreenshotOptions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
using PuppeteerSharp.Media;
Expand All @@ -10,14 +9,6 @@ namespace PuppeteerSharp
/// </summary>
public class ScreenshotOptions
{
private static readonly Dictionary<string, ScreenshotType?> _extensionScreenshotTypeMap = new()
{
["jpe"] = ScreenshotType.Jpeg,
["jpeg"] = ScreenshotType.Jpeg,
["jpg"] = ScreenshotType.Jpeg,
["png"] = ScreenshotType.Png,
};

/// <summary>
/// Specifies clipping region of the page.
/// </summary>
Expand Down Expand Up @@ -87,8 +78,14 @@ public class ScreenshotOptions
internal static ScreenshotType? GetScreenshotTypeFromFile(string file)
{
var extension = new FileInfo(file).Extension.Replace(".", string.Empty);
_extensionScreenshotTypeMap.TryGetValue(extension, out var result);
return result;
return GetScreenshotType(extension);
}

private static ScreenshotType? GetScreenshotType(string extension) => extension switch
{
"jpe" or "jpeg" or "jpg" => ScreenshotType.Jpeg,
"png" => ScreenshotType.Png,
_ => null,
};
}
}

0 comments on commit 1f3ea4e

Please sign in to comment.