diff --git a/.gitignore b/.gitignore index ed0e87e25e0..4e9d1eddb81 100644 --- a/.gitignore +++ b/.gitignore @@ -225,3 +225,6 @@ msbuild.binlog *.project.lock.json /build/tools/** !/build/tools/packages.config + +# Generated file from .ttinclude +**/Generated/TypeInfo.g.cs \ No newline at end of file diff --git a/Microsoft.Toolkit.Parsers/Markdown/Blocks/YamlHeaderBlock.cs b/Microsoft.Toolkit.Parsers/Markdown/Blocks/YamlHeaderBlock.cs index b2ca0c7b238..1cfd33c1a0c 100644 --- a/Microsoft.Toolkit.Parsers/Markdown/Blocks/YamlHeaderBlock.cs +++ b/Microsoft.Toolkit.Parsers/Markdown/Blocks/YamlHeaderBlock.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; -using System.Text; using Microsoft.Toolkit.Parsers.Markdown.Helpers; namespace Microsoft.Toolkit.Parsers.Markdown.Blocks @@ -108,8 +107,6 @@ internal static YamlHeaderBlock Parse(string markdown, int start, int end, out i } var result = new YamlHeaderBlock(); - var keys = new List(); - var values = new List(); result.Children = new Dictionary(); foreach (var item in elements) { diff --git a/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs b/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs index 0dd7cf42ea4..135dfec69a6 100644 --- a/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs +++ b/Microsoft.Toolkit.Parsers/Markdown/Inlines/ImageInline.cs @@ -73,8 +73,6 @@ internal static void AddTripChars(List tripCharHelpers) /// A parsed markdown image, or null if this is not a markdown image. internal static InlineParseResult Parse(string markdown, int start, int end) { - int refstart = 0; - // Expect a '!' character. if (start >= end || markdown[start] != '!') { @@ -120,7 +118,7 @@ internal static InlineParseResult Parse(string markdown, int start, int end) if (pos < end && markdown[pos] == '[') { - refstart = pos; + int refstart = pos; // Find the reference ']' character while (pos < end) diff --git a/Microsoft.Toolkit.Parsers/Markdown/MarkdownDocument.cs b/Microsoft.Toolkit.Parsers/Markdown/MarkdownDocument.cs index 5d744328603..efa76254ece 100644 --- a/Microsoft.Toolkit.Parsers/Markdown/MarkdownDocument.cs +++ b/Microsoft.Toolkit.Parsers/Markdown/MarkdownDocument.cs @@ -55,7 +55,7 @@ public MarkdownDocument() /// The markdown text. public void Parse(string markdownText) { - Blocks = Parse(markdownText, 0, markdownText.Length, quoteDepth: 0, actualEnd: out int actualEnd); + Blocks = Parse(markdownText, 0, markdownText.Length, quoteDepth: 0, actualEnd: out _); // Remove any references from the list of blocks, and add them to a dictionary. for (int i = Blocks.Count - 1; i >= 0; i--) diff --git a/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs b/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs index 641335d3706..e17afdbf233 100644 --- a/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs +++ b/Microsoft.Toolkit.Parsers/Rss/RssHelper.cs @@ -311,9 +311,9 @@ public static string TimeZoneToOffset(string tz) tz = tz.ToUpper().Trim(); - if (timeZones.ContainsKey(tz)) + if (TimeZones.ContainsKey(tz)) { - return timeZones[tz].First(); + return TimeZones[tz].First(); } return null; @@ -337,8 +337,7 @@ private static IEnumerable GetImagesInHTMLString(string htmlString) if (matchHeight.Success) { var heightValue = matchHeight.Groups["height"].Value; - int size = 0; - if (int.TryParse(heightValue, out size) && size < 10) + if (int.TryParse(heightValue, out var heightIntValue) && heightIntValue < 10) { include = false; } @@ -348,8 +347,7 @@ private static IEnumerable GetImagesInHTMLString(string htmlString) if (matchWidth.Success) { var widthValue = matchWidth.Groups["width"].Value; - int size = 0; - if (int.TryParse(widthValue, out size) && size < 10) + if (int.TryParse(widthValue, out var widthIntValue) && widthIntValue < 10) { include = false; } @@ -376,7 +374,7 @@ private static IEnumerable GetImagesInHTMLString(string htmlString) /// /// Dictionary of timezones. /// - private static Dictionary timeZones = new Dictionary + private static readonly Dictionary TimeZones = new Dictionary { { "ACDT", new[] { "-1030", "Australian Central Daylight" } }, { "ACST", new[] { "-0930", "Australian Central Standard" } }, diff --git a/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs b/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs index 88d0a13a293..be93787e951 100644 --- a/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs +++ b/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs @@ -49,7 +49,7 @@ public override string ToString() /// Formatted string of key / value. public string ToString(bool withQuotes) { - string format = null; + string format; if (withQuotes) { format = "{0}=\"{1}\""; diff --git a/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs b/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs index 001aca2ff0b..7ddd6543090 100644 --- a/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs +++ b/Microsoft.Toolkit.Uwp.Connectivity/BluetoothLEHelper/ObservableGattDeviceService.cs @@ -48,7 +48,7 @@ public ObservableGattDeviceService(GattDeviceService service) Service = service; Name = GattUuidsService.ConvertUuidToName(service.Uuid); UUID = Service.Uuid.ToString(); - var t = GetAllCharacteristics(); + _ = PopulateAllCharacteristicsAsync(); } /// @@ -147,10 +147,10 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName } /// - /// Gets all the characteristics of this service + /// Populate the characteristics in . /// /// The status of the communication with the GATT device. - private async Task GetAllCharacteristics() + private async Task PopulateAllCharacteristicsAsync() { var tokenSource = new CancellationTokenSource(5000); var getCharacteristicsTask = await Task.Run( diff --git a/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs b/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs index 81a0e1ed334..89cecae17eb 100644 --- a/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs +++ b/Microsoft.Toolkit.Uwp.Notifications/DesktopNotificationManager/DesktopNotificationManagerCompat.cs @@ -181,13 +181,13 @@ public static bool IsRunningAsUwp() else { int length = 0; - StringBuilder sb = new StringBuilder(0); - int result = GetCurrentPackageFullName(ref length, sb); + var sb = new StringBuilder(0); + GetCurrentPackageFullName(ref length, sb); sb = new StringBuilder(length); - result = GetCurrentPackageFullName(ref length, sb); + int error = GetCurrentPackageFullName(ref length, sb); - _isRunningAsUwp = result != APPMODEL_ERROR_NO_PACKAGE; + _isRunningAsUwp = error != APPMODEL_ERROR_NO_PACKAGE; } } diff --git a/Microsoft.Toolkit.Uwp.Notifications/Toasts/Builder/ToastContentBuilder.Actions.cs b/Microsoft.Toolkit.Uwp.Notifications/Toasts/Builder/ToastContentBuilder.Actions.cs index 4ce255d546c..031861ccbec 100644 --- a/Microsoft.Toolkit.Uwp.Notifications/Toasts/Builder/ToastContentBuilder.Actions.cs +++ b/Microsoft.Toolkit.Uwp.Notifications/Toasts/Builder/ToastContentBuilder.Actions.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace Microsoft.Toolkit.Uwp.Notifications { @@ -198,8 +197,8 @@ public ToastContentBuilder AddComboBox(string id, string title, string defaultSe for (int i = 0; i < choices.Count(); i++) { - var choice = choices.ElementAt(i); - box.Items.Add(new ToastSelectionBoxItem(choice.comboBoxItemId, choice.comboBoxItemContent)); + var (comboBoxItemId, comboBoxItemContent) = choices.ElementAt(i); + box.Items.Add(new ToastSelectionBoxItem(comboBoxItemId, comboBoxItemContent)); } return AddToastInput(box); @@ -208,7 +207,7 @@ public ToastContentBuilder AddComboBox(string id, string title, string defaultSe /// /// Add an input option to the Toast. /// - /// An instance of a class that impmement that will be used on the toast. + /// An instance of a class that implement that will be used on the toast. /// The current instance of public ToastContentBuilder AddToastInput(IToastInput input) { diff --git a/Microsoft.Toolkit.Uwp.Notifications/Toasts/ToastPeople.cs b/Microsoft.Toolkit.Uwp.Notifications/Toasts/ToastPeople.cs index 25f6370ad3a..a1e3a320c75 100644 --- a/Microsoft.Toolkit.Uwp.Notifications/Toasts/ToastPeople.cs +++ b/Microsoft.Toolkit.Uwp.Notifications/Toasts/ToastPeople.cs @@ -31,7 +31,7 @@ public sealed class ToastPeople internal void PopulateToastElement(Element_Toast toast) { - string hintPeople = null; + string hintPeople; if (RemoteId != null) { diff --git a/Microsoft.Toolkit.Uwp.PlatformDifferencesGen/Program.cs b/Microsoft.Toolkit.Uwp.PlatformDifferencesGen/Program.cs index 11839c02c9d..1cfaef00249 100644 --- a/Microsoft.Toolkit.Uwp.PlatformDifferencesGen/Program.cs +++ b/Microsoft.Toolkit.Uwp.PlatformDifferencesGen/Program.cs @@ -191,15 +191,11 @@ public static string AssemblyDirectory private static Dictionary> ProcessAssembly(Assembly assembly) { - int pos = assembly.FullName.IndexOf(", Culture"); - - string fileName = $"{assembly.FullName.Substring(0, pos)}.json"; - - Dictionary> types = new Dictionary>(); + var types = new Dictionary>(); foreach (var exportedType in assembly.ExportedTypes) { - List members = new List(); + var members = new List(); if (exportedType.IsEnum) { diff --git a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/Analyzer.cs b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/Analyzer.cs index 6692b5c799f..ebc19cd548b 100644 --- a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/Analyzer.cs +++ b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/Analyzer.cs @@ -314,9 +314,7 @@ public static HowToGuard GetGuardForSymbol(ISymbol target) private static TypePresenceIndicator CheckCollectionForType(Dictionary> collection, string typeName, ISymbol symbol) { - List newMembers = null; - - if (!collection.TryGetValue(typeName, out newMembers)) + if (!collection.TryGetValue(typeName, out var newMembers)) { return TypePresenceIndicator.NotFound; } diff --git a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerCS.cs b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerCS.cs index 9438fb95717..5d8e09ab74a 100644 --- a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerCS.cs +++ b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerCS.cs @@ -202,10 +202,7 @@ private void AnalyzeExpression(SyntaxNodeAnalysisContext context, ConcurrentDict } var line = loc.GetLineSpan().StartLinePosition.Line; - - Diagnostic diagnostic = null; - - if (reports.TryGetValue(line, out diagnostic) && diagnostic.Location.SourceSpan.Start <= loc.SourceSpan.Start) + if (reports.TryGetValue(line, out var diagnostic) && diagnostic.Location.SourceSpan.Start <= loc.SourceSpan.Start) { return; } diff --git a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerVB.cs b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerVB.cs index e403a5fa71e..115968ee68b 100644 --- a/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerVB.cs +++ b/Microsoft.Toolkit.Uwp.PlatformSpecificAnalyzer/PlatformSpecificAnalyzerVB.cs @@ -226,10 +226,7 @@ private void AnalyzeExpression(SyntaxNodeAnalysisContext context, ConcurrentDict } var line = loc.GetLineSpan().StartLinePosition.Line; - - Diagnostic diagnostic = null; - - if (reports.TryGetValue(line, out diagnostic) && diagnostic.Location.SourceSpan.Start <= loc.SourceSpan.Start) + if (reports.TryGetValue(line, out var diagnostic) && diagnostic.Location.SourceSpan.Start <= loc.SourceSpan.Start) { return; } diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Pages/SampleController.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/Pages/SampleController.xaml.cs index 6b60ed88bd0..7c93b2bafac 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Pages/SampleController.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Pages/SampleController.xaml.cs @@ -8,7 +8,6 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; -using System.Threading.Tasks; using Microsoft.Toolkit.Uwp.SampleApp.Common; using Microsoft.Toolkit.Uwp.SampleApp.Controls; using Microsoft.Toolkit.Uwp.SampleApp.Models; @@ -165,7 +164,7 @@ public void RefreshXamlRender() { if (CurrentSample != null) { - var code = string.Empty; + string code; if (InfoAreaPivot.SelectedItem == PropertiesPivotItem) { code = CurrentSample.BindedXamlCode; diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageCache/ImageCachePage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageCache/ImageCachePage.xaml.cs index 073db7e4c6e..63bd02f289a 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageCache/ImageCachePage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageCache/ImageCachePage.xaml.cs @@ -66,7 +66,7 @@ private async Task PreCacheImages(bool loadInMemory = false) private async Task LoadDataAsync() { var source = new PhotosDataSource(); - _photoItems = await new PhotosDataSource().GetItemsAsync(true); + _photoItems = await source.GetItemsAsync(true); } private async void PreCache_Tapped(object sender, RoutedEventArgs e) diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LinkedIn Service/LinkedInPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LinkedIn Service/LinkedInPage.xaml.cs index 452b4aeb84d..ba824ec0a9e 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LinkedIn Service/LinkedInPage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LinkedIn Service/LinkedInPage.xaml.cs @@ -39,7 +39,7 @@ private async void ConnectButton_Click(object sender, RoutedEventArgs e) CallbackUri = CallbackUri.Text }; - var succeeded = LinkedInService.Instance.Initialize(oAuthTokens, LinkedInPermissions.ReadBasicProfile | LinkedInPermissions.WriteShare); + LinkedInService.Instance.Initialize(oAuthTokens, LinkedInPermissions.ReadBasicProfile | LinkedInPermissions.WriteShare); var loggedIn = await LinkedInService.Instance.LoginAsync(); @@ -66,7 +66,7 @@ private async void ShareButton_Click(object sender, RoutedEventArgs e) return; } - var response = await LinkedInService.Instance.ShareActivityAsync(ShareText.Text); + await LinkedInService.Instance.ShareActivityAsync(ShareText.Text); var message = new MessageDialog("Share sent to LinkedIn"); await message.ShowAsync(); diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LiveTile/LiveTilePage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LiveTile/LiveTilePage.xaml.cs index 418ffb5c1d7..53642cff0f9 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LiveTile/LiveTilePage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/LiveTile/LiveTilePage.xaml.cs @@ -170,7 +170,7 @@ private void Initialize() tile.VisualElements.Square150x150Logo = Constants.Square150x150Logo; tile.VisualElements.Wide310x150Logo = Constants.Wide310x150Logo; tile.VisualElements.Square310x310Logo = Constants.Square310x310Logo; - var dontWait = tile.UpdateAsync(); // Commit changes (no need to await) + _ = tile.UpdateAsync(); // Commit changes (no need to await) tile.CreateTileUpdater().Update(new TileNotification(_tileContent.GetXml())); } diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/MarkdownTextBlock/MarkdownTextBlockPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/MarkdownTextBlock/MarkdownTextBlockPage.xaml.cs index f7d84fdfca6..d19885094d6 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/MarkdownTextBlock/MarkdownTextBlockPage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/MarkdownTextBlock/MarkdownTextBlockPage.xaml.cs @@ -57,7 +57,7 @@ private void Current_ThemeChanged(object sender, Models.ThemeChangedArgs e) private async void MarkdownText_ImageClicked(object sender, LinkClickedEventArgs e) { - if (!Uri.TryCreate(e.Link, UriKind.Absolute, out Uri result)) + if (!Uri.IsWellFormedUriString(e.Link, UriKind.Absolute)) { await new MessageDialog("Masked relative Images needs to be manually handled.").ShowAsync(); } @@ -91,7 +91,7 @@ private void SetInitalText(string text) private async void MarkdownText_LinkClicked(object sender, LinkClickedEventArgs e) { - if (!Uri.TryCreate(e.Link, UriKind.Absolute, out Uri result)) + if (!Uri.IsWellFormedUriString(e.Link, UriKind.Absolute)) { await new MessageDialog("Masked relative links needs to be manually handled.").ShowAsync(); } diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RadialGauge/RadialGaugeCode.bind b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RadialGauge/RadialGaugeCode.bind index cfd2706e3d1..9a332b448d4 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RadialGauge/RadialGaugeCode.bind +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RadialGauge/RadialGaugeCode.bind @@ -26,6 +26,7 @@ MinAngle="@[MinAngle:Slider:210:0-360]" MaxAngle="@[MaxAngle:Slider:150:0-360]" Unit="units" + ValueStringFormat="@[ValueStringFormat:String:N0]" NeedleWidth="@[NeedleWidth:Slider:4:1-10]" NeedleLength="@[NeedleLength:Slider:100:20-100]" TickLength="@[TickLength:Slider:10:0-30]" diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/WeatherLiveTileAndToast/WeatherLiveTileAndToastPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/WeatherLiveTileAndToast/WeatherLiveTileAndToastPage.xaml.cs index 14993245414..d172b39aa34 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/WeatherLiveTileAndToast/WeatherLiveTileAndToastPage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/WeatherLiveTileAndToast/WeatherLiveTileAndToastPage.xaml.cs @@ -314,7 +314,7 @@ private void Initialize() tile.VisualElements.Square150x150Logo = Constants.Square150x150Logo; tile.VisualElements.Wide310x150Logo = Constants.Wide310x150Logo; tile.VisualElements.Square310x310Logo = Constants.Square310x310Logo; - var dontWait = tile.UpdateAsync(); // Commit changes (no need to await) + _ = tile.UpdateAsync(); // Commit changes (no need to await) tile.CreateTileUpdater().Update(new TileNotification(_tileContent.GetXml())); } diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs b/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs index 359353ec5ff..936e8fffb82 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Shell.SamplePicker.cs @@ -36,11 +36,11 @@ private Sample CurrentSample set { _currentSample = value; - var nop = SetNavViewSelection(); + _ = SetNavViewSelectionAsync(); } } - private async Task SetNavViewSelection() + private async Task SetNavViewSelectionAsync() { if (_currentSample != null) { @@ -59,10 +59,10 @@ private async Task SetNavViewSelection() private void HideSamplePicker() { - SamplePickerGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed; + SamplePickerGrid.Visibility = Visibility.Collapsed; _selectedCategory = null; - var noop = SetNavViewSelection(); + _ = SetNavViewSelectionAsync(); } private async void ShowSamplePicker(Sample[] samples = null, bool group = false) @@ -323,7 +323,7 @@ private void HideMoreInfo() animation.Configuration = new DirectConnectedAnimationConfiguration(); } - var t = SamplePickerGridView.TryStartConnectedAnimationAsync(animation, MoreInfoContent.DataContext, "SampleIcon"); + _ = SamplePickerGridView.TryStartConnectedAnimationAsync(animation, MoreInfoContent.DataContext, "SampleIcon"); } MoreInfoContent.DataContext = null; diff --git a/Microsoft.Toolkit.Uwp.UI.Animations/ConnectedAnimations/ConnectedAnimationHelper.cs b/Microsoft.Toolkit.Uwp.UI.Animations/ConnectedAnimations/ConnectedAnimationHelper.cs index 555f5bba5a9..702eacacd4d 100644 --- a/Microsoft.Toolkit.Uwp.UI.Animations/ConnectedAnimations/ConnectedAnimationHelper.cs +++ b/Microsoft.Toolkit.Uwp.UI.Animations/ConnectedAnimations/ConnectedAnimationHelper.cs @@ -50,8 +50,7 @@ internal void SetParameterForNextFrameNavigation(object parameter) private void Frame_Navigating(object sender, Windows.UI.Xaml.Navigation.NavigatingCancelEventArgs e) { - object parameter = null; - + object parameter; if (_nextParameter != null) { parameter = _nextParameter; diff --git a/Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ExpressionNodes/ExpressionNode.cs b/Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ExpressionNodes/ExpressionNode.cs index 44fcd7ef4d8..48464ef9e4c 100644 --- a/Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ExpressionNodes/ExpressionNode.cs +++ b/Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ExpressionNodes/ExpressionNode.cs @@ -473,7 +473,7 @@ private string GetOperationString() private string ToExpressionStringInternal() { - string ret = string.Empty; + string ret; // Do a recursive depth-first traversal of the node tree to print out the full expression string switch (GetOperationKind()) diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/Automation/DataGridAutomationPeer.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/Automation/DataGridAutomationPeer.cs index 980586b3bf1..c2537307b49 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/Automation/DataGridAutomationPeer.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/Automation/DataGridAutomationPeer.cs @@ -724,8 +724,7 @@ internal void PopulateItemPeers() { if (item != null) { - DataGridItemAutomationPeer peer = null; - + DataGridItemAutomationPeer peer; if (oldChildren.ContainsKey(item)) { peer = oldChildren[item] as DataGridItemAutomationPeer; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs index 46ae26a4def..a4099d34afe 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.cs @@ -3199,7 +3199,7 @@ public void ScrollIntoView(object item, DataGridColumn column) } else { - int slot = -1; + int slot; DataGridRowGroupInfo rowGroupInfo = null; ICollectionViewGroup collectionViewGroup = item as ICollectionViewGroup; if (collectionViewGroup != null) @@ -3207,7 +3207,7 @@ public void ScrollIntoView(object item, DataGridColumn column) rowGroupInfo = RowGroupInfoFromCollectionViewGroup(collectionViewGroup); if (rowGroupInfo == null) { - Debug.Assert(false, "Expected non-null rowGroupInfo."); + Debug.Fail("Expected non-null rowGroupInfo."); return; } @@ -5631,13 +5631,12 @@ private void DataGrid_GotFocus(object sender, RoutedEventArgs e) } } - // Keep track of which row contains the newly focused element - DataGridRow focusedRow = null; DependencyObject focusedElement = e.OriginalSource as DependencyObject; _focusedObject = focusedElement; while (focusedElement != null) { - focusedRow = focusedElement as DataGridRow; + // Keep track of which row contains the newly focused element + var focusedRow = focusedElement as DataGridRow; if (focusedRow != null && focusedRow.OwningGrid == this && _focusedRow != focusedRow) { ResetFocusedRow(); @@ -5697,8 +5696,7 @@ private void DataGrid_KeyUp(object sender, KeyRoutedEventArgs e) { if (this.ColumnHeaders != null && this.AreColumnHeadersVisible) { - bool ctrl, shift; - KeyboardHelper.GetMetaKeyState(out ctrl, out shift); + KeyboardHelper.GetMetaKeyState(out _, out var shift); if (shift && this.LastHandledKeyDown != VirtualKey.Tab) { @@ -6598,7 +6596,7 @@ private void MakeFirstDisplayedCellCurrentCell() // No current cell, therefore no selection either - try to set the current cell to the // ItemsSource's ICollectionView.CurrentItem if it exists, otherwise use the first displayed cell. - int slot = 0; + int slot; if (this.DataConnection.CollectionView != null) { if (this.DataConnection.CollectionView.IsCurrentBeforeFirst || diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs index a7fbf293b1e..f7409ced760 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridCellsPresenter.cs @@ -275,7 +275,7 @@ protected override Size MeasureOverride(Size availableSize) if (this.OwningGrid.UsesStarSizing && !this.OwningGrid.AutoSizingColumns) { double adjustment = this.OwningGrid.CellsWidth - totalDisplayWidth; - totalDisplayWidth += adjustment - this.OwningGrid.AdjustColumnWidths(0, adjustment, false); + this.OwningGrid.AdjustColumnWidths(0, adjustment, false); // Since we didn't know the final widths of the columns until we resized, // we waited until now to measure each cell diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeader.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeader.cs index d3d0a5a1339..fa972cf7f98 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeader.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeader.cs @@ -712,7 +712,6 @@ private void DataGridColumnHeader_PointerReleased(object sender, PointerRoutedEv { // Completed a click or tap without dragging, so raise the DataGrid.Sorting event. InvokeProcessSort(); - handled = true; break; } @@ -897,8 +896,7 @@ private int GetReorderingTargetDisplayIndex(Point pointerPositionHeaders) { Debug.Assert(this.OwningGrid != null, "Expected non-null OwningGrid."); - double scrollAmount = 0; - DataGridColumn targetColumn = GetReorderingTargetColumn(pointerPositionHeaders, false /*scroll*/, out scrollAmount); + DataGridColumn targetColumn = GetReorderingTargetColumn(pointerPositionHeaders, false /*scroll*/, out _); if (targetColumn != null) { return targetColumn.DisplayIndex > this.OwningColumn.DisplayIndex ? targetColumn.DisplayIndex - 1 : targetColumn.DisplayIndex; @@ -1009,8 +1007,7 @@ private void OnPointerMove_Reorder(ref bool handled, Pointer pointer, Point poin this.OwningGrid.OnColumnHeaderDragDelta(dragDeltaEventArgs); // Find header we're hovering over - double scrollAmount = 0; - DataGridColumn targetColumn = GetReorderingTargetColumn(pointerPositionHeaders, !this.OwningColumn.IsFrozen /*scroll*/, out scrollAmount); + DataGridColumn targetColumn = GetReorderingTargetColumn(pointerPositionHeaders, !this.OwningColumn.IsFrozen /*scroll*/, out var scrollAmount); this.OwningGrid.ColumnHeaders.DragIndicatorOffset = pointerPosition.X - interactionInfo.DragStart.Value.X + scrollAmount; this.OwningGrid.ColumnHeaders.InvalidateArrange(); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs index f2f9efe104b..7f0d0ea763f 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumnHeadersPresenter.cs @@ -360,12 +360,12 @@ protected override Size MeasureOverride(Size availableSize) if (this.OwningGrid.UsesStarSizing && !this.OwningGrid.AutoSizingColumns) { double adjustment = double.IsPositiveInfinity(availableSize.Width) ? this.OwningGrid.CellsWidth : availableSize.Width - totalDisplayWidth; - totalDisplayWidth += adjustment - this.OwningGrid.AdjustColumnWidths(0, adjustment, false); + this.OwningGrid.AdjustColumnWidths(0, adjustment, false); // Since we didn't know the final widths of the columns until we resized, // we waited until now to measure each header double leftEdge = 0; - foreach (DataGridColumn column in this.OwningGrid.ColumnsInternal.GetVisibleColumns()) + foreach (var column in this.OwningGrid.ColumnsInternal.GetVisibleColumns()) { column.ComputeLayoutRoundedWidth(leftEdge); column.HeaderCell.Measure(new Size(column.LayoutRoundedWidth, double.PositiveInfinity)); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumns.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumns.cs index ffa82e39272..97b55a71caf 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumns.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridColumns.cs @@ -1136,7 +1136,6 @@ private void AutoGenerateColumnsPrivate() private bool ComputeDisplayedColumns() { bool invalidate = false; - int numVisibleScrollingCols = 0; int visibleScrollingColumnsTmp = 0; double displayWidth = this.CellsWidth; double cx = 0; @@ -1194,7 +1193,7 @@ private bool ComputeDisplayedColumns() dataGridColumn = this.ColumnsInternal.GetNextVisibleColumn(dataGridColumn); } - numVisibleScrollingCols = visibleScrollingColumnsTmp; + var numVisibleScrollingCols = visibleScrollingColumnsTmp; // if we inflate the data area then we paint columns to the left of firstDisplayedScrollingCol if (cx < displayWidth) diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs index a7d8ca81265..d584336951c 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridDataConnection.cs @@ -538,8 +538,7 @@ public bool GetPropertyIsReadOnly(string propertyName) return true; } - object[] index = null; - propertyInfo = propertyType.GetPropertyOrIndexer(propertyNames[i], out index); + propertyInfo = propertyType.GetPropertyOrIndexer(propertyNames[i], out _); if (propertyInfo == null || propertyInfo.GetIsReadOnly()) { // Either the property doesn't exist or it does exist but is read-only. @@ -547,8 +546,7 @@ public bool GetPropertyIsReadOnly(string propertyName) } // Check if EditableAttribute is defined on the property and if it indicates uneditable - EditableAttribute editableAttribute = null; - editableAttribute = propertyInfo.GetCustomAttributes().OfType().FirstOrDefault(); + var editableAttribute = propertyInfo.GetCustomAttributes().OfType().FirstOrDefault(); if (editableAttribute != null && !editableAttribute.AllowEdit) { return true; @@ -705,9 +703,7 @@ internal void MoveCurrentTo(object item, int backupSlot, int columnIndex, DataGr _scrollForCurrentChanged = scrollIntoView; _backupSlotForCurrentChanged = backupSlot; - bool itemIsCollectionViewGroup = false; - - itemIsCollectionViewGroup = item is ICollectionViewGroup; + var itemIsCollectionViewGroup = item is ICollectionViewGroup; this.CollectionView.MoveCurrentTo((itemIsCollectionViewGroup || this.IndexOf(item) == this.NewItemPlaceholderIndex) ? null : item); _expectingCurrentChanged = false; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridError.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridError.cs index ebb55c374bc..e4eff6267a8 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridError.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridError.cs @@ -84,7 +84,7 @@ public static ArgumentException ValueIsNotAnInstanceOfEitherOr(string paramName, public static ArgumentOutOfRangeException ValueMustBeBetween(string paramName, string valueName, object lowValue, bool lowInclusive, object highValue, bool highInclusive) { - string message = null; + string message; if (lowInclusive && highInclusive) { diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRows.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRows.cs index fb524f71a56..330de25883d 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRows.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRows.cs @@ -1537,7 +1537,7 @@ private void ExpandSlots(int startSlot, int endSlot, bool isHeaderDisplayed, ref // Figure out which slots actually need to be expanded since some might already be collapsed double currentHeightChange = 0; int firstSlot = startSlot; - int lastSlot = endSlot; + int lastSlot; while (firstSlot <= endSlot) { firstSlot = _collapsedSlotsTable.GetNextIndex(firstSlot - 1); @@ -1553,9 +1553,8 @@ private void ExpandSlots(int startSlot, int endSlot, bool isHeaderDisplayed, ref if (!isHeaderDisplayed) { // Estimate the height change if the slots aren't displayed. If they are displayed, we can add real values - double headerHeight = 0; double rowCount = lastSlot - firstSlot + 1; - rowCount -= GetRowGroupHeaderCount(firstSlot, lastSlot, Visibility.Collapsed, out headerHeight); + rowCount -= GetRowGroupHeaderCount(firstSlot, lastSlot, Visibility.Collapsed, out var headerHeight); double detailsCount = GetDetailsCountInclusive(firstSlot, lastSlot); currentHeightChange += headerHeight + (detailsCount * this.RowDetailsHeightEstimate) + (rowCount * this.RowHeightEstimate); } @@ -1747,9 +1746,8 @@ private double GetExactSlotElementHeight(int slot) // Returns an estimate for the height of the slots between fromSlot and toSlot private double GetHeightEstimate(int fromSlot, int toSlot) { - double headerHeight = 0; double rowCount = toSlot - fromSlot + 1; - rowCount -= GetRowGroupHeaderCount(fromSlot, toSlot, Visibility.Visible, out headerHeight); + rowCount -= GetRowGroupHeaderCount(fromSlot, toSlot, Visibility.Visible, out var headerHeight); double detailsCount = GetDetailsCountInclusive(fromSlot, toSlot); return headerHeight + (detailsCount * this.RowDetailsHeightEstimate) + (rowCount * this.RowHeightEstimate); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridTemplateColumn.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridTemplateColumn.cs index 01dfee11fd2..5a9a7e527fc 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridTemplateColumn.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridTemplateColumn.cs @@ -82,7 +82,7 @@ internal bool HasDistinctTemplates /// The previous, unedited value in the cell being edited. protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue) { - editingElement = GenerateEditingElement(null, null); + _ = GenerateEditingElement(null, null); } /// diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/IndexToValueTable.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/IndexToValueTable.cs index 0117ec382d9..a850e54665f 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/IndexToValueTable.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/IndexToValueTable.cs @@ -428,10 +428,7 @@ public int GetNthIndex(int n) /// /// index to search for /// the value at the given index or the default value if index is not in the table - public T GetValueAt(int index) - { - return GetValueAt(index, out bool found); - } + public T GetValueAt(int index) => GetValueAt(index, out _); /// /// Returns the value at a given index or the default value if the index is not in the table @@ -697,7 +694,7 @@ private void AddValuesPrivate(int startIndex, int count, T value, int? startRang } else { - int lowerRangeIndex = startRangeIndex.HasValue ? startRangeIndex.Value : this.FindRangeIndex(startIndex); + int lowerRangeIndex = startRangeIndex ?? this.FindRangeIndex(startIndex); Range lowerRange = (lowerRangeIndex < 0) ? null : _list[lowerRangeIndex]; if (lowerRange == null) { @@ -770,7 +767,7 @@ private int FindRangeIndex(int index) // Do a binary search for the index int front = 0; int end = _list.Count - 1; - Range range = null; + Range range; while (end > front) { int median = (front + end) / 2; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/TypeHelper.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/TypeHelper.cs index 21e60652634..3792cb88f4c 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/TypeHelper.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/Utilities/TypeHelper.cs @@ -176,8 +176,7 @@ internal static PropertyInfo GetNestedProperty(this Type parentType, string prop List propertyNames = SplitPropertyPath(propertyPath); for (int i = 0; i < propertyNames.Count; i++) { - object[] index = null; - propertyInfo = propertyType.GetPropertyOrIndexer(propertyNames[i], out index); + propertyInfo = propertyType.GetPropertyOrIndexer(propertyNames[i], out var index); if (propertyInfo == null) { item = null; @@ -272,9 +271,8 @@ internal static PropertyInfo GetPropertyOrIndexer(this Type type, string propert return null; } - PropertyInfo indexer = null; - string stringIndex = propertyPath.Substring(1, propertyPath.Length - 2); - indexer = FindIndexerInMembers(type.GetDefaultMembers(), stringIndex, out index); + var stringIndex = propertyPath.Substring(1, propertyPath.Length - 2); + var indexer = FindIndexerInMembers(type.GetDefaultMembers(), stringIndex, out index); if (indexer != null) { // We found the indexer, so return it. diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/BladeView/BladeView.Properties.cs b/Microsoft.Toolkit.Uwp.UI.Controls/BladeView/BladeView.Properties.cs index ecdaa957b40..9d56a557840 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/BladeView/BladeView.Properties.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/BladeView/BladeView.Properties.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using Windows.Foundation; using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; namespace Microsoft.Toolkit.Uwp.UI.Controls { @@ -69,7 +68,6 @@ public int AutoCollapseCountThreshold private static void OnBladeModeChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var bladeView = (BladeView)dependencyObject; - var bladeScrollViewer = bladeView.GetScrollViewer(); if (bladeView.BladeMode == BladeMode.Fullscreen) { diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs b/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs index 991199ffcb1..b5b9dff9138 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/Carousel/CarouselPanel.cs @@ -141,9 +141,6 @@ internal void OnManipulationCompleted(object sender, ManipulationCompletedRouted // Need to know which direction we took for this manipulation. var translation = Carousel.Orientation == Orientation.Horizontal ? e.Cumulative.Translation.X : e.Cumulative.Translation.Y; - // if manipulation is not enough to change index we will have to force refresh - var lastIndex = Carousel.SelectedIndex; - // potentially border effects bool hasBreak = false; @@ -250,10 +247,8 @@ protected override Size MeasureOverride(Size availableSize) } } - var width = 0d; - var height = 0d; - // It's a Auto size, so we define the size should be 3 items + double width; if (double.IsInfinity(availableSize.Width)) { width = Carousel.Orientation == Orientation.Horizontal ? containerWidth * (Children.Count > 3 ? 3 : Children.Count) : containerWidth; @@ -264,6 +259,7 @@ protected override Size MeasureOverride(Size availableSize) } // It's a Auto size, so we define the size should be 3 items + double height; if (double.IsInfinity(availableSize.Height)) { height = Carousel.Orientation == Orientation.Vertical ? containerHeight * (Children.Count > 3 ? 3 : Children.Count) : containerHeight; @@ -385,7 +381,6 @@ private void ApplyProjection(UIElement element, Proj proj, Storyboard storyboard /// Return the new projection private Proj GetProjectionFromManipulation(UIElement element, double delta) { - PlaneProjection projection = element.Projection as PlaneProjection; CompositeTransform compositeTransform = element.RenderTransform as CompositeTransform; var bounds = Carousel.Orientation == Orientation.Horizontal ? desiredWidth : desiredHeight; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Animations.cs b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Animations.cs index 4087d1faa84..2ad3c7b3243 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Animations.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Animations.cs @@ -97,7 +97,6 @@ private static List GetRectKeyframes(Rect from, Rect to, { var rectKeyframes = new List(); var step = TimeSpan.FromMilliseconds(10); - var total = duration.TotalMilliseconds; var startPointFrom = new Point(from.X, from.Y); var endPointFrom = new Point(from.X + from.Width, from.Y + from.Height); var startPointTo = new Point(to.X, to.Y); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs index 1f47e0f822b..82614619a95 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Events.cs @@ -7,7 +7,6 @@ using Windows.System; using Windows.UI.Core; using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; namespace Microsoft.Toolkit.Uwp.UI.Controls @@ -26,12 +25,12 @@ private void ImageCropperThumb_KeyDown(object sender, KeyRoutedEventArgs e) diffPos.X--; var upKeyState = Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Up); var downKeyState = Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Down); - if (Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Up) == CoreVirtualKeyStates.Down) + if (upKeyState == CoreVirtualKeyStates.Down) { diffPos.Y--; } - if (Window.Current.CoreWindow.GetAsyncKeyState(VirtualKey.Down) == CoreVirtualKeyStates.Down) + if (downKeyState == CoreVirtualKeyStates.Down) { diffPos.Y++; } diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Logic.cs b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Logic.cs index 5f6a023ef46..44c216e0e7f 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Logic.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/ImageCropper/ImageCropper.Logic.cs @@ -6,7 +6,6 @@ using System.Numerics; using Windows.Foundation; using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Hosting; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; @@ -103,7 +102,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) return; } - double radian = 0d, diffPointRadian = 0d, effectiveLength = 0d; + double radian = 0d, diffPointRadian = 0d; if (KeepAspectRatio) { radian = Math.Atan(UsedAspectRatio); @@ -178,7 +177,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) case ThumbPosition.UpperLeft: if (KeepAspectRatio) { - effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); + var effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); var originSizeChange = new Point(-effectiveLength * Math.Sin(radian), -effectiveLength * Math.Cos(radian)); var safeChange = GetSafeSizeChangeWhenKeepAspectRatio(_restrictedSelectRect, position, currentSelectedRect, originSizeChange, UsedAspectRatio); diffPos.X = -safeChange.X; @@ -192,7 +191,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) if (KeepAspectRatio) { diffPointRadian = -diffPointRadian; - effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); + var effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); var originSizeChange = new Point(-effectiveLength * Math.Sin(radian), -effectiveLength * Math.Cos(radian)); var safeChange = GetSafeSizeChangeWhenKeepAspectRatio(_restrictedSelectRect, position, currentSelectedRect, originSizeChange, UsedAspectRatio); diffPos.X = safeChange.X; @@ -206,7 +205,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) if (KeepAspectRatio) { diffPointRadian = -diffPointRadian; - effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); + var effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); var originSizeChange = new Point(effectiveLength * Math.Sin(radian), effectiveLength * Math.Cos(radian)); var safeChange = GetSafeSizeChangeWhenKeepAspectRatio(_restrictedSelectRect, position, currentSelectedRect, originSizeChange, UsedAspectRatio); diffPos.X = -safeChange.X; @@ -219,7 +218,7 @@ private void UpdateCroppedRect(ThumbPosition position, Point diffPos) case ThumbPosition.LowerRight: if (KeepAspectRatio) { - effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); + var effectiveLength = diffPos.Y / Math.Cos(diffPointRadian) * Math.Cos(diffPointRadian - radian); var originSizeChange = new Point(effectiveLength * Math.Sin(radian), effectiveLength * Math.Cos(radian)); var safeChange = GetSafeSizeChangeWhenKeepAspectRatio(_restrictedSelectRect, position, currentSelectedRect, originSizeChange, UsedAspectRatio); diffPos.X = safeChange.X; diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/InAppNotification/InAppNotification.AttachedProperties.cs b/Microsoft.Toolkit.Uwp.UI.Controls/InAppNotification/InAppNotification.AttachedProperties.cs index be3f45b3c48..a566a9b52cf 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/InAppNotification/InAppNotification.AttachedProperties.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/InAppNotification/InAppNotification.AttachedProperties.cs @@ -43,7 +43,6 @@ private static void OnKeyFrameAnimationChanged(DependencyObject d, DependencyPro { if (e.NewValue is TimeSpan ts) { - var keyTimeFromAnimationDuration = KeyTime.FromTimeSpan(ts); if (d is DoubleKeyFrame dkf) { dkf.KeyTime = KeyTime.FromTimeSpan(ts); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/OrbitView/OrbitView.cs b/Microsoft.Toolkit.Uwp.UI.Controls/OrbitView/OrbitView.cs index 98fd7a3c80a..4cd44307cfc 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/OrbitView/OrbitView.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/OrbitView/OrbitView.cs @@ -622,7 +622,7 @@ private Line CreateAnchor(UIElement element, double x, double y) var elementNode = elementVisual.GetReference(); var centerNode = centerVisual.GetReference(); - ScalarNode expression = null; + ScalarNode expression; var elementY = elementNode.Offset.Y + (elementNode.Size.Y / 2); var centerY = centerNode.Offset.Y + (centerNode.Size.Y / 2); var elementX = elementNode.Offset.X + (elementNode.Size.X / 2); diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/RadialGauge/RadialGauge.cs b/Microsoft.Toolkit.Uwp.UI.Controls/RadialGauge/RadialGauge.cs index f105bed8a10..256a6268757 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/RadialGauge/RadialGauge.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/RadialGauge/RadialGauge.cs @@ -88,7 +88,7 @@ public class RadialGauge : RangeBase /// Identifies the ValueStringFormat dependency property. /// public static readonly DependencyProperty ValueStringFormatProperty = - DependencyProperty.Register(nameof(ValueStringFormat), typeof(string), typeof(RadialGauge), new PropertyMetadata("N0")); + DependencyProperty.Register(nameof(ValueStringFormat), typeof(string), typeof(RadialGauge), new PropertyMetadata("N0", (s, e) => OnValueChanged(s))); /// /// Identifies the TickSpacing dependency property. diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/RadialGauge/RadialGauge.xaml b/Microsoft.Toolkit.Uwp.UI.Controls/RadialGauge/RadialGauge.xaml index 5a70512d6f9..d9b428eceb5 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/RadialGauge/RadialGauge.xaml +++ b/Microsoft.Toolkit.Uwp.UI.Controls/RadialGauge/RadialGauge.xaml @@ -108,7 +108,6 @@ FontSize="20" FontWeight="SemiBold" Foreground="{TemplateBinding Foreground}" - Text="{TemplateBinding Value}" TextAlignment="Center" /> public object Convert(object value, Type targetType, object parameter, string language) { - string finalvalue = string.Empty; + string finalvalue; switch ((string)value) { case "Desktop": diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/RotatorTile/RotatorTile.cs b/Microsoft.Toolkit.Uwp.UI.Controls/RotatorTile/RotatorTile.cs index e68e58e1ab8..2aab5261187 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/RotatorTile/RotatorTile.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/RotatorTile/RotatorTile.cs @@ -168,7 +168,6 @@ private void RotatorTile_Unloaded(object sender, RoutedEventArgs e) /// private void Timer_Tick(object sender, object e) { - var item = GetItemAt(_currentIndex + 1); _timer.Interval = GetTileDuration(); UpdateNextItem(); } @@ -322,7 +321,6 @@ private object GetItemAt(int index) } else if (ItemsSource is IEnumerable) { - var items = ItemsSource as IEnumerable; var ienum = ((IEnumerable)ItemsSource).GetEnumerator(); int count = 0; while (ienum.MoveNext()) @@ -484,7 +482,6 @@ private void Incc_CollectionChanged(object sender, NotifyCollectionChangedEventA } else if (e.Action == NotifyCollectionChangedAction.Add) { - int endIndex = e.NewStartingIndex + e.NewItems.Count; if (e.NewItems?.Count > 0) { if (_currentIndex < 0) diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/Formatter.cs b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/Formatter.cs index 3c4190b36f9..25669a72fe1 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/Formatter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/Formatter.cs @@ -5,7 +5,6 @@ using System; using Microsoft.Toolkit.Uwp.UI.Controls.TextToolbarButtons; using Windows.UI.Text; -using Windows.UI.Xaml.Controls; namespace Microsoft.Toolkit.Uwp.UI.Controls.TextToolbarFormats { @@ -81,8 +80,7 @@ public virtual void EnsureAtNewLine() int counter = 0; bool atNewLine = false; - string docText = string.Empty; - Model.Editor.Document.GetText(TextGetOptions.NoHidden, out docText); + Model.Editor.Document.GetText(TextGetOptions.NoHidden, out var docText); var lines = docText.Split(new string[] { Return }, StringSplitOptions.None); foreach (var line in lines) @@ -176,8 +174,7 @@ public virtual string Text { get { - string currentvalue = string.Empty; - Model.Editor.Document.GetText(TextGetOptions.FormatRtf, out currentvalue); + Model.Editor.Document.GetText(TextGetOptions.FormatRtf, out var currentvalue); return currentvalue; } } diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/MarkDown/MarkDownFormatter.cs b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/MarkDown/MarkDownFormatter.cs index b0874115043..113fe7f77bf 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/MarkDown/MarkDownFormatter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/MarkDown/MarkDownFormatter.cs @@ -440,8 +440,7 @@ public override string Text { get { - string currentvalue = string.Empty; - Model.Editor.Document.GetText(TextGetOptions.UseCrlf, out currentvalue); + Model.Editor.Document.GetText(TextGetOptions.UseCrlf, out var currentvalue); return currentvalue.Replace('\n', '\r'); // Converts CRLF into double Return for Markdown new line. } } diff --git a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/RichText/RichTextFormatter.cs b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/RichText/RichTextFormatter.cs index edd0a94138e..3523ef61193 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/RichText/RichTextFormatter.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar/Formats/RichText/RichTextFormatter.cs @@ -95,8 +95,7 @@ public override string Text { get { - string currentvalue = string.Empty; - Model.Editor.Document.GetText(TextGetOptions.FormatRtf, out currentvalue); + Model.Editor.Document.GetText(TextGetOptions.FormatRtf, out var currentvalue); return currentvalue; } } diff --git a/Microsoft.Toolkit.Uwp.UI/Cache/CacheBase.cs b/Microsoft.Toolkit.Uwp.UI/Cache/CacheBase.cs index a43529a541f..1fa3d1b1716 100644 --- a/Microsoft.Toolkit.Uwp.UI/Cache/CacheBase.cs +++ b/Microsoft.Toolkit.Uwp.UI/Cache/CacheBase.cs @@ -11,7 +11,6 @@ using System.Threading; using System.Threading.Tasks; using Windows.Storage; -using Windows.Storage.Streams; namespace Microsoft.Toolkit.Uwp.UI { @@ -144,7 +143,7 @@ public Task ClearAsync(TimeSpan duration) /// awaitable task public async Task RemoveExpiredAsync(TimeSpan? duration = null) { - TimeSpan expiryDuration = duration.HasValue ? duration.Value : CacheDuration; + TimeSpan expiryDuration = duration ?? CacheDuration; var folder = await GetCacheFolderAsync().ConfigureAwait(false); var files = await folder.GetFilesAsync().AsTask().ConfigureAwait(false); @@ -197,10 +196,7 @@ public async Task RemoveAsync(IEnumerable uriForCachedItems) foreach (var uri in uriForCachedItems) { string fileName = GetCacheFileName(uri); - - StorageFile file = null; - - if (hashDictionary.TryGetValue(fileName, out file)) + if (hashDictionary.TryGetValue(fileName, out var file)) { filesToDelete.Add(file); keys.Add(fileName); @@ -335,10 +331,7 @@ private async Task GetItemAsync(Uri uri, bool throwOnError, bool preCacheOnly T instance = default(T); string fileName = GetCacheFileName(uri); - - ConcurrentRequest request = null; - - _concurrentTasks.TryGetValue(fileName, out request); + _concurrentTasks.TryGetValue(fileName, out var request); // if similar request exists check if it was preCacheOnly and validate that current request isn't preCacheOnly if (request != null && request.EnsureCachedCopy && !preCacheOnly) @@ -372,8 +365,7 @@ private async Task GetItemAsync(Uri uri, bool throwOnError, bool preCacheOnly } finally { - _concurrentTasks.TryRemove(fileName, out request); - request = null; + _concurrentTasks.TryRemove(fileName, out _); } return instance; @@ -381,7 +373,6 @@ private async Task GetItemAsync(Uri uri, bool throwOnError, bool preCacheOnly private async Task GetFromCacheOrDownloadAsync(Uri uri, string fileName, bool preCacheOnly, CancellationToken cancellationToken, List> initializerKeyValues) { - StorageFile baseFile = null; T instance = default(T); if (_inMemoryFileStorage.MaxItemCount > 0) @@ -399,7 +390,7 @@ private async Task GetFromCacheOrDownloadAsync(Uri uri, string fileName, bool } var folder = await GetCacheFolderAsync().ConfigureAwait(false); - baseFile = await folder.TryGetItemAsync(fileName).AsTask().ConfigureAwait(false) as StorageFile; + var baseFile = await folder.TryGetItemAsync(fileName).AsTask().ConfigureAwait(false) as StorageFile; bool downloadDataFile = baseFile == null || await IsFileOutOfDateAsync(baseFile, CacheDuration).ConfigureAwait(false); diff --git a/Microsoft.Toolkit.Uwp.UI/Cache/InMemoryStorage.cs b/Microsoft.Toolkit.Uwp.UI/Cache/InMemoryStorage.cs index d394213f1ce..3383c401062 100644 --- a/Microsoft.Toolkit.Uwp.UI/Cache/InMemoryStorage.cs +++ b/Microsoft.Toolkit.Uwp.UI/Cache/InMemoryStorage.cs @@ -82,11 +82,7 @@ public void Remove(IEnumerable keys) continue; } - InMemoryStorageItem tempItem = null; - - _inMemoryStorage.TryRemove(key, out tempItem); - - tempItem = null; + _inMemoryStorage.TryRemove(key, out _); } } @@ -119,9 +115,7 @@ public void SetItem(InMemoryStorageItem item) /// Valid item if not out of date or return null if out of date or item does not exist public InMemoryStorageItem GetItem(string id, TimeSpan duration) { - InMemoryStorageItem tempItem = null; - - if (!_inMemoryStorage.TryGetValue(id, out tempItem)) + if (!_inMemoryStorage.TryGetValue(id, out var tempItem)) { return null; } @@ -133,7 +127,7 @@ public InMemoryStorageItem GetItem(string id, TimeSpan duration) return tempItem; } - _inMemoryStorage.TryRemove(id, out tempItem); + _inMemoryStorage.TryRemove(id, out _); return null; } diff --git a/Microsoft.Toolkit.Uwp.UI/Extensions/Hyperlink/HyperlinkExtensions.cs b/Microsoft.Toolkit.Uwp.UI/Extensions/Hyperlink/HyperlinkExtensions.cs index 39c346a9be8..e4697182b60 100644 --- a/Microsoft.Toolkit.Uwp.UI/Extensions/Hyperlink/HyperlinkExtensions.cs +++ b/Microsoft.Toolkit.Uwp.UI/Extensions/Hyperlink/HyperlinkExtensions.cs @@ -9,7 +9,7 @@ namespace Microsoft.Toolkit.Uwp.UI { /// - /// Provides attached dependency properties for the content element that allows + /// Provides attached dependency properties for the content element that allows /// it to invoke a when clicked /// public static class HyperlinkExtensions @@ -29,64 +29,51 @@ public static class HyperlinkExtensions /// /// The from which to get the associated instance /// The instance associated with the the or null - public static ICommand GetCommand(Windows.UI.Xaml.Documents.Hyperlink obj) - { - return (ICommand)obj.GetValue(CommandProperty); - } + public static ICommand GetCommand(Hyperlink obj) => (ICommand)obj.GetValue(CommandProperty); /// /// Sets the instance assocaited with the specified /// /// The to associated the instance to /// The instance to bind to the - public static void SetCommand(Windows.UI.Xaml.Documents.Hyperlink obj, ICommand value) - { - obj.SetValue(CommandProperty, value); - } + public static void SetCommand(Hyperlink obj, ICommand value) => obj.SetValue(CommandProperty, value); /// /// Gets the instance assocaited with the specified /// /// The from which to get the associated value /// The value associated with the the or null - public static object GetCommandParameter(Windows.UI.Xaml.Documents.Hyperlink obj) - { - return obj.GetValue(CommandParameterProperty); - } + public static object GetCommandParameter(Hyperlink obj) => obj.GetValue(CommandParameterProperty); /// /// Sets the assocaited with the specified /// /// The to associated the instance to /// The to set the to - public static void SetCommandParameter(Windows.UI.Xaml.Documents.Hyperlink obj, object value) - { - obj.SetValue(CommandParameterProperty, value); - } + public static void SetCommandParameter(Hyperlink obj, object value) => obj.SetValue(CommandParameterProperty, value); private static void OnCommandPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { - Windows.UI.Xaml.Documents.Hyperlink hyperlink = sender as Windows.UI.Xaml.Documents.Hyperlink; - - if (hyperlink != null) + if (sender is Hyperlink hyperlink) { hyperlink.Click -= OnHyperlinkClicked; - ICommand command = args.NewValue as ICommand; - - if (command != null) + if (args.NewValue is ICommand) { hyperlink.Click += OnHyperlinkClicked; } } } - private static void OnHyperlinkClicked(Windows.UI.Xaml.Documents.Hyperlink sender, Windows.UI.Xaml.Documents.HyperlinkClickEventArgs args) + private static void OnHyperlinkClicked(Hyperlink sender, HyperlinkClickEventArgs args) { - ICommand command = GetCommand(sender); - object parameter = GetCommandParameter(sender); + var command = GetCommand(sender); + var parameter = GetCommandParameter(sender); - command?.Execute(parameter); + if (command?.CanExecute(parameter) == true) + { + command.Execute(parameter); + } } } } diff --git a/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxMask/TextBoxMask.cs b/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxMask/TextBoxMask.cs index 5eda2b7b13c..aa06c2fd5da 100644 --- a/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxMask/TextBoxMask.cs +++ b/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxMask/TextBoxMask.cs @@ -261,7 +261,6 @@ private static void Textbox_SelectionChanged(object sender, RoutedEventArgs e) private static void Textbox_TextChanging(TextBox textbox, TextBoxTextChangingEventArgs args) { - var mask = textbox.GetValue(MaskProperty) as string; var escapedMask = textbox.GetValue(EscapedMaskProperty) as string; var escapedChars = textbox.GetValue(EscapedCharacterIndicesProperty) as List; diff --git a/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxRegEx/TextBoxRegex.cs b/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxRegEx/TextBoxRegex.cs index e0d0cb5e277..3cc924678a9 100644 --- a/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxRegEx/TextBoxRegex.cs +++ b/Microsoft.Toolkit.Uwp.UI/Extensions/TextBoxRegEx/TextBoxRegex.cs @@ -62,7 +62,7 @@ private static void ValidateTextBox(TextBox textbox, bool force = true) { var validationType = (ValidationType)textbox.GetValue(ValidationTypeProperty); string regex; - bool regexMatch = false; + bool regexMatch; switch (validationType) { default: diff --git a/Microsoft.Toolkit.Uwp/Deferred/EventHandlerExtensions.cs b/Microsoft.Toolkit.Uwp/Deferred/EventHandlerExtensions.cs index 62b5abcec3a..ee2b2cf5aac 100644 --- a/Microsoft.Toolkit.Uwp/Deferred/EventHandlerExtensions.cs +++ b/Microsoft.Toolkit.Uwp/Deferred/EventHandlerExtensions.cs @@ -3,9 +3,7 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; @@ -16,8 +14,6 @@ namespace Microsoft.Toolkit.Uwp.Deferred /// public static class EventHandlerExtensions { - private static readonly Task CompletedTask = Task.FromResult(0); - /// /// Use to invoke an async using . /// @@ -46,7 +42,7 @@ public static Task InvokeAsync(this EventHandler eventHandler, object send { if (eventHandler == null) { - return CompletedTask; + return Task.CompletedTask; } var tasks = eventHandler.GetInvocationList() @@ -59,7 +55,7 @@ public static Task InvokeAsync(this EventHandler eventHandler, object send var deferral = eventArgs.GetCurrentDeferralAndReset(); - return deferral?.WaitForCompletion(cancellationToken) ?? CompletedTask; + return deferral?.WaitForCompletion(cancellationToken) ?? Task.CompletedTask; }) .ToArray(); diff --git a/Microsoft.Toolkit.Uwp/Deferred/TypedEventHandlerExtensions.cs b/Microsoft.Toolkit.Uwp/Deferred/TypedEventHandlerExtensions.cs index 20a50adcd3d..9e7258e9775 100644 --- a/Microsoft.Toolkit.Uwp/Deferred/TypedEventHandlerExtensions.cs +++ b/Microsoft.Toolkit.Uwp/Deferred/TypedEventHandlerExtensions.cs @@ -15,8 +15,6 @@ namespace Microsoft.Toolkit.Uwp.Deferred /// public static class TypedEventHandlerExtensions { - private static readonly Task CompletedTask = Task.FromResult(0); - /// /// Use to invoke an async using . /// @@ -47,7 +45,7 @@ public static Task InvokeAsync(this TypedEventHandler eventHandler, { if (eventHandler == null) { - return CompletedTask; + return Task.CompletedTask; } var tasks = eventHandler.GetInvocationList() @@ -60,7 +58,7 @@ public static Task InvokeAsync(this TypedEventHandler eventHandler, var deferral = eventArgs.GetCurrentDeferralAndReset(); - return deferral?.WaitForCompletion(cancellationToken) ?? CompletedTask; + return deferral?.WaitForCompletion(cancellationToken) ?? Task.CompletedTask; }) .ToArray(); diff --git a/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs b/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs index b6e0dba55c9..b70792c75a7 100644 --- a/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs +++ b/Microsoft.Toolkit.Uwp/Extensions/StringExtensions.cs @@ -2,13 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Net; -using System.Text.RegularExpressions; -using System.Threading.Tasks; using Windows.ApplicationModel.Resources; namespace Microsoft.Toolkit.Uwp.Extensions @@ -18,7 +11,7 @@ namespace Microsoft.Toolkit.Uwp.Extensions /// public static class StringExtensions { - private static ResourceLoader _independentLoader = ResourceLoader.GetForViewIndependentUse(); + private static readonly ResourceLoader IndependentLoader = ResourceLoader.GetForViewIndependentUse(); /// /// Retrieves the provided resource for the current view context. @@ -26,9 +19,7 @@ public static class StringExtensions /// Resource key to retrieve. /// string value for given resource or empty string if not found. public static string GetViewLocalized(this string resourceKey) - { - return ResourceLoader.GetForCurrentView().GetString(resourceKey); - } + => ResourceLoader.GetForCurrentView().GetString(resourceKey); /// /// Retrieves the provided resource for the given key for use independent of the UI thread. @@ -36,9 +27,7 @@ public static string GetViewLocalized(this string resourceKey) /// Resource key to retrieve. /// string value for given resource or empty string if not found. public static string GetLocalized(this string resourceKey) - { - return _independentLoader.GetString(resourceKey); - } + => IndependentLoader.GetString(resourceKey); /// /// Retrieves the provided resource for the given key for use independent of the UI thread. @@ -47,8 +36,6 @@ public static string GetLocalized(this string resourceKey) /// Resource path to retrieve. /// string value for given resource or empty string if not found. public static string GetLocalized(this string resourceKey, string resourcePath) - { - return ResourceLoader.GetForViewIndependentUse(resourcePath).GetString(resourceKey); - } + => ResourceLoader.GetForViewIndependentUse(resourcePath).GetString(resourceKey); } } diff --git a/Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs b/Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs index 7f400811d85..baebb28059a 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/BackgroundTaskHelper.cs @@ -63,8 +63,10 @@ public static BackgroundTaskRegistration Register(string backgroundTaskName, str } // build the background task - BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); - builder.Name = backgroundTaskName; + BackgroundTaskBuilder builder = new BackgroundTaskBuilder + { + Name = backgroundTaskName + }; // check if we are registering in SPM mode if (backgroundTaskEntryPoint != string.Empty) diff --git a/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/CameraHelper.cs b/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/CameraHelper.cs index 2df16f0c836..4043fe1728c 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/CameraHelper.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/CameraHelper.cs @@ -21,12 +21,10 @@ namespace Microsoft.Toolkit.Uwp.Helpers public class CameraHelper : IDisposable { private static IReadOnlyList _frameSourceGroups; - private SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1); + private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1); private MediaCapture _mediaCapture; private MediaFrameReader _frameReader; private MediaFrameSourceGroup _group; - private MediaFrameSource _previewFrameSource; - private List _frameFormatsAvailable; private bool groupChanged = false; private bool _initialized; @@ -53,7 +51,7 @@ public static async Task> GetFrameSourceGro /// /// Gets a list of available on the source. /// - public List FrameFormatsAvailable { get => _frameFormatsAvailable; } + public IReadOnlyList FrameFormatsAvailable { get; private set; } /// /// Gets or sets the source group for camera video preview. @@ -71,7 +69,7 @@ public MediaFrameSourceGroup FrameSourceGroup /// /// Gets the currently selected for video preview. /// - public MediaFrameSource PreviewFrameSource { get => _previewFrameSource; } + public MediaFrameSource PreviewFrameSource { get; private set; } /// /// Occurs when a new frame arrives. @@ -89,9 +87,9 @@ public async Task InitializeAndStartCaptureAsync() CameraHelperResult result; try { - await semaphoreSlim.WaitAsync(); + await _semaphoreSlim.WaitAsync(); - // if FrameSourceGroup hasn't changed from last initialiazation, just return back. + // if FrameSourceGroup hasn't changed from last initialization, just return back. if (_initialized && _group != null && !groupChanged) { return CameraHelperResult.Success; @@ -130,9 +128,9 @@ public async Task InitializeAndStartCaptureAsync() result = await InitializeMediaCaptureAsync(); - if (_previewFrameSource != null) + if (PreviewFrameSource != null) { - _frameReader = await _mediaCapture.CreateFrameReaderAsync(_previewFrameSource); + _frameReader = await _mediaCapture.CreateFrameReaderAsync(PreviewFrameSource); if (Windows.Foundation.Metadata.ApiInformation.IsPropertyPresent("Windows.Media.Capture.Frames.MediaFrameReader", "AcquisitionMode")) { _frameReader.AcquisitionMode = MediaFrameReaderAcquisitionMode.Realtime; @@ -164,7 +162,7 @@ public async Task InitializeAndStartCaptureAsync() } finally { - semaphoreSlim.Release(); + _semaphoreSlim.Release(); } } @@ -174,7 +172,7 @@ public async Task InitializeAndStartCaptureAsync() /// A representing the asynchronous operation. public async Task CleanUpAsync() { - await semaphoreSlim.WaitAsync(); + await _semaphoreSlim.WaitAsync(); try { _initialized = false; @@ -188,7 +186,7 @@ public async Task CleanUpAsync() } finally { - semaphoreSlim.Release(); + _semaphoreSlim.Release(); } } @@ -211,35 +209,35 @@ private async Task InitializeMediaCaptureAsync() await _mediaCapture.InitializeAsync(settings); // Find the first video preview or record stream available - _previewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoPreview + PreviewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoPreview && source.Value.Info.SourceKind == MediaFrameSourceKind.Color).Value; - if (_previewFrameSource == null) + if (PreviewFrameSource == null) { - _previewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoRecord + PreviewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoRecord && source.Value.Info.SourceKind == MediaFrameSourceKind.Color).Value; } - if (_previewFrameSource == null) + if (PreviewFrameSource == null) { return CameraHelperResult.NoFrameSourceAvailable; } // Get only formats of a certain framerate and compatible subtype for previewing, order them by resolution - _frameFormatsAvailable = _previewFrameSource.SupportedFormats.Where(format => + FrameFormatsAvailable = PreviewFrameSource.SupportedFormats.Where(format => format.FrameRate.Numerator / format.FrameRate.Denominator >= 15 // fps && (string.Compare(format.Subtype, MediaEncodingSubtypes.Nv12, true) == 0 || string.Compare(format.Subtype, MediaEncodingSubtypes.Bgra8, true) == 0 || string.Compare(format.Subtype, MediaEncodingSubtypes.Yuy2, true) == 0 || string.Compare(format.Subtype, MediaEncodingSubtypes.Rgb32, true) == 0))?.OrderBy(format => format.VideoFormat.Width * format.VideoFormat.Height).ToList(); - if (_frameFormatsAvailable == null || !_frameFormatsAvailable.Any()) + if (FrameFormatsAvailable == null || !FrameFormatsAvailable.Any()) { return CameraHelperResult.NoCompatibleFrameFormatAvailable; } - // Set the format with the higest resolution available by default - var defaultFormat = _frameFormatsAvailable.Last(); - await _previewFrameSource.SetFormatAsync(defaultFormat); + // Set the format with the highest resolution available by default + var defaultFormat = FrameFormatsAvailable.Last(); + await PreviewFrameSource.SetFormatAsync(defaultFormat); } catch (UnauthorizedAccessException) { @@ -306,7 +304,8 @@ private void Reader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEvent private bool disposedValue = false; - private async void Dispose(bool disposing) + /// + public async void Dispose() { if (!disposedValue) { @@ -314,11 +313,5 @@ private async void Dispose(bool disposing) await CleanUpAsync(); } } - - /// - public void Dispose() - { - Dispose(true); - } } } diff --git a/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/FrameEventArgs.cs b/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/FrameEventArgs.cs index ce860bffa1e..a3cb0e0ff8d 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/FrameEventArgs.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/CameraHelper/FrameEventArgs.cs @@ -15,9 +15,9 @@ namespace Microsoft.Toolkit.Uwp.Helpers /// public class FrameEventArgs : EventArgs { + private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); private VideoFrame _videoFrame; private VideoFrame _videoFrameCopy; - private SemaphoreSlim _semaphore = new SemaphoreSlim(1); /// /// Gets the video frame. diff --git a/Microsoft.Toolkit.Uwp/Helpers/ObjectStorage/BaseObjectStorageHelper.cs b/Microsoft.Toolkit.Uwp/Helpers/ObjectStorage/BaseObjectStorageHelper.cs index 32c6c41cb6b..c3abcc49fbc 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/ObjectStorage/BaseObjectStorageHelper.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/ObjectStorage/BaseObjectStorageHelper.cs @@ -16,8 +16,6 @@ namespace Microsoft.Toolkit.Uwp.Helpers /// public abstract class BaseObjectStorageHelper : IObjectStorageHelper { - private JsonSerializer serializer = new JsonSerializer(); - /// /// Gets or sets the settings container. /// @@ -67,14 +65,7 @@ public bool KeyExists(string compositeKey, string key) /// The T object public T Read(string key, T @default = default(T)) { - object value = null; - - if (!Settings.Values.TryGetValue(key, out value)) - { - return @default; - } - - if (value == null) + if (!Settings.Values.TryGetValue(key, out var value) || value == null) { return @default; } diff --git a/Microsoft.Toolkit.Uwp/Helpers/PrintHelper/PrintHelperOptions.cs b/Microsoft.Toolkit.Uwp/Helpers/PrintHelper/PrintHelperOptions.cs index 4e66ef6f987..8f4429730e8 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/PrintHelper/PrintHelperOptions.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/PrintHelper/PrintHelperOptions.cs @@ -6,8 +6,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Text; -using System.Threading.Tasks; using Windows.Graphics.Printing; namespace Microsoft.Toolkit.Uwp.Helpers @@ -144,20 +142,5 @@ private void InitializePossibleDisplayOptions() .Where(p => p.PropertyType == typeof(string)) .Select(p => (string)p.GetValue(null)); } - - private void InitializeDefaultOptions() - { - Bordering = PrintBordering.Default; - MediaSize = PrintMediaSize.Default; - MediaType = PrintMediaType.Default; - HolePunch = PrintHolePunch.Default; - Binding = PrintBinding.Default; - Duplex = PrintDuplex.Default; - ColorMode = PrintColorMode.Default; - Collation = PrintCollation.Default; - PrintQuality = PrintQuality.Default; - Staple = PrintStaple.Default; - Orientation = PrintOrientation.Default; - } } } diff --git a/Microsoft.Toolkit.Uwp/Helpers/RemoteDeviceHelper/RemoteDeviceHelper.cs b/Microsoft.Toolkit.Uwp/Helpers/RemoteDeviceHelper/RemoteDeviceHelper.cs index 3f551784a38..ecfa44c2553 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/RemoteDeviceHelper/RemoteDeviceHelper.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/RemoteDeviceHelper/RemoteDeviceHelper.cs @@ -50,33 +50,6 @@ public void GenerateSystems() GenerateSystemsWithFilterAsync(null); } - /// - /// Initiate Enumeration with specific RemoteSystemStatusType - /// - private void GenerateSystemsByFilters(RemoteSystemStatusType remoteSystemStatusType, RemoteSystemAuthorizationKind remoteSystemAuthorizationKind, RemoteSystemDiscoveryType remoteSystemDiscoveryType) - { - var remoteSystemStatusTypeFilter = new RemoteSystemStatusTypeFilter(remoteSystemStatusType); - var remoteSystemDiscoveryTypeFilter = new RemoteSystemDiscoveryTypeFilter(remoteSystemDiscoveryType); - var remoteSystemAuthorizationKindFilter = new RemoteSystemAuthorizationKindFilter(remoteSystemAuthorizationKind); - var filters = new List(); - if (remoteSystemStatusTypeFilter != null) - { - filters.Add(remoteSystemStatusTypeFilter); - } - - if (remoteSystemDiscoveryTypeFilter != null) - { - filters.Add(remoteSystemDiscoveryTypeFilter); - } - - if (remoteSystemAuthorizationKindFilter != null) - { - filters.Add(remoteSystemAuthorizationKindFilter); - } - - GenerateSystemsWithFilterAsync(filters); - } - /// /// Initiate Enumeration with specific RemoteSysemKind with Filters /// diff --git a/Microsoft.Toolkit.Uwp/Helpers/WeakEventListener.cs b/Microsoft.Toolkit.Uwp/Helpers/WeakEventListener.cs index 6dc4082a94d..3a69d3d95dc 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/WeakEventListener.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/WeakEventListener.cs @@ -20,7 +20,7 @@ public sealed class WeakEventListener /// /// WeakReference to the instance listening for the event. /// - private WeakReference weakInstance; + private readonly WeakReference _weakInstance; /// /// Initializes a new instance of the class. @@ -33,7 +33,7 @@ public WeakEventListener(TInstance instance) throw new ArgumentNullException(nameof(instance)); } - weakInstance = new WeakReference(instance); + _weakInstance = new WeakReference(instance); } /// @@ -53,7 +53,7 @@ public WeakEventListener(TInstance instance) /// Event arguments. public void OnEvent(TSource source, TEventArgs eventArgs) { - TInstance target = (TInstance)weakInstance.Target; + var target = (TInstance)_weakInstance.Target; if (target != null) { // Call registered action diff --git a/Microsoft.Toolkit/Converters.cs b/Microsoft.Toolkit/Converters.cs index a7a2ef509ad..20cb290b8b0 100644 --- a/Microsoft.Toolkit/Converters.cs +++ b/Microsoft.Toolkit/Converters.cs @@ -2,10 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; -using System.Text; - namespace Microsoft.Toolkit { /// diff --git a/Microsoft.Toolkit/Diagnostics/Generated/Guard.Collection.g.cs b/Microsoft.Toolkit/Diagnostics/Generated/Guard.Collection.g.cs new file mode 100644 index 00000000000..346241db8cc --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Generated/Guard.Collection.g.cs @@ -0,0 +1,1638 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/* ======================== + * Auto generated file + * ===================== */ + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + public static partial class Guard + { + /// + /// Asserts that the input instance must be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(Span span, string name) + { + if (span.Length != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty(span, name); + } + } + + /// + /// Asserts that the input instance must not be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is == 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(Span span, string name) + { + if (span.Length == 0) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEmptyWithSpan(name); + } + } + + /// + /// Asserts that the input instance must have a size of a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(Span span, int size, string name) + { + if (span.Length != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size not equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(Span span, int size, string name) + { + if (span.Length == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size over a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(Span span, int size, string name) + { + if (span.Length <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of at least or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(Span span, int size, string name) + { + if (span.Length < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(Span span, int size, string name) + { + if (span.Length >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(Span span, int size, string name) + { + if (span.Length > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(span, size, name); + } + } + + /// + /// Asserts that the source instance must have the same size of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(Span source, Span destination, string name) + { + if (source.Length != destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the source instance must have a size of less than or equal to that of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is > the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(Span source, Span destination, string name) + { + if (source.Length > destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the input index is valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is not valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRangeFor(int index, Span span, string name) + { + if ((uint)index >= (uint)span.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRangeFor(index, span, name); + } + } + + /// + /// Asserts that the input index is not valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRangeFor(int index, Span span, string name) + { + if ((uint)index < (uint)span.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(index, span, name); + } + } + + /// + /// Asserts that the input instance must be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(ReadOnlySpan span, string name) + { + if (span.Length != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty(span, name); + } + } + + /// + /// Asserts that the input instance must not be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is == 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(ReadOnlySpan span, string name) + { + if (span.Length == 0) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEmptyWithReadOnlySpan(name); + } + } + + /// + /// Asserts that the input instance must have a size of a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(ReadOnlySpan span, int size, string name) + { + if (span.Length != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size not equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(ReadOnlySpan span, int size, string name) + { + if (span.Length == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size over a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(ReadOnlySpan span, int size, string name) + { + if (span.Length <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of at least or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(ReadOnlySpan span, int size, string name) + { + if (span.Length < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(ReadOnlySpan span, int size, string name) + { + if (span.Length >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan(span, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(ReadOnlySpan span, int size, string name) + { + if (span.Length > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(span, size, name); + } + } + + /// + /// Asserts that the source instance must have the same size of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(ReadOnlySpan source, Span destination, string name) + { + if (source.Length != destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the source instance must have a size of less than or equal to that of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is > the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(ReadOnlySpan source, Span destination, string name) + { + if (source.Length > destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the input index is valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is not valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRangeFor(int index, ReadOnlySpan span, string name) + { + if ((uint)index >= (uint)span.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRangeFor(index, span, name); + } + } + + /// + /// Asserts that the input index is not valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRangeFor(int index, ReadOnlySpan span, string name) + { + if ((uint)index < (uint)span.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(index, span, name); + } + } + + /// + /// Asserts that the input instance must be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(Memory memory, string name) + { + if (memory.Length != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty(memory, name); + } + } + + /// + /// Asserts that the input instance must not be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is == 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(Memory memory, string name) + { + if (memory.Length == 0) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEmpty>(name); + } + } + + /// + /// Asserts that the input instance must have a size of a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(Memory memory, int size, string name) + { + if (memory.Length != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size not equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(Memory memory, int size, string name) + { + if (memory.Length == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size over a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(Memory memory, int size, string name) + { + if (memory.Length <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of at least or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(Memory memory, int size, string name) + { + if (memory.Length < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(Memory memory, int size, string name) + { + if (memory.Length >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(Memory memory, int size, string name) + { + if (memory.Length > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(memory, size, name); + } + } + + /// + /// Asserts that the source instance must have the same size of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(Memory source, Memory destination, string name) + { + if (source.Length != destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the source instance must have a size of less than or equal to that of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is > the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(Memory source, Memory destination, string name) + { + if (source.Length > destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the input index is valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is not valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRangeFor(int index, Memory memory, string name) + { + if ((uint)index >= (uint)memory.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRangeFor(index, memory, name); + } + } + + /// + /// Asserts that the input index is not valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRangeFor(int index, Memory memory, string name) + { + if ((uint)index < (uint)memory.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(index, memory, name); + } + } + + /// + /// Asserts that the input instance must be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(ReadOnlyMemory memory, string name) + { + if (memory.Length != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty(memory, name); + } + } + + /// + /// Asserts that the input instance must not be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is == 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(ReadOnlyMemory memory, string name) + { + if (memory.Length == 0) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEmpty>(name); + } + } + + /// + /// Asserts that the input instance must have a size of a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(ReadOnlyMemory memory, int size, string name) + { + if (memory.Length != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size not equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(ReadOnlyMemory memory, int size, string name) + { + if (memory.Length == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size over a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(ReadOnlyMemory memory, int size, string name) + { + if (memory.Length <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of at least or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(ReadOnlyMemory memory, int size, string name) + { + if (memory.Length < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(ReadOnlyMemory memory, int size, string name) + { + if (memory.Length >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan(memory, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(ReadOnlyMemory memory, int size, string name) + { + if (memory.Length > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(memory, size, name); + } + } + + /// + /// Asserts that the source instance must have the same size of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(ReadOnlyMemory source, Memory destination, string name) + { + if (source.Length != destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the source instance must have a size of less than or equal to that of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is > the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(ReadOnlyMemory source, Memory destination, string name) + { + if (source.Length > destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the input index is valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is not valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRangeFor(int index, ReadOnlyMemory memory, string name) + { + if ((uint)index >= (uint)memory.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRangeFor(index, memory, name); + } + } + + /// + /// Asserts that the input index is not valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRangeFor(int index, ReadOnlyMemory memory, string name) + { + if ((uint)index < (uint)memory.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(index, memory, name); + } + } + + /// + /// Asserts that the input array instance must be empty. + /// + /// The item of items in the input array instance. + /// The input array instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(T[] array, string name) + { + if (array.Length != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty(array, name); + } + } + + /// + /// Asserts that the input array instance must not be empty. + /// + /// The item of items in the input array instance. + /// The input array instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is == 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(T[] array, string name) + { + if (array.Length == 0) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEmpty(name); + } + } + + /// + /// Asserts that the input array instance must have a size of a specified value. + /// + /// The item of items in the input array instance. + /// The input array instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(T[] array, int size, string name) + { + if (array.Length != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(array, size, name); + } + } + + /// + /// Asserts that the input array instance must have a size not equal to a specified value. + /// + /// The item of items in the input array instance. + /// The input array instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(T[] array, int size, string name) + { + if (array.Length == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo(array, size, name); + } + } + + /// + /// Asserts that the input array instance must have a size over a specified value. + /// + /// The item of items in the input array instance. + /// The input array instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(T[] array, int size, string name) + { + if (array.Length <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver(array, size, name); + } + } + + /// + /// Asserts that the input array instance must have a size of at least or equal to a specified value. + /// + /// The item of items in the input array instance. + /// The input array instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(T[] array, int size, string name) + { + if (array.Length < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast(array, size, name); + } + } + + /// + /// Asserts that the input array instance must have a size of less than a specified value. + /// + /// The item of items in the input array instance. + /// The input array instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(T[] array, int size, string name) + { + if (array.Length >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan(array, size, name); + } + } + + /// + /// Asserts that the input array instance must have a size of less than or equal to a specified value. + /// + /// The item of items in the input array instance. + /// The input array instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(T[] array, int size, string name) + { + if (array.Length > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(array, size, name); + } + } + + /// + /// Asserts that the source array instance must have the same size of a destination array instance. + /// + /// The item of items in the input array instance. + /// The source array instance to check the size for. + /// The destination array instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(T[] source, T[] destination, string name) + { + if (source.Length != destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the source array instance must have a size of less than or equal to that of a destination array instance. + /// + /// The item of items in the input array instance. + /// The source array instance to check the size for. + /// The destination array instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is > the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(T[] source, T[] destination, string name) + { + if (source.Length > destination.Length) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(source, destination, name); + } + } + + /// + /// Asserts that the input index is valid for a given array instance. + /// + /// The item of items in the input array instance. + /// The input index to be used to access . + /// The input array instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is not valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRangeFor(int index, T[] array, string name) + { + if ((uint)index >= (uint)array.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRangeFor(index, array, name); + } + } + + /// + /// Asserts that the input index is not valid for a given array instance. + /// + /// The item of items in the input array instance. + /// The input index to be used to access . + /// The input array instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRangeFor(int index, T[] array, string name) + { + if ((uint)index < (uint)array.Length) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(index, array, name); + } + } + + /// + /// Asserts that the input instance must be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(List list, string name) + { + if (list.Count != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty((ICollection)list, name); + } + } + + /// + /// Asserts that the input instance must not be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is == 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(List list, string name) + { + if (list.Count == 0) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEmpty>(name); + } + } + + /// + /// Asserts that the input instance must have a size of a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(List list, int size, string name) + { + if (list.Count != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo((ICollection)list, size, name); + } + } + + /// + /// Asserts that the input instance must have a size not equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(List list, int size, string name) + { + if (list.Count == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo((ICollection)list, size, name); + } + } + + /// + /// Asserts that the input instance must have a size over a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(List list, int size, string name) + { + if (list.Count <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver((ICollection)list, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of at least or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(List list, int size, string name) + { + if (list.Count < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast((ICollection)list, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(List list, int size, string name) + { + if (list.Count >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan((ICollection)list, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(List list, int size, string name) + { + if (list.Count > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo((ICollection)list, size, name); + } + } + + /// + /// Asserts that the source instance must have the same size of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(List source, List destination, string name) + { + if (source.Count != destination.Count) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo((ICollection)source, destination.Count, name); + } + } + + /// + /// Asserts that the source instance must have a size of less than or equal to that of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is > the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(List source, List destination, string name) + { + if (source.Count > destination.Count) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo((ICollection)source, destination.Count, name); + } + } + + /// + /// Asserts that the input index is valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is not valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRangeFor(int index, List list, string name) + { + if ((uint)index >= (uint)list.Count) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRangeFor(index, (ICollection)list, name); + } + } + + /// + /// Asserts that the input index is not valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRangeFor(int index, List list, string name) + { + if ((uint)index < (uint)list.Count) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(index, (ICollection)list, name); + } + } + + /// + /// Asserts that the input instance must be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(ICollection collection, string name) + { + if (collection.Count != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty(collection, name); + } + } + + /// + /// Asserts that the input instance must not be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is == 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(ICollection collection, string name) + { + if (collection.Count == 0) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEmpty>(name); + } + } + + /// + /// Asserts that the input instance must have a size of a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(ICollection collection, int size, string name) + { + if (collection.Count != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size not equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(ICollection collection, int size, string name) + { + if (collection.Count == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size over a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(ICollection collection, int size, string name) + { + if (collection.Count <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of at least or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(ICollection collection, int size, string name) + { + if (collection.Count < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(ICollection collection, int size, string name) + { + if (collection.Count >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(ICollection collection, int size, string name) + { + if (collection.Count > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(collection, size, name); + } + } + + /// + /// Asserts that the source instance must have the same size of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(ICollection source, ICollection destination, string name) + { + if (source.Count != destination.Count) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, destination.Count, name); + } + } + + /// + /// Asserts that the source instance must have a size of less than or equal to that of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is > the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(ICollection source, ICollection destination, string name) + { + if (source.Count > destination.Count) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, destination.Count, name); + } + } + + /// + /// Asserts that the input index is valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is not valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRangeFor(int index, ICollection collection, string name) + { + if ((uint)index >= (uint)collection.Count) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRangeFor(index, collection, name); + } + } + + /// + /// Asserts that the input index is not valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRangeFor(int index, ICollection collection, string name) + { + if ((uint)index < (uint)collection.Count) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(index, collection, name); + } + } + + /// + /// Asserts that the input instance must be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(IReadOnlyCollection collection, string name) + { + if (collection.Count != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty(collection, name); + } + } + + /// + /// Asserts that the input instance must not be empty. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is == 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(IReadOnlyCollection collection, string name) + { + if (collection.Count == 0) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEmpty>(name); + } + } + + /// + /// Asserts that the input instance must have a size of a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(IReadOnlyCollection collection, int size, string name) + { + if (collection.Count != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size not equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(IReadOnlyCollection collection, int size, string name) + { + if (collection.Count == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size over a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(IReadOnlyCollection collection, int size, string name) + { + if (collection.Count <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of at least or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(IReadOnlyCollection collection, int size, string name) + { + if (collection.Count < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(IReadOnlyCollection collection, int size, string name) + { + if (collection.Count >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan(collection, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than or equal to a specified value. + /// + /// The item of items in the input instance. + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(IReadOnlyCollection collection, int size, string name) + { + if (collection.Count > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(collection, size, name); + } + } + + /// + /// Asserts that the source instance must have the same size of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(IReadOnlyCollection source, ICollection destination, string name) + { + if (source.Count != destination.Count) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, destination.Count, name); + } + } + + /// + /// Asserts that the source instance must have a size of less than or equal to that of a destination instance. + /// + /// The item of items in the input instance. + /// The source instance to check the size for. + /// The destination instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is > the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(IReadOnlyCollection source, ICollection destination, string name) + { + if (source.Count > destination.Count) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, destination.Count, name); + } + } + + /// + /// Asserts that the input index is valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is not valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRangeFor(int index, IReadOnlyCollection collection, string name) + { + if ((uint)index >= (uint)collection.Count) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRangeFor(index, collection, name); + } + } + + /// + /// Asserts that the input index is not valid for a given instance. + /// + /// The item of items in the input instance. + /// The input index to be used to access . + /// The input instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRangeFor(int index, IReadOnlyCollection collection, string name) + { + if ((uint)index < (uint)collection.Count) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(index, collection, name); + } + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Generated/Guard.Collection.tt b/Microsoft.Toolkit/Diagnostics/Generated/Guard.Collection.tt new file mode 100644 index 00000000000..37430fced50 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Generated/Guard.Collection.tt @@ -0,0 +1,283 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +<#@include file="TypeInfo.ttinclude" #> +/* ======================== + * Auto generated file + * ===================== */ + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + public static partial class Guard + { +<# +GenerateTextForItems(EnumerableTypes, item => +{ +#> + /// + /// Asserts that the input <#=item.XmlType#> instance must be empty. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input <#=item.XmlType#> instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(<#=item.Type#> <#=item.Name#>, string name) + { + if (<#=item.Name#>.<#=item.Size#> != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty(<#=item.Cast#><#=item.Name#>, name); + } + } + + /// + /// Asserts that the input <#=item.XmlType#> instance must not be empty. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input <#=item.XmlType#> instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is == 0. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(<#=item.Type#> <#=item.Name#>, string name) + { + if (<#=item.Name#>.<#=item.Size#> == 0) + { +<# + if (item.Type == "Span") + { +#> + ThrowHelper.ThrowArgumentExceptionForIsNotEmptyWithSpan(name); +<# + } + else if (item.Type == "ReadOnlySpan") + { +#> + ThrowHelper.ThrowArgumentExceptionForIsNotEmptyWithReadOnlySpan(name); +<# + } + else + { +#> + ThrowHelper.ThrowArgumentExceptionForIsNotEmpty<<#=item.Type#>>(name); +<# + } +#> + } + } + + /// + /// Asserts that the input <#=item.XmlType#> instance must have a size of a specified value. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input <#=item.XmlType#> instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(<#=item.Type#> <#=item.Name#>, int size, string name) + { + if (<#=item.Name#>.<#=item.Size#> != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(<#=item.Cast#><#=item.Name#>, size, name); + } + } + + /// + /// Asserts that the input <#=item.XmlType#> instance must have a size not equal to a specified value. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input <#=item.XmlType#> instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(<#=item.Type#> <#=item.Name#>, int size, string name) + { + if (<#=item.Name#>.<#=item.Size#> == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo(<#=item.Cast#><#=item.Name#>, size, name); + } + } + + /// + /// Asserts that the input <#=item.XmlType#> instance must have a size over a specified value. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input <#=item.XmlType#> instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(<#=item.Type#> <#=item.Name#>, int size, string name) + { + if (<#=item.Name#>.<#=item.Size#> <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver(<#=item.Cast#><#=item.Name#>, size, name); + } + } + + /// + /// Asserts that the input <#=item.XmlType#> instance must have a size of at least or equal to a specified value. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input <#=item.XmlType#> instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(<#=item.Type#> <#=item.Name#>, int size, string name) + { + if (<#=item.Name#>.<#=item.Size#> < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast(<#=item.Cast#><#=item.Name#>, size, name); + } + } + + /// + /// Asserts that the input <#=item.XmlType#> instance must have a size of less than a specified value. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input <#=item.XmlType#> instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(<#=item.Type#> <#=item.Name#>, int size, string name) + { + if (<#=item.Name#>.<#=item.Size#> >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan(<#=item.Cast#><#=item.Name#>, size, name); + } + } + + /// + /// Asserts that the input <#=item.XmlType#> instance must have a size of less than or equal to a specified value. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input <#=item.XmlType#> instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(<#=item.Type#> <#=item.Name#>, int size, string name) + { + if (<#=item.Name#>.<#=item.Size#> > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(<#=item.Cast#><#=item.Name#>, size, name); + } + } + + /// + /// Asserts that the source <#=item.XmlType#> instance must have the same size of a destination <#=item.XmlType#> instance. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The source <#=item.XmlType#> instance to check the size for. + /// The destination <#=item.XmlType#> instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is != the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(<#=item.Type#> source, <#=item.DestinationType#> destination, string name) + { + if (source.<#=item.Size#> != destination.<#=item.Size#>) + { +<# + if (item.HasCountProperty) + { +#> + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(<#=item.Cast#>source, destination.<#=item.Size#>, name); +<# + } + else + { +#> + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(source, <#=item.Cast#>destination, name); +<# + } +#> + } + } + + /// + /// Asserts that the source <#=item.XmlType#> instance must have a size of less than or equal to that of a destination <#=item.XmlType#> instance. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The source <#=item.XmlType#> instance to check the size for. + /// The destination <#=item.XmlType#> instance to check the size for. + /// The name of the input parameter being tested. + /// Thrown if the size of is > the one of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(<#=item.Type#> source, <#=item.DestinationType#> destination, string name) + { + if (source.<#=item.Size#> > destination.<#=item.Size#>) + { +<# + if (item.HasCountProperty) + { +#> + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(<#=item.Cast#>source, destination.<#=item.Size#>, name); +<# + } + else + { +#> + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(source, <#=item.Cast#>destination, name); +<# + } +#> + } + } + + /// + /// Asserts that the input index is valid for a given <#=item.XmlType#> instance. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input index to be used to access . + /// The input <#=item.XmlType#> instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is not valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRangeFor(int index, <#=item.Type#> <#=item.Name#>, string name) + { +<# + /* Here we're leveraging the fact that signed integers are represented + * in 2-complement to perform the bounds check with a single compare operation. + * This is the same trick used throughout CoreCLR as well. + * For more info and code sample, see the original conversation here: + * https://github.com/windows-toolkit/WindowsCommunityToolkit/pull/3131#discussion_r390682835 */ +#> + if ((uint)index >= (uint)<#=item.Name#>.<#=item.Size#>) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRangeFor(index, <#=item.Cast#><#=item.Name#>, name); + } + } + + /// + /// Asserts that the input index is not valid for a given <#=item.XmlType#> instance. + /// + /// The item of items in the input <#=item.XmlType#> instance. + /// The input index to be used to access . + /// The input <#=item.XmlType#> instance to use to validate . + /// The name of the input parameter being tested. + /// Thrown if is valid to access . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRangeFor(int index, <#=item.Type#> <#=item.Name#>, string name) + { + if ((uint)index < (uint)<#=item.Name#>.<#=item.Size#>) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(index, <#=item.Cast#><#=item.Name#>, name); + } + } +<# +}); +#> + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Generated/Guard.Comparable.Numeric.g.cs b/Microsoft.Toolkit/Diagnostics/Generated/Guard.Comparable.Numeric.g.cs new file mode 100644 index 00000000000..ec0d08fd788 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Generated/Guard.Comparable.Numeric.g.cs @@ -0,0 +1,2745 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/* ======================== + * Auto generated file + * ===================== */ + +using System; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + public static partial class Guard + { + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(byte value, byte target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(byte value, byte target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(byte value, byte maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(byte value, byte maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(byte value, byte minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(byte value, byte minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(byte value, byte minimum, byte maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(byte value, byte minimum, byte maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(byte value, byte minimum, byte maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(byte value, byte minimum, byte maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(byte value, byte minimum, byte maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(byte value, byte minimum, byte maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(sbyte value, sbyte target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(sbyte value, sbyte target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(sbyte value, sbyte maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(sbyte value, sbyte maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(sbyte value, sbyte minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(sbyte value, sbyte minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(sbyte value, sbyte minimum, sbyte maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(sbyte value, sbyte minimum, sbyte maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(sbyte value, sbyte minimum, sbyte maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(sbyte value, sbyte minimum, sbyte maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(sbyte value, sbyte minimum, sbyte maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(sbyte value, sbyte minimum, sbyte maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(short value, short target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(short value, short target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(short value, short maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(short value, short maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(short value, short minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(short value, short minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(short value, short minimum, short maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(short value, short minimum, short maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(short value, short minimum, short maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(short value, short minimum, short maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(short value, short minimum, short maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(short value, short minimum, short maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(ushort value, ushort target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(ushort value, ushort target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(ushort value, ushort maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(ushort value, ushort maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(ushort value, ushort minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(ushort value, ushort minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(ushort value, ushort minimum, ushort maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(ushort value, ushort minimum, ushort maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(ushort value, ushort minimum, ushort maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(ushort value, ushort minimum, ushort maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(ushort value, ushort minimum, ushort maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(ushort value, ushort minimum, ushort maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(char value, char target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(char value, char target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(char value, char maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(char value, char maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(char value, char minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(char value, char minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(char value, char minimum, char maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(char value, char minimum, char maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(char value, char minimum, char maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(char value, char minimum, char maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(char value, char minimum, char maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(char value, char minimum, char maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(int value, int target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(int value, int target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(int value, int maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(int value, int maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(int value, int minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(int value, int minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(int value, int minimum, int maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(int value, int minimum, int maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(int value, int minimum, int maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(int value, int minimum, int maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(int value, int minimum, int maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(int value, int minimum, int maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(uint value, uint target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(uint value, uint target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(uint value, uint maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(uint value, uint maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(uint value, uint minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(uint value, uint minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(uint value, uint minimum, uint maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(uint value, uint minimum, uint maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(uint value, uint minimum, uint maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(uint value, uint minimum, uint maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(uint value, uint minimum, uint maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(uint value, uint minimum, uint maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(float value, float target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(float value, float target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(float value, float maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(float value, float maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(float value, float minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(float value, float minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(float value, float minimum, float maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(float value, float minimum, float maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(float value, float minimum, float maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(float value, float minimum, float maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(float value, float minimum, float maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(float value, float minimum, float maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(long value, long target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(long value, long target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(long value, long maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(long value, long maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(long value, long minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(long value, long minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(long value, long minimum, long maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(long value, long minimum, long maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(long value, long minimum, long maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(long value, long minimum, long maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(long value, long minimum, long maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(long value, long minimum, long maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(ulong value, ulong target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(ulong value, ulong target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(ulong value, ulong maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(ulong value, ulong maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(ulong value, ulong minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(ulong value, ulong minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(ulong value, ulong minimum, ulong maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(ulong value, ulong minimum, ulong maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(ulong value, ulong minimum, ulong maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(ulong value, ulong minimum, ulong maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(ulong value, ulong minimum, ulong maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(ulong value, ulong minimum, ulong maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(double value, double target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(double value, double target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(double value, double maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(double value, double maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(double value, double minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(double value, double minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(double value, double minimum, double maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(double value, double minimum, double maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(double value, double minimum, double maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(double value, double minimum, double maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(double value, double minimum, double maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(double value, double minimum, double maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(decimal value, decimal target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(decimal value, decimal target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(decimal value, decimal maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(decimal value, decimal maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(decimal value, decimal minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(decimal value, decimal minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(decimal value, decimal minimum, decimal maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(decimal value, decimal minimum, decimal maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(decimal value, decimal minimum, decimal maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(decimal value, decimal minimum, decimal maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(decimal value, decimal minimum, decimal maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(decimal value, decimal minimum, decimal maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Generated/Guard.Comparable.Numeric.tt b/Microsoft.Toolkit/Diagnostics/Generated/Guard.Comparable.Numeric.tt new file mode 100644 index 00000000000..3cb7ee32093 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Generated/Guard.Comparable.Numeric.tt @@ -0,0 +1,255 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +<#@include file="TypeInfo.ttinclude" #> +/* ======================== + * Auto generated file + * ===================== */ + +using System; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + public static partial class Guard + { +<# +GenerateTextForItems(NumericTypes, type => +{ +#> + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(<#=type#> value, <#=type#> target, string name) + { + if (value != target) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(<#=type#> value, <#=type#> target, string name) + { + if (value == target) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(<#=type#> value, <#=type#> maximum, string name) + { + if (value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(<#=type#> value, <#=type#> maximum, string name) + { + if (value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(<#=type#> value, <#=type#> minimum, string name) + { + if (value <= minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(<#=type#> value, <#=type#> minimum, string name) + { + if (value < minimum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(<#=type#> value, <#=type#> minimum, <#=type#> maximum, string name) + { + if (value < minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(<#=type#> value, <#=type#> minimum, <#=type#> maximum, string name) + { + if (value >= minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(<#=type#> value, <#=type#> minimum, <#=type#> maximum, string name) + { + if (value <= minimum || value >= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(<#=type#> value, <#=type#> minimum, <#=type#> maximum, string name) + { + if (value > minimum && value < maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(<#=type#> value, <#=type#> minimum, <#=type#> maximum, string name) + { + if (value < minimum || value > maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(<#=type#> value, <#=type#> minimum, <#=type#> maximum, string name) + { + if (value >= minimum && value <= maximum) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } +<# +}); +#> + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Generated/Guard.md b/Microsoft.Toolkit/Diagnostics/Generated/Guard.md new file mode 100644 index 00000000000..6b381a62b90 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Generated/Guard.md @@ -0,0 +1,17 @@ +# T4 templates and generated APIs + +This folder contains a number of template files (with the `.tt` or `.ttinclude` extensions) and the generated `.g.cs` files generated by those templates. The template files use the T4 format, which is natively supported by Visual Studio (more info is available [here](https://docs.microsoft.com/en-us/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2019)). + +## Why is this needed? + +There are a few reasons why T4 templates are used for the `Guard` class: + + - Especially when a large number of similar overloads are available for the same APIs, using templates makes it much easier to maintain code and spot mistakes, as the actual number of lines of code to review is much smaller: it's just the code in each template! + - Using type-specific overloads instead of generic methods can result in faster code. For instance, T4 templates are used to generate overloads for comparison APIs (eg. `Guard.IsGreaterThan(int, int, string)`). This results in more compact and optimized code as opposed to a generic method using `where T : IComparable` as type constraint. + - In some cases, using generic methods just isn't possible. For instance, types like `Span` and `ReadOnlySpan` can't be used as generic type parameters, and even if that had been possible, they don't implement an interface we could use in the generic type constraint. Using T4 templates solves this issue, as we can just have specialized method for each supported type or collection type. + +## How to make changes + +If you need to change an API that is declared in a template, or to add a new one, just edit the right `.tt` file and save it: Visual Studio will take care of updating the generated `.g.cs` file automatically. Don't make changes to those generated `.g.cs` files directly, as those will be overwritten as soon as their source template is updated. + +Note that all the `.g.cs` files are checked in into the repository, so if you do make changes to a template file, make sure to also include the updated `.g.cs` file in your commits. diff --git a/Microsoft.Toolkit/Diagnostics/Generated/ThrowHelper.Collection.g.cs b/Microsoft.Toolkit/Diagnostics/Generated/ThrowHelper.Collection.g.cs new file mode 100644 index 00000000000..e40c0d94fe5 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Generated/ThrowHelper.Collection.g.cs @@ -0,0 +1,817 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +/* ======================== + * Auto generated file + * ===================== */ + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Extensions; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] + internal static partial class ThrowHelper + { + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(Span span, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must be empty, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(Span span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must have a size equal to {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(Span span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must have a size not equal to {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(Span span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must have a size over {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(Span span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must have a size of at least {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(Span span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must have a size less than {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(Span span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must have a size less than or equal to {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(Span source, Span destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must have a size equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(Span source, Span destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must have a size less than or equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRangeFor(int index, Span span, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must be in the range given by <0> and {span.Length.ToAssertString()} to be a valid index for the target collection ({typeof(Span).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(int index, Span span, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must not be in the range given by <0> and {span.Length.ToAssertString()} to be an invalid index for the target collection ({typeof(Span).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(ReadOnlySpan span, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must be empty, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(ReadOnlySpan span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must have a size equal to {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(ReadOnlySpan span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must have a size not equal to {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(ReadOnlySpan span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must have a size over {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(ReadOnlySpan span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must have a size of at least {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(ReadOnlySpan span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must have a size less than {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(ReadOnlySpan span, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must have a size less than or equal to {size}, had a size of {span.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(ReadOnlySpan source, Span destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must have a size equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(ReadOnlySpan source, Span destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must have a size less than or equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRangeFor(int index, ReadOnlySpan span, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must be in the range given by <0> and {span.Length.ToAssertString()} to be a valid index for the target collection ({typeof(ReadOnlySpan).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(int index, ReadOnlySpan span, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must not be in the range given by <0> and {span.Length.ToAssertString()} to be an invalid index for the target collection ({typeof(ReadOnlySpan).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(Memory memory, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Memory).ToTypeString()}) must be empty, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(Memory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Memory).ToTypeString()}) must have a size equal to {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(Memory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Memory).ToTypeString()}) must have a size not equal to {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(Memory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Memory).ToTypeString()}) must have a size over {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(Memory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Memory).ToTypeString()}) must have a size of at least {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(Memory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Memory).ToTypeString()}) must have a size less than {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(Memory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Memory).ToTypeString()}) must have a size less than or equal to {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(Memory source, Memory destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(Memory).ToTypeString()}) must have a size equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(Memory source, Memory destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(Memory).ToTypeString()}) must have a size less than or equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRangeFor(int index, Memory memory, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must be in the range given by <0> and {memory.Length.ToAssertString()} to be a valid index for the target collection ({typeof(Memory).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(int index, Memory memory, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must not be in the range given by <0> and {memory.Length.ToAssertString()} to be an invalid index for the target collection ({typeof(Memory).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(ReadOnlyMemory memory, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlyMemory).ToTypeString()}) must be empty, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(ReadOnlyMemory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlyMemory).ToTypeString()}) must have a size equal to {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(ReadOnlyMemory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlyMemory).ToTypeString()}) must have a size not equal to {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(ReadOnlyMemory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlyMemory).ToTypeString()}) must have a size over {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(ReadOnlyMemory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlyMemory).ToTypeString()}) must have a size of at least {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(ReadOnlyMemory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlyMemory).ToTypeString()}) must have a size less than {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(ReadOnlyMemory memory, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlyMemory).ToTypeString()}) must have a size less than or equal to {size}, had a size of {memory.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(ReadOnlyMemory source, Memory destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(ReadOnlyMemory).ToTypeString()}) must have a size equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(ReadOnlyMemory source, Memory destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(ReadOnlyMemory).ToTypeString()}) must have a size less than or equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRangeFor(int index, ReadOnlyMemory memory, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must be in the range given by <0> and {memory.Length.ToAssertString()} to be a valid index for the target collection ({typeof(ReadOnlyMemory).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(int index, ReadOnlyMemory memory, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must not be in the range given by <0> and {memory.Length.ToAssertString()} to be an invalid index for the target collection ({typeof(ReadOnlyMemory).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(T[] array, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T[]).ToTypeString()}) must be empty, had a size of {array.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(T[] array, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T[]).ToTypeString()}) must have a size equal to {size}, had a size of {array.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(T[] array, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T[]).ToTypeString()}) must have a size not equal to {size}, had a size of {array.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(T[] array, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T[]).ToTypeString()}) must have a size over {size}, had a size of {array.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(T[] array, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T[]).ToTypeString()}) must have a size of at least {size}, had a size of {array.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(T[] array, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T[]).ToTypeString()}) must have a size less than {size}, had a size of {array.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(T[] array, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T[]).ToTypeString()}) must have a size less than or equal to {size}, had a size of {array.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(T[] source, T[] destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(T[]).ToTypeString()}) must have a size equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(T[] source, T[] destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(T[]).ToTypeString()}) must have a size less than or equal to {destination.Length.ToAssertString()} (the destination), had a size of {source.Length.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRangeFor(int index, T[] array, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must be in the range given by <0> and {array.Length.ToAssertString()} to be a valid index for the target collection ({typeof(T[]).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(int index, T[] array, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must not be in the range given by <0> and {array.Length.ToAssertString()} to be an invalid index for the target collection ({typeof(T[]).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(List list, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(List).ToTypeString()}) must be empty, had a size of {list.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(List list, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(List).ToTypeString()}) must have a size equal to {size}, had a size of {list.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(List list, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(List).ToTypeString()}) must have a size not equal to {size}, had a size of {list.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(List list, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(List).ToTypeString()}) must have a size over {size}, had a size of {list.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(List list, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(List).ToTypeString()}) must have a size of at least {size}, had a size of {list.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(List list, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(List).ToTypeString()}) must have a size less than {size}, had a size of {list.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(List list, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(List).ToTypeString()}) must have a size less than or equal to {size}, had a size of {list.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(List source, List destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(List).ToTypeString()}) must have a size equal to {destination.Count.ToAssertString()} (the destination), had a size of {source.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(List source, List destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(List).ToTypeString()}) must have a size less than or equal to {destination.Count.ToAssertString()} (the destination), had a size of {source.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRangeFor(int index, List list, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must be in the range given by <0> and {list.Count.ToAssertString()} to be a valid index for the target collection ({typeof(List).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(int index, List list, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must not be in the range given by <0> and {list.Count.ToAssertString()} to be an invalid index for the target collection ({typeof(List).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(ICollection collection, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ICollection).ToTypeString()}) must be empty, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(ICollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ICollection).ToTypeString()}) must have a size equal to {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(ICollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ICollection).ToTypeString()}) must have a size not equal to {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(ICollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ICollection).ToTypeString()}) must have a size over {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(ICollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ICollection).ToTypeString()}) must have a size of at least {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(ICollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ICollection).ToTypeString()}) must have a size less than {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(ICollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ICollection).ToTypeString()}) must have a size less than or equal to {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(ICollection source, ICollection destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(ICollection).ToTypeString()}) must have a size equal to {destination.Count.ToAssertString()} (the destination), had a size of {source.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(ICollection source, ICollection destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(ICollection).ToTypeString()}) must have a size less than or equal to {destination.Count.ToAssertString()} (the destination), had a size of {source.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRangeFor(int index, ICollection collection, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must be in the range given by <0> and {collection.Count.ToAssertString()} to be a valid index for the target collection ({typeof(ICollection).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(int index, ICollection collection, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must not be in the range given by <0> and {collection.Count.ToAssertString()} to be an invalid index for the target collection ({typeof(ICollection).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(IReadOnlyCollection collection, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(IReadOnlyCollection).ToTypeString()}) must be empty, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(IReadOnlyCollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(IReadOnlyCollection).ToTypeString()}) must have a size equal to {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(IReadOnlyCollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(IReadOnlyCollection).ToTypeString()}) must have a size not equal to {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(IReadOnlyCollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(IReadOnlyCollection).ToTypeString()}) must have a size over {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(IReadOnlyCollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(IReadOnlyCollection).ToTypeString()}) must have a size of at least {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(IReadOnlyCollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(IReadOnlyCollection).ToTypeString()}) must have a size less than {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(IReadOnlyCollection collection, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(IReadOnlyCollection).ToTypeString()}) must have a size less than or equal to {size}, had a size of {collection.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(IReadOnlyCollection source, ICollection destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(IReadOnlyCollection).ToTypeString()}) must have a size equal to {destination.Count.ToAssertString()} (the destination), had a size of {source.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(IReadOnlyCollection source, ICollection destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(IReadOnlyCollection).ToTypeString()}) must have a size less than or equal to {destination.Count.ToAssertString()} (the destination), had a size of {source.Count.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRangeFor(int index, IReadOnlyCollection collection, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must be in the range given by <0> and {collection.Count.ToAssertString()} to be a valid index for the target collection ({typeof(IReadOnlyCollection).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(int index, IReadOnlyCollection collection, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must not be in the range given by <0> and {collection.Count.ToAssertString()} to be an invalid index for the target collection ({typeof(IReadOnlyCollection).ToTypeString()}), was {index.ToAssertString()}"); + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Generated/ThrowHelper.Collection.tt b/Microsoft.Toolkit/Diagnostics/Generated/ThrowHelper.Collection.tt new file mode 100644 index 00000000000..4aaac7f607a --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Generated/ThrowHelper.Collection.tt @@ -0,0 +1,131 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. +<#@include file="TypeInfo.ttinclude" #> +/* ======================== + * Auto generated file + * ===================== */ + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Extensions; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] + internal static partial class ThrowHelper + { +<# +GenerateTextForItems(EnumerableTypes, item => +{ +#> + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(<#=item.Type#> <#=item.Name#>, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(<#=item.Type#>).ToTypeString()}) must be empty, had a size of {<#=item.Name#>.<#=item.Size#>.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(<#=item.Type#> <#=item.Name#>, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(<#=item.Type#>).ToTypeString()}) must have a size equal to {size}, had a size of {<#=item.Name#>.<#=item.Size#>.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(<#=item.Type#> <#=item.Name#>, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(<#=item.Type#>).ToTypeString()}) must have a size not equal to {size}, had a size of {<#=item.Name#>.<#=item.Size#>.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(<#=item.Type#> <#=item.Name#>, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(<#=item.Type#>).ToTypeString()}) must have a size over {size}, had a size of {<#=item.Name#>.<#=item.Size#>.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(<#=item.Type#> <#=item.Name#>, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(<#=item.Type#>).ToTypeString()}) must have a size of at least {size}, had a size of {<#=item.Name#>.<#=item.Size#>.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(<#=item.Type#> <#=item.Name#>, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(<#=item.Type#>).ToTypeString()}) must have a size less than {size}, had a size of {<#=item.Name#>.<#=item.Size#>.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(<#=item.Type#> <#=item.Name#>, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(<#=item.Type#>).ToTypeString()}) must have a size less than or equal to {size}, had a size of {<#=item.Name#>.<#=item.Size#>.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(<#=item.Type#> source, <#=item.DestinationType#> destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(<#=item.Type#>).ToTypeString()}) must have a size equal to {destination.<#=item.Size#>.ToAssertString()} (the destination), had a size of {source.<#=item.Size#>.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(<#=item.Type#> source, <#=item.DestinationType#> destination, string name) + { + ThrowArgumentException(name, $"The source {name.ToAssertString()} ({typeof(<#=item.Type#>).ToTypeString()}) must have a size less than or equal to {destination.<#=item.Size#>.ToAssertString()} (the destination), had a size of {source.<#=item.Size#>.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRangeFor(int index, <#=item.Type#> <#=item.Name#>, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must be in the range given by <0> and {<#=item.Name#>.<#=item.Size#>.ToAssertString()} to be a valid index for the target collection ({typeof(<#=item.Type#>).ToTypeString()}), was {index.ToAssertString()}"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRangeFor(int index, <#=item.Type#> <#=item.Name#>, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} (int) must not be in the range given by <0> and {<#=item.Name#>.<#=item.Size#>.ToAssertString()} to be an invalid index for the target collection ({typeof(<#=item.Type#>).ToTypeString()}), was {index.ToAssertString()}"); + } +<# +}); +#> + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Generated/TypeInfo.ttinclude b/Microsoft.Toolkit/Diagnostics/Generated/TypeInfo.ttinclude new file mode 100644 index 00000000000..04e29500538 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Generated/TypeInfo.ttinclude @@ -0,0 +1,97 @@ +<#@ template language="C#"#> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ output extension=".g.cs"#> +<#+ + /// + /// A model representing the info on an enumerable type + /// + sealed class EnumerableTypeInfo + { + public EnumerableTypeInfo( + string type, + string xmlType, + string name, + string size, + string destinationType, + string cast) + { + Type = type; + XmlType = xmlType; + Name = name; + Size = size; + DestinationType = destinationType; + Cast = cast; + } + + /// + /// Gets the name of the current type + /// + public string Type { get; } + + /// + /// Gets the XML-formatted name of the current type (eg. with {T} instead of <T>) + /// + public string XmlType { get; } + + /// + /// Gets the variable name to use + /// + public string Name { get; } + + /// + /// Gets the name of the property to use to retrieve the length of the current type + /// + public string Size { get; } + + /// + /// Gets whether or not the current type has a "Count" property + /// + public bool HasCountProperty => Size == "Count"; + + /// + /// Gets the name of the destination type, when comparing counts across different collections + /// + public string DestinationType { get; } + + /// + /// Gets the (optional) casting to resolve the diamond problem between different interfaces + /// + public string Cast { get; } + } + + /// + /// Gets the list of available enumerable types to generate APIs for + /// + static readonly IReadOnlyList EnumerableTypes = new[] + { + new EnumerableTypeInfo("Span", "", "span", "Length", "Span", ""), + new EnumerableTypeInfo("ReadOnlySpan", "", "span", "Length", "Span", ""), + new EnumerableTypeInfo("Memory", "", "memory", "Length", "Memory", ""), + new EnumerableTypeInfo("ReadOnlyMemory", "", "memory", "Length", "Memory", ""), + new EnumerableTypeInfo("T[]", " array", "array", "Length", "T[]", ""), + new EnumerableTypeInfo("List", "", "list", "Count", "List", "(ICollection)"), + new EnumerableTypeInfo("ICollection", "", "collection", "Count", "ICollection", ""), + new EnumerableTypeInfo("IReadOnlyCollection", "", "collection", "Count", "ICollection", ""), + }; + + /// + /// Gets the list of available numeric types to generate APIs for + /// + static readonly IReadOnlyList NumericTypes = new[] { "byte", "sbyte", "short", "ushort", "char", "int", "uint", "float", "long", "ulong", "double", "decimal" }; + + /// + /// Generates text for a given sequence of items, automatically adding the necessary spacing + /// + void GenerateTextForItems(IReadOnlyList items, Action factory) + { + for (int i = 0; i < items.Count; i++) + { + // Insert a blank line after the first item + if (i > 0) WriteLine(""); + + // Invoke the factory with the current item + factory(items [i]); + } + } +#> \ No newline at end of file diff --git a/Microsoft.Toolkit/Diagnostics/Guard.Comparable.Generic.cs b/Microsoft.Toolkit/Diagnostics/Guard.Comparable.Generic.cs new file mode 100644 index 00000000000..1c974232ecd --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Guard.Comparable.Generic.cs @@ -0,0 +1,387 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + public static partial class Guard + { + /// + /// Asserts that the input value is . + /// + /// The type of value type being tested. + /// The input value to test. + /// The name of the input parameter being tested. + /// Thrown if is not . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsDefault(T value, string name) + where T : struct, IEquatable + { + if (!value.Equals(default)) + { + ThrowHelper.ThrowArgumentExceptionForIsDefault(value, name); + } + } + + /// + /// Asserts that the input value is not . + /// + /// The type of value type being tested. + /// The input value to test. + /// The name of the input parameter being tested. + /// Thrown if is . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotDefault(T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + ThrowHelper.ThrowArgumentExceptionForIsNotDefault(name); + } + } + + /// + /// Asserts that the input value must be equal to a specified value. + /// + /// The type of input values to compare. + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is != . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEqualTo(T value, T target, string name) + where T : notnull, IEquatable + { + if (!value.Equals(target)) + { + ThrowHelper.ThrowArgumentExceptionForIsEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be not equal to a specified value. + /// + /// The type of input values to compare. + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is == . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEqualTo(T value, T target, string name) + where T : notnull, IEquatable + { + if (value.Equals(target)) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEqualTo(value, target, name); + } + } + + /// + /// Asserts that the input value must be a bitwise match with a specified value. + /// + /// The type of input values to compare. + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is not a bitwise match for . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBitwiseEqualTo(T value, T target, string name) + where T : unmanaged + { + /* Include some fast paths if the input type is of size 1, 2, 4 or 8. + * In those cases, just reinterpret the bytes as values of an integer type, + * and compare them directly, which is much faster than having a loop over each byte. + * The conditional branches below are known at compile time by the JIT compiler, + * so that only the right one will actually be translated into native code. */ + if (typeof(T) == typeof(byte) || + typeof(T) == typeof(sbyte) || + typeof(T) == typeof(bool)) + { + byte valueByte = Unsafe.As(ref value); + byte targetByte = Unsafe.As(ref target); + + if (valueByte != targetByte) + { + ThrowHelper.ThrowArgumentExceptionForsBitwiseEqualTo(value, target, name); + } + } + else if (typeof(T) == typeof(ushort) || + typeof(T) == typeof(short) || + typeof(T) == typeof(char)) + { + ushort valueUShort = Unsafe.As(ref value); + ushort targetUShort = Unsafe.As(ref target); + + if (valueUShort != targetUShort) + { + ThrowHelper.ThrowArgumentExceptionForsBitwiseEqualTo(value, target, name); + } + } + else if (typeof(T) == typeof(uint) || + typeof(T) == typeof(int) || + typeof(T) == typeof(float)) + { + uint valueUInt = Unsafe.As(ref value); + uint targetUInt = Unsafe.As(ref target); + + if (valueUInt != targetUInt) + { + ThrowHelper.ThrowArgumentExceptionForsBitwiseEqualTo(value, target, name); + } + } + else if (typeof(T) == typeof(ulong) || + typeof(T) == typeof(long) || + typeof(T) == typeof(double)) + { + ulong valueULong = Unsafe.As(ref value); + ulong targetULong = Unsafe.As(ref target); + + if (valueULong != targetULong) + { + ThrowHelper.ThrowArgumentExceptionForsBitwiseEqualTo(value, target, name); + } + } + else + { + ref byte valueRef = ref Unsafe.As(ref value); + ref byte targetRef = ref Unsafe.As(ref target); + int bytesCount = Unsafe.SizeOf(); + + for (int i = 0; i < bytesCount; i++) + { + byte valueByte = Unsafe.Add(ref valueRef, i); + byte targetByte = Unsafe.Add(ref targetRef, i); + + if (valueByte != targetByte) + { + ThrowHelper.ThrowArgumentExceptionForsBitwiseEqualTo(value, target, name); + } + } + } + } + + /// + /// Asserts that the input value must be less than a specified value. + /// + /// The type of input values to compare. + /// The input value to test. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThan(T value, T maximum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(maximum) >= 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThan(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be less than or equal to a specified value. + /// + /// The type of input values to compare. + /// The input value to test. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsLessThanOrEqualTo(T value, T maximum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(maximum) > 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(value, maximum, name); + } + } + + /// + /// Asserts that the input value must be greater than a specified value. + /// + /// The type of input values to compare. + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThan(T value, T minimum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(minimum) <= 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThan(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be greater than or equal to a specified value. + /// + /// The type of input values to compare. + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsGreaterThanOrEqualTo(T value, T minimum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(minimum) < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(value, minimum, name); + } + } + + /// + /// Asserts that the input value must be in a given range. + /// + /// The type of input values to compare. + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or >= . + /// + /// This API asserts the equivalent of " in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(minimum) < 0 || value.CompareTo(maximum) >= 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given range. + /// + /// The type of input values to compare. + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or < . + /// + /// This API asserts the equivalent of " not in [, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(minimum) >= 0 && value.CompareTo(maximum) < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotInRange(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The type of input values to compare. + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is <= or >= . + /// + /// This API asserts the equivalent of " in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetween(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(minimum) <= 0 || value.CompareTo(maximum) >= 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The type of input values to compare. + /// The input value to test. + /// The exclusive minimum value that is accepted. + /// The exclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is > or < . + /// + /// This API asserts the equivalent of " not in (, )", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetween(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(minimum) > 0 && value.CompareTo(maximum) < 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetween(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must be in a given interval. + /// + /// The type of input values to compare. + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is < or > . + /// + /// This API asserts the equivalent of " in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsBetweenOrEqualTo(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(minimum) < 0 || value.CompareTo(maximum) > 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(value, minimum, maximum, name); + } + } + + /// + /// Asserts that the input value must not be in a given interval. + /// + /// The type of input values to compare. + /// The input value to test. + /// The inclusive minimum value that is accepted. + /// The inclusive maximum value that is accepted. + /// The name of the input parameter being tested. + /// Thrown if is >= or <= . + /// + /// This API asserts the equivalent of " not in [, ]", using arithmetic notation. + /// The method is generic to avoid boxing the parameters, if they are value types. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotBetweenOrEqualTo(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (value.CompareTo(minimum) >= 0 && value.CompareTo(maximum) <= 0) + { + ThrowHelper.ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(value, minimum, maximum, name); + } + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Guard.Comparable.Numeric.cs b/Microsoft.Toolkit/Diagnostics/Guard.Comparable.Numeric.cs new file mode 100644 index 00000000000..712b5fa6784 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Guard.Comparable.Numeric.cs @@ -0,0 +1,166 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + public static partial class Guard + { + /// + /// Asserts that the input value must be within a given distance from a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The maximum distance to allow between and . + /// The name of the input parameter being tested. + /// Thrown if ( - ) > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsCloseTo(int value, int target, uint delta, string name) + { + /* Cast to long before calculating the difference to avoid overflows + * when the values are at the two extremes of the supported range. + * Then cast to double to calculate the absolute value: this allows + * the JIT compiler to use AVX instructions on X64 CPUs instead of + * conditional jumps, which results in more efficient assembly code. + * The IEEE 754 specs guarantees that a 32 bit integer value can + * be stored within a double precision floating point value with + * no loss of precision, so the result will always be correct here. + * The difference is then cast to uint as that's the maximum possible + * value it can have, and comparing two 32 bit integer values + * results in shorter and slightly faster code than using doubles. */ + if ((uint)Math.Abs((double)((long)value - target)) > delta) + { + ThrowHelper.ThrowArgumentExceptionForIsCloseTo(value, target, delta, name); + } + } + + /// + /// Asserts that the input value must not be within a given distance from a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The maximum distance to allow between and . + /// The name of the input parameter being tested. + /// Thrown if ( - ) <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotCloseTo(int value, int target, uint delta, string name) + { + if ((uint)Math.Abs((double)((long)value - target)) <= delta) + { + ThrowHelper.ThrowArgumentExceptionForIsNotCloseTo(value, target, delta, name); + } + } + + /// + /// Asserts that the input value must be within a given distance from a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The maximum distance to allow between and . + /// The name of the input parameter being tested. + /// Thrown if ( - ) > . + [MethodImpl(MethodImplOptions.NoInlining)] + public static void IsCloseTo(long value, long target, ulong delta, string name) + { + /* This method and the one below are not inlined because + * using the decimal type results in quite a bit of code. */ + if ((ulong)Math.Abs((decimal)value - target) > delta) + { + ThrowHelper.ThrowArgumentExceptionForIsCloseTo(value, target, delta, name); + } + } + + /// + /// Asserts that the input value must not be within a given distance from a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The maximum distance to allow between and . + /// The name of the input parameter being tested. + /// Thrown if ( - ) <= . + [MethodImpl(MethodImplOptions.NoInlining)] + public static void IsNotCloseTo(long value, long target, ulong delta, string name) + { + if ((ulong)Math.Abs((decimal)value - target) <= delta) + { + ThrowHelper.ThrowArgumentExceptionForIsNotCloseTo(value, target, delta, name); + } + } + + /// + /// Asserts that the input value must be within a given distance from a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The maximum distance to allow between and . + /// The name of the input parameter being tested. + /// Thrown if ( - ) > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsCloseTo(float value, float target, float delta, string name) + { + if (Math.Abs(value - target) > delta) + { + ThrowHelper.ThrowArgumentExceptionForIsCloseTo(value, target, delta, name); + } + } + + /// + /// Asserts that the input value must not be within a given distance from a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The maximum distance to allow between and . + /// The name of the input parameter being tested. + /// Thrown if ( - ) <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotCloseTo(float value, float target, float delta, string name) + { + if (Math.Abs(value - target) <= delta) + { + ThrowHelper.ThrowArgumentExceptionForIsNotCloseTo(value, target, delta, name); + } + } + + /// + /// Asserts that the input value must be within a given distance from a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The maximum distance to allow between and . + /// The name of the input parameter being tested. + /// Thrown if ( - ) > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsCloseTo(double value, double target, double delta, string name) + { + if (Math.Abs(value - target) > delta) + { + ThrowHelper.ThrowArgumentExceptionForIsCloseTo(value, target, delta, name); + } + } + + /// + /// Asserts that the input value must not be within a given distance from a specified value. + /// + /// The input value to test. + /// The target value to test for. + /// The maximum distance to allow between and . + /// The name of the input parameter being tested. + /// Thrown if ( - ) <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotCloseTo(double value, double target, double delta, string name) + { + if (Math.Abs(value - target) <= delta) + { + ThrowHelper.ThrowArgumentExceptionForIsNotCloseTo(value, target, delta, name); + } + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Guard.IO.cs b/Microsoft.Toolkit/Diagnostics/Guard.IO.cs new file mode 100644 index 00000000000..242f139030a --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Guard.IO.cs @@ -0,0 +1,78 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.IO; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + public static partial class Guard + { + /// + /// Asserts that the input instance must support reading. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if doesn't support reading. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CanRead(Stream stream, string name) + { + if (!stream.CanRead) + { + ThrowHelper.ThrowArgumentExceptionForCanRead(stream, name); + } + } + + /// + /// Asserts that the input instance must support writing. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if doesn't support writing. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CanWrite(Stream stream, string name) + { + if (!stream.CanWrite) + { + ThrowHelper.ThrowArgumentExceptionForCanWrite(stream, name); + } + } + + /// + /// Asserts that the input instance must support seeking. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if doesn't support seeking. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CanSeek(Stream stream, string name) + { + if (!stream.CanSeek) + { + ThrowHelper.ThrowArgumentExceptionForCanSeek(stream, name); + } + } + + /// + /// Asserts that the input instance must be at the starting position. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is not at the starting position. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsAtStartPosition(Stream stream, string name) + { + if (stream.Position != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsAtStartPosition(stream, name); + } + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Guard.String.cs b/Microsoft.Toolkit/Diagnostics/Guard.String.cs new file mode 100644 index 00000000000..05286bee164 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Guard.String.cs @@ -0,0 +1,233 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + public static partial class Guard + { + /// + /// Asserts that the input instance must be or empty. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is neither nor empty. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNullOrEmpty(string? text, string name) + { + if (!string.IsNullOrEmpty(text)) + { + ThrowHelper.ThrowArgumentExceptionForIsNullOrEmpty(text, name); + } + } + + /// + /// Asserts that the input instance must not be or empty. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is or empty. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotNullOrEmpty(string? text, string name) + { + if (string.IsNullOrEmpty(text)) + { + ThrowHelper.ThrowArgumentExceptionForIsNotNullOrEmpty(text, name); + } + } + + /// + /// Asserts that the input instance must be or whitespace. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is neither nor whitespace. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNullOrWhitespace(string? text, string name) + { + if (!string.IsNullOrWhiteSpace(text)) + { + ThrowHelper.ThrowArgumentExceptionForIsNullOrWhitespace(text, name); + } + } + + /// + /// Asserts that the input instance must not be or whitespace. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is or whitespace. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotNullOrWhitespace(string? text, string name) + { + if (string.IsNullOrWhiteSpace(text)) + { + ThrowHelper.ThrowArgumentExceptionForIsNotNullOrWhitespace(text, name); + } + } + + /// + /// Asserts that the input instance must be empty. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is empty. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsEmpty(string text, string name) + { + if (text.Length != 0) + { + ThrowHelper.ThrowArgumentExceptionForIsEmpty(text, name); + } + } + + /// + /// Asserts that the input instance must not be empty. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is empty. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotEmpty(string text, string name) + { + if (text.Length == 0) + { + ThrowHelper.ThrowArgumentExceptionForIsNotEmpty(text, name); + } + } + + /// + /// Asserts that the input instance must be whitespace. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is neither nor whitespace. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsWhitespace(string text, string name) + { + if (!string.IsNullOrWhiteSpace(text)) + { + ThrowHelper.ThrowArgumentExceptionForIsWhitespace(text, name); + } + } + + /// + /// Asserts that the input instance must not be or whitespace. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is or whitespace. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotWhitespace(string text, string name) + { + if (string.IsNullOrWhiteSpace(text)) + { + ThrowHelper.ThrowArgumentExceptionForIsNotWhitespace(text, name); + } + } + + /// + /// Asserts that the input instance must have a size of a specified value. + /// + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is != . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeEqualTo(string text, int size, string name) + { + if (text.Length != size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeEqualTo(text, size, name); + } + } + + /// + /// Asserts that the input instance must have a size not equal to a specified value. + /// + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is == . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeNotEqualTo(string text, int size, string name) + { + if (text.Length == size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeNotEqualTo(text, size, name); + } + } + + /// + /// Asserts that the input instance must have a size over a specified value. + /// + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is <= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeOver(string text, int size, string name) + { + if (text.Length <= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeOver(text, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of at least specified value. + /// + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is < . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeAtLeast(string text, int size, string name) + { + if (text.Length < size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeAtLeast(text, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than a specified value. + /// + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is >= . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThan(string text, int size, string name) + { + if (text.Length >= size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThan(text, size, name); + } + } + + /// + /// Asserts that the input instance must have a size of less than or equal to a specified value. + /// + /// The input instance to check the size for. + /// The target size to test. + /// The name of the input parameter being tested. + /// Thrown if the size of is > . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasSizeLessThanOrEqualTo(string text, int size, string name) + { + if (text.Length > size) + { + ThrowHelper.ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(text, size, name); + } + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Guard.Tasks.cs b/Microsoft.Toolkit/Diagnostics/Guard.Tasks.cs new file mode 100644 index 00000000000..846ef8c30f4 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Guard.Tasks.cs @@ -0,0 +1,170 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + public static partial class Guard + { + /// + /// Asserts that the input instance is in a completed state. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is not in a completed state. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsCompleted(Task task, string name) + { + if (!task.IsCompleted) + { + ThrowHelper.ThrowArgumentExceptionForIsCompleted(task, name); + } + } + + /// + /// Asserts that the input instance is not in a completed state. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is in a completed state. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotCompleted(Task task, string name) + { + if (task.IsCompleted) + { + ThrowHelper.ThrowArgumentExceptionForIsNotCompleted(task, name); + } + } + + /// + /// Asserts that the input instance has been completed successfully. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if has not been completed successfully. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsCompletedSuccessfully(Task task, string name) + { + if (task.Status != TaskStatus.RanToCompletion) + { + ThrowHelper.ThrowArgumentExceptionForIsCompletedSuccessfully(task, name); + } + } + + /// + /// Asserts that the input instance has not been completed successfully. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if has been completed successfully. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotCompletedSuccessfully(Task task, string name) + { + if (task.Status == TaskStatus.RanToCompletion) + { + ThrowHelper.ThrowArgumentExceptionForIsNotCompletedSuccessfully(task, name); + } + } + + /// + /// Asserts that the input instance is faulted. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is not faulted. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsFaulted(Task task, string name) + { + if (!task.IsFaulted) + { + ThrowHelper.ThrowArgumentExceptionForIsFaulted(task, name); + } + } + + /// + /// Asserts that the input instance is not faulted. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is faulted. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotFaulted(Task task, string name) + { + if (task.IsFaulted) + { + ThrowHelper.ThrowArgumentExceptionForIsNotFaulted(task, name); + } + } + + /// + /// Asserts that the input instance is canceled. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is not canceled. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsCanceled(Task task, string name) + { + if (!task.IsCanceled) + { + ThrowHelper.ThrowArgumentExceptionForIsCanceled(task, name); + } + } + + /// + /// Asserts that the input instance is not canceled. + /// + /// The input instance to test. + /// The name of the input parameter being tested. + /// Thrown if is canceled. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotCanceled(Task task, string name) + { + if (task.IsCanceled) + { + ThrowHelper.ThrowArgumentExceptionForIsNotCanceled(task, name); + } + } + + /// + /// Asserts that the input instance has a specific status. + /// + /// The input instance to test. + /// The task status that is accepted. + /// The name of the input parameter being tested. + /// Thrown if doesn't match . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasStatusEqualTo(Task task, TaskStatus status, string name) + { + if (task.Status != status) + { + ThrowHelper.ThrowArgumentExceptionForHasStatusEqualTo(task, status, name); + } + } + + /// + /// Asserts that the input instance has not a specific status. + /// + /// The input instance to test. + /// The task status that is accepted. + /// The name of the input parameter being tested. + /// Thrown if matches . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void HasStatusNotEqualTo(Task task, TaskStatus status, string name) + { + if (task.Status == status) + { + ThrowHelper.ThrowArgumentExceptionForHasStatusNotEqualTo(task, status, name); + } + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/Guard.cs b/Microsoft.Toolkit/Diagnostics/Guard.cs new file mode 100644 index 00000000000..a8703a4c04a --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/Guard.cs @@ -0,0 +1,288 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to verify conditions when running code. + /// + [DebuggerStepThrough] + public static partial class Guard + { + /// + /// Asserts that the input value is . + /// + /// The type of reference value type being tested. + /// The input value to test. + /// The name of the input parameter being tested. + /// Thrown if is not . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1119", Justification = "Negated pattern match expression")] + public static void IsNull(T? value, string name) + where T : class + { + if (!(value is null)) + { + ThrowHelper.ThrowArgumentExceptionForIsNull(value, name); + } + } + + /// + /// Asserts that the input value is . + /// + /// The type of nullable value type being tested. + /// The input value to test. + /// The name of the input parameter being tested. + /// Thrown if is not . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1119", Justification = "Negated pattern match expression")] + public static void IsNull(T? value, string name) + where T : struct + { + if (!(value is null)) + { + ThrowHelper.ThrowArgumentExceptionForIsNull(value, name); + } + } + + /// + /// Asserts that the input value is not . + /// + /// The type of reference value type being tested. + /// The input value to test. + /// The name of the input parameter being tested. + /// Thrown if is . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotNull(T? value, string name) + where T : class + { + if (value is null) + { + ThrowHelper.ThrowArgumentNullExceptionForIsNotNull(name); + } + } + + /// + /// Asserts that the input value is not . + /// + /// The type of nullable value type being tested. + /// The input value to test. + /// The name of the input parameter being tested. + /// Thrown if is . + /// The method is generic to avoid boxing the parameters, if they are value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotNull(T? value, string name) + where T : struct + { + if (value is null) + { + ThrowHelper.ThrowArgumentNullExceptionForIsNotNull(name); + } + } + + /// + /// Asserts that the input value is of a specific type. + /// + /// The type of the input value. + /// The input to test. + /// The name of the input parameter being tested. + /// Thrown if is not of type . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsOfType(object value, string name) + { + if (value.GetType() != typeof(T)) + { + ThrowHelper.ThrowArgumentExceptionForIsOfType(value, name); + } + } + + /// + /// Asserts that the input value is not of a specific type. + /// + /// The type of the input value. + /// The input to test. + /// The name of the input parameter being tested. + /// Thrown if is of type . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotOfType(object value, string name) + { + if (value.GetType() == typeof(T)) + { + ThrowHelper.ThrowArgumentExceptionForIsNotOfType(value, name); + } + } + + /// + /// Asserts that the input value is of a specific type. + /// + /// The input to test. + /// The type to look for. + /// The name of the input parameter being tested. + /// Thrown if the type of is not the same as . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsOfType(object value, Type type, string name) + { + if (value.GetType() != type) + { + ThrowHelper.ThrowArgumentExceptionForIsOfType(value, type, name); + } + } + + /// + /// Asserts that the input value is not of a specific type. + /// + /// The input to test. + /// The type to look for. + /// The name of the input parameter being tested. + /// Thrown if the type of is the same as . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotOfType(object value, Type type, string name) + { + if (value.GetType() == type) + { + ThrowHelper.ThrowArgumentExceptionForIsNotOfType(value, type, name); + } + } + + /// + /// Asserts that the input value can be assigned to a specified type. + /// + /// The type to check the input value against. + /// The input to test. + /// The name of the input parameter being tested. + /// Thrown if can't be assigned to type . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsAssignableToType(object value, string name) + { + if (!(value is T)) + { + ThrowHelper.ThrowArgumentExceptionForIsAssignableToType(value, name); + } + } + + /// + /// Asserts that the input value can't be assigned to a specified type. + /// + /// The type to check the input value against. + /// The input to test. + /// The name of the input parameter being tested. + /// Thrown if can be assigned to type . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotAssignableToType(object value, string name) + { + if (value is T) + { + ThrowHelper.ThrowArgumentExceptionForIsNotAssignableToType(value, name); + } + } + + /// + /// Asserts that the input value can be assigned to a specified type. + /// + /// The input to test. + /// The type to look for. + /// The name of the input parameter being tested. + /// Thrown if can't be assigned to . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsAssignableToType(object value, Type type, string name) + { + if (!type.IsInstanceOfType(value)) + { + ThrowHelper.ThrowArgumentExceptionForIsAssignableToType(value, type, name); + } + } + + /// + /// Asserts that the input value can't be assigned to a specified type. + /// + /// The input to test. + /// The type to look for. + /// The name of the input parameter being tested. + /// Thrown if can be assigned to . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsNotAssignableToType(object value, Type type, string name) + { + if (type.IsInstanceOfType(value)) + { + ThrowHelper.ThrowArgumentExceptionForIsNotAssignableToType(value, type, name); + } + } + + /// + /// Asserts that the input value must be the same instance as the target value. + /// + /// The type of input values to compare. + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is not the same instance as . + /// The method is generic to prevent using it with value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsReferenceEqualTo(T value, T target, string name) + where T : class + { + if (!ReferenceEquals(value, target)) + { + ThrowHelper.ThrowArgumentExceptionForIsReferenceEqualTo(name); + } + } + + /// + /// Asserts that the input value must not be the same instance as the target value. + /// + /// The type of input values to compare. + /// The input value to test. + /// The target value to test for. + /// The name of the input parameter being tested. + /// Thrown if is the same instance as . + /// The method is generic to prevent using it with value types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsReferenceNotEqualTo(T value, T target, string name) + where T : class + { + if (ReferenceEquals(value, target)) + { + ThrowHelper.ThrowArgumentExceptionForIsReferenceNotEqualTo(name); + } + } + + /// + /// Asserts that the input value must be . + /// + /// The input to test. + /// The name of the input parameter being tested. + /// Thrown if is . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsTrue(bool value, string name) + { + if (!value) + { + ThrowHelper.ThrowArgumentExceptionForIsTrue(name); + } + } + + /// + /// Asserts that the input value must be . + /// + /// The input to test. + /// The name of the input parameter being tested. + /// Thrown if is . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IsFalse(bool value, string name) + { + if (value) + { + ThrowHelper.ThrowArgumentExceptionForIsFalse(name); + } + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/ThrowHelper.Collection.Generic.cs b/Microsoft.Toolkit/Diagnostics/ThrowHelper.Collection.Generic.cs new file mode 100644 index 00000000000..7f1a57d1b80 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/ThrowHelper.Collection.Generic.cs @@ -0,0 +1,49 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Extensions; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] + internal static partial class ThrowHelper + { + /// + /// Throws an when fails. + /// + /// This method is needed because can't be used as a generic type parameter. + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotEmptyWithSpan(string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(Span).ToTypeString()}) must not be empty"); + } + + /// + /// Throws an when fails. + /// + /// This method is needed because can't be used as a generic type parameter. + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotEmptyWithReadOnlySpan(string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(ReadOnlySpan).ToTypeString()}) must not be empty"); + } + + /// + /// Throws an when (or an overload) fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotEmpty(string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must not be empty"); + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/ThrowHelper.Comparable.Generic.cs b/Microsoft.Toolkit/Diagnostics/ThrowHelper.Comparable.Generic.cs new file mode 100644 index 00000000000..0dab8651f21 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/ThrowHelper.Comparable.Generic.cs @@ -0,0 +1,148 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Extensions; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] + internal static partial class ThrowHelper + { + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsDefault(T value, string name) + where T : struct + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be the default value {default(T).ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotDefault(string name) + where T : struct + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must not be the default value {default(T).ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEqualTo(T value, T target, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be equal to {target.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotEqualTo(T value, T target, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must not be equal to {target.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsLessThan(T value, T maximum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be less than {maximum.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsLessThanOrEqualTo(T value, T maximum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be less than or equal to {maximum.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsGreaterThan(T value, T minimum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be greater than {minimum.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsGreaterThanOrEqualTo(T value, T minimum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be greater than or equal to {minimum.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsInRange(T value, T minimum, T maximum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be in the range given by {minimum.ToAssertString()} and {maximum.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotInRange(T value, T minimum, T maximum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must not be in the range given by {minimum.ToAssertString()} and {maximum.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsBetween(T value, T minimum, T maximum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be between {minimum.ToAssertString()} and {maximum.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotBetween(T value, T minimum, T maximum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must not be between {minimum.ToAssertString()} and {maximum.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsBetweenOrEqualTo(T value, T minimum, T maximum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be between or equal to {minimum.ToAssertString()} and {maximum.ToAssertString()}, was {value.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentOutOfRangeExceptionForIsNotBetweenOrEqualTo(T value, T minimum, T maximum, string name) + { + ThrowArgumentOutOfRangeException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must not be between or equal to {minimum.ToAssertString()} and {maximum.ToAssertString()}, was {value.ToAssertString()}"); + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/ThrowHelper.Comparable.Numeric.cs b/Microsoft.Toolkit/Diagnostics/ThrowHelper.Comparable.Numeric.cs new file mode 100644 index 00000000000..ab05318ad6c --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/ThrowHelper.Comparable.Numeric.cs @@ -0,0 +1,92 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Extensions; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] + internal static partial class ThrowHelper + { + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsCloseTo(int value, int target, uint delta, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(int).ToTypeString()}) must be within a distance of {delta.ToAssertString()} from {target.ToAssertString()}, was {value.ToAssertString()} and had a distance of {Math.Abs((double)((long)value - target)).ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotCloseTo(int value, int target, uint delta, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(int).ToTypeString()}) must not be within a distance of {delta.ToAssertString()} from {target.ToAssertString()}, was {value.ToAssertString()} and had a distance of {Math.Abs((double)((long)value - target)).ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsCloseTo(long value, long target, ulong delta, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(long).ToTypeString()}) must be within a distance of {delta.ToAssertString()} from {target.ToAssertString()}, was {value.ToAssertString()} and had a distance of {Math.Abs((decimal)value - target).ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotCloseTo(long value, long target, ulong delta, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(long).ToTypeString()}) must not be within a distance of {delta.ToAssertString()} from {target.ToAssertString()}, was {value.ToAssertString()} and had a distance of {Math.Abs((decimal)value - target).ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsCloseTo(float value, float target, float delta, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(float).ToTypeString()}) must be within a distance of {delta.ToAssertString()} from {target.ToAssertString()}, was {value.ToAssertString()} and had a distance of {Math.Abs(value - target).ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotCloseTo(float value, float target, float delta, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(float).ToTypeString()}) must not be within a distance of {delta.ToAssertString()} from {target.ToAssertString()}, was {value.ToAssertString()} and had a distance of {Math.Abs(value - target).ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsCloseTo(double value, double target, double delta, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(double).ToTypeString()}) must be within a distance of {delta.ToAssertString()} from {target.ToAssertString()}, was {value.ToAssertString()} and had a distance of {Math.Abs(value - target).ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotCloseTo(double value, double target, double delta, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(double).ToTypeString()}) must not be within a distance of {delta.ToAssertString()} from {target.ToAssertString()}, was {value.ToAssertString()} and had a distance of {Math.Abs(value - target).ToAssertString()}"); + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/ThrowHelper.IO.cs b/Microsoft.Toolkit/Diagnostics/ThrowHelper.IO.cs new file mode 100644 index 00000000000..5dada175c32 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/ThrowHelper.IO.cs @@ -0,0 +1,57 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Extensions; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] + internal static partial class ThrowHelper + { + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForCanRead(Stream stream, string name) + { + ThrowArgumentException(name, $"Stream {name.ToAssertString()} ({stream.GetType().ToTypeString()}) doesn't support reading"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForCanWrite(Stream stream, string name) + { + ThrowArgumentException(name, $"Stream {name.ToAssertString()} ({stream.GetType().ToTypeString()}) doesn't support writing"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForCanSeek(Stream stream, string name) + { + ThrowArgumentException(name, $"Stream {name.ToAssertString()} ({stream.GetType().ToTypeString()}) doesn't support seeking"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsAtStartPosition(Stream stream, string name) + { + ThrowArgumentException(name, $"Stream {name.ToAssertString()} ({stream.GetType().ToTypeString()}) must be at position {0.ToAssertString()}, was at {stream.Position.ToAssertString()}"); + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/ThrowHelper.String.cs b/Microsoft.Toolkit/Diagnostics/ThrowHelper.String.cs new file mode 100644 index 00000000000..496507b6dc1 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/ThrowHelper.String.cs @@ -0,0 +1,145 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] + internal static partial class ThrowHelper + { + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNullOrEmpty(string? text, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must be null or empty, was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotNullOrEmpty(string? text, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not be null or empty, was {(text is null ? "null" : "empty")}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNullOrWhitespace(string? text, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must be null or whitespace, was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotNullOrWhitespace(string? text, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not be null or whitespace, was {(text is null ? "null" : "whitespace")}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsEmpty(string text, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must be empty, was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotEmpty(string text, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not be empty"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsWhitespace(string text, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must be whitespace, was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotWhitespace(string text, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not be whitespace, was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeEqualTo(string text, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size equal to {size}, had a size of {text.Length} and was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeNotEqualTo(string text, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must not have a size equal to {size}, was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeOver(string text, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size over {size}, had a size of {text.Length} and was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeAtLeast(string text, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size of at least {size}, had a size of {text.Length} and was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThan(string text, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size less than {size}, had a size of {text.Length} and was {text.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasSizeLessThanOrEqualTo(string text, int size, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} (string) must have a size less than or equal to {size}, had a size of {text.Length} and was {text.ToAssertString()}"); + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/ThrowHelper.Tasks.cs b/Microsoft.Toolkit/Diagnostics/ThrowHelper.Tasks.cs new file mode 100644 index 00000000000..9fad34ea8d1 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/ThrowHelper.Tasks.cs @@ -0,0 +1,111 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using Microsoft.Toolkit.Extensions; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] + internal static partial class ThrowHelper + { + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsCompleted(Task task, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must be completed, had status {task.Status.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotCompleted(Task task, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must not be completed, had status {task.Status.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsCompletedSuccessfully(Task task, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must be completed successfully, had status {task.Status.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotCompletedSuccessfully(Task task, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must not be completed successfully, had status {task.Status.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsFaulted(Task task, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must be faulted, had status {task.Status.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotFaulted(Task task, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must not be faulted, had status {task.Status.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsCanceled(Task task, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must be canceled, had status {task.Status.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotCanceled(Task task, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must not be canceled, had status {task.Status.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasStatusEqualTo(Task task, TaskStatus status, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must have status {status}, had status {task.Status.ToAssertString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForHasStatusNotEqualTo(Task task, TaskStatus status, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({task.GetType().ToTypeString()}) must not have status {status.ToAssertString()}"); + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/ThrowHelper.ThrowExceptions.cs b/Microsoft.Toolkit/Diagnostics/ThrowHelper.ThrowExceptions.cs new file mode 100644 index 00000000000..52e270677e9 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/ThrowHelper.ThrowExceptions.cs @@ -0,0 +1,70 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + internal static partial class ThrowHelper + { + /// + /// Returns a formatted representation of the input value. + /// + /// The input to format. + /// A formatted representation of to display in error messages. + [Pure] + private static string ToAssertString(this object? obj) + { + return obj switch + { + string _ => $"\"{obj}\"", + null => "null", + _ => $"<{obj}>" + }; + } + + /// + /// Throws a new . + /// + /// The argument name. + /// The message to include in the exception. + /// Thrown with and . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ThrowArgumentException(string name, string message) + { + throw new ArgumentException(message, name); + } + + /// + /// Throws a new . + /// + /// The argument name. + /// The message to include in the exception. + /// Thrown with and . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ThrowArgumentNullException(string name, string message) + { + throw new ArgumentNullException(name, message); + } + + /// + /// Throws a new . + /// + /// The argument name. + /// The message to include in the exception. + /// Thrown with and . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ThrowArgumentOutOfRangeException(string name, string message) + { + throw new ArgumentOutOfRangeException(name, message); + } + } +} diff --git a/Microsoft.Toolkit/Diagnostics/ThrowHelper.cs b/Microsoft.Toolkit/Diagnostics/ThrowHelper.cs new file mode 100644 index 00000000000..5436d9b48b4 --- /dev/null +++ b/Microsoft.Toolkit/Diagnostics/ThrowHelper.cs @@ -0,0 +1,171 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Extensions; + +#nullable enable + +namespace Microsoft.Toolkit.Diagnostics +{ + /// + /// Helper methods to throw exceptions + /// + [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1618", Justification = "Internal helper methods")] + internal static partial class ThrowHelper + { +#pragma warning disable CS0419 + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNull(T value, string name) + where T : class + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be null, was {value.ToAssertString()} ({value.GetType().ToTypeString()})"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNull(T? value, string name) + where T : struct + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T?).ToTypeString()}) must be null, was {value.ToAssertString()} ({typeof(T).ToTypeString()})"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentNullExceptionForIsNotNull(string name) + { + ThrowArgumentNullException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be not null)"); + } +#pragma warning restore CS0419 + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsOfType(object value, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must be of type {typeof(T).ToTypeString()}, was {value.GetType().ToTypeString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotOfType(object value, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must not be of type {typeof(T).ToTypeString()}, was {value.GetType().ToTypeString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsOfType(object value, Type type, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must be of type {type.ToTypeString()}, was {value.GetType().ToTypeString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotOfType(object value, Type type, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must not be of type {type.ToTypeString()}, was {value.GetType().ToTypeString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsAssignableToType(object value, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must be assignable to type {typeof(T).ToTypeString()}, was {value.GetType().ToTypeString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotAssignableToType(object value, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must not be assignable to type {typeof(T).ToTypeString()}, was {value.GetType().ToTypeString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsAssignableToType(object value, Type type, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must be assignable to type {type.ToTypeString()}, was {value.GetType().ToTypeString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsNotAssignableToType(object value, Type type, string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must not be assignable to type {type.ToTypeString()}, was {value.GetType().ToTypeString()}"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForsBitwiseEqualTo(T value, T target, string name) + where T : unmanaged + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) is not a bitwise match, was <{value.ToHexString()}> instead of <{target.ToHexString()}>"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsReferenceEqualTo(string name) + where T : class + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must be the same instance as the target object"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsReferenceNotEqualTo(string name) + where T : class + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} ({typeof(T).ToTypeString()}) must not be the same instance as the target object"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsTrue(string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must be true, was false"); + } + + /// + /// Throws an when fails. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + public static void ThrowArgumentExceptionForIsFalse(string name) + { + ThrowArgumentException(name, $"Parameter {name.ToAssertString()} must be false, was true"); + } + } +} diff --git a/Microsoft.Toolkit/Extensions/ArrayExtensions.cs b/Microsoft.Toolkit/Extensions/ArrayExtensions.cs index 5e90dcda17c..a7e870492e8 100644 --- a/Microsoft.Toolkit/Extensions/ArrayExtensions.cs +++ b/Microsoft.Toolkit/Extensions/ArrayExtensions.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace Microsoft.Toolkit.Extensions { diff --git a/Microsoft.Toolkit/Extensions/StringExtensions.cs b/Microsoft.Toolkit/Extensions/StringExtensions.cs index 6a979bf0c80..9192cb6810c 100644 --- a/Microsoft.Toolkit/Extensions/StringExtensions.cs +++ b/Microsoft.Toolkit/Extensions/StringExtensions.cs @@ -55,10 +55,7 @@ public static class StringExtensions /// /// The string to test. /// true for a valid email address; otherwise, false. - public static bool IsEmail(this string str) - { - return Regex.IsMatch(str, EmailRegex); - } + public static bool IsEmail(this string str) => Regex.IsMatch(str, EmailRegex); /// /// Determines whether a string is a valid decimal number. @@ -66,39 +63,28 @@ public static bool IsEmail(this string str) /// The string to test. /// true for a valid decimal number; otherwise, false. public static bool IsDecimal(this string str) - { - return decimal.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal _decimal); - } + => decimal.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out _); /// /// Determines whether a string is a valid integer. /// /// The string to test. /// true for a valid integer; otherwise, false. - public static bool IsNumeric(this string str) - { - return int.TryParse(str, out int _integer); - } + public static bool IsNumeric(this string str) => int.TryParse(str, out _); /// /// Determines whether a string is a valid phone number. /// /// The string to test. /// true for a valid phone number; otherwise, false. - public static bool IsPhoneNumber(this string str) - { - return Regex.IsMatch(str, PhoneNumberRegex); - } + public static bool IsPhoneNumber(this string str) => Regex.IsMatch(str, PhoneNumberRegex); /// /// Determines whether a string contains only letters. /// /// The string to test. /// true if the string contains only letters; otherwise, false. - public static bool IsCharacterString(this string str) - { - return Regex.IsMatch(str, CharactersRegex); - } + public static bool IsCharacterString(this string str) => Regex.IsMatch(str, CharactersRegex); /// /// Returns a string representation of an object. @@ -106,10 +92,7 @@ public static bool IsCharacterString(this string str) /// The object to convert. /// String representation of the object. [Obsolete("Use value?.ToString() instead. This will be removed in the next release of the toolkit.")] - public static string ToSafeString(this object value) - { - return value?.ToString(); - } + public static string ToSafeString(this object value) => value?.ToString(); /// /// Returns a string with HTML comments, scripts, styles, and tags removed. @@ -156,10 +139,7 @@ public static string FixHtml(this string html) /// The string to be truncated. /// The maximum length. /// Truncated string. - public static string Truncate(this string value, int length) - { - return Truncate(value, length, false); - } + public static string Truncate(this string value, int length) => Truncate(value, length, false); /// /// Provide better linking for resourced strings. @@ -167,10 +147,7 @@ public static string Truncate(this string value, int length) /// The format of the string being linked. /// The object which will receive the linked String. /// Truncated string. - public static string AsFormat(this string format, params object[] args) - { - return string.Format(format, args); - } + public static string AsFormat(this string format, params object[] args) => string.Format(format, args); /// /// Truncates a string to the specified length. diff --git a/Microsoft.Toolkit/Extensions/TypeExtensions.cs b/Microsoft.Toolkit/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..c012d085daf --- /dev/null +++ b/Microsoft.Toolkit/Extensions/TypeExtensions.cs @@ -0,0 +1,117 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Runtime.CompilerServices; + +#nullable enable + +namespace Microsoft.Toolkit.Extensions +{ + /// + /// Helpers for working with types. + /// + public static class TypeExtensions + { + /// + /// The mapping of built-in types to their simple representation. + /// + private static readonly IReadOnlyDictionary BuiltInTypesMap = new Dictionary + { + [typeof(bool)] = "bool", + [typeof(byte)] = "byte", + [typeof(sbyte)] = "sbyte", + [typeof(short)] = "short", + [typeof(ushort)] = "ushort", + [typeof(char)] = "char", + [typeof(int)] = "int", + [typeof(uint)] = "uint", + [typeof(float)] = "float", + [typeof(long)] = "long", + [typeof(ulong)] = "ulong", + [typeof(double)] = "double", + [typeof(decimal)] = "decimal", + [typeof(object)] = "object", + [typeof(string)] = "string" + }; + + /// + /// A thread-safe mapping of precomputed string representation of types. + /// + private static readonly ConditionalWeakTable DisplayNames = new ConditionalWeakTable(); + + /// + /// Returns a simple string representation of a type. + /// + /// The input type. + /// The string representation of . + [Pure] + public static string ToTypeString(this Type type) + { + // Local function to create the formatted string for a given type + static string FormatDisplayString(Type type) + { + // Primitive types use the keyword name + if (BuiltInTypesMap.TryGetValue(type, out string? typeName)) + { + return typeName!; + } + + // Generic types + if (type.IsGenericType && + type.FullName is { } fullName && + fullName.Split('`') is { } tokens && + tokens.Length > 0 && + tokens[0] is { } genericName && + genericName.Length > 0) + { + var typeArguments = type.GetGenericArguments().Select(FormatDisplayString); + + // Nullable types are displayed as T? + var genericType = type.GetGenericTypeDefinition(); + if (genericType == typeof(Nullable<>)) + { + return $"{typeArguments.First()}?"; + } + + // ValueTuple types are displayed as (T1, T2) + if (genericType == typeof(ValueTuple<>) || + genericType == typeof(ValueTuple<,>) || + genericType == typeof(ValueTuple<,,>) || + genericType == typeof(ValueTuple<,,,>) || + genericType == typeof(ValueTuple<,,,,>) || + genericType == typeof(ValueTuple<,,,,,>) || + genericType == typeof(ValueTuple<,,,,,,>) || + genericType == typeof(ValueTuple<,,,,,,,>)) + { + return $"({string.Join(", ", typeArguments)})"; + } + + // Standard generic types are displayed as Foo + return $"{genericName}<{string.Join(", ", typeArguments)}>"; + } + + // Array types are displayed as Foo[] + if (type.IsArray) + { + var elementType = type.GetElementType(); + var rank = type.GetArrayRank(); + + return $"{FormatDisplayString(elementType)}[{new string(',', rank - 1)}]"; + } + + return type.ToString(); + } + + /* Atomically get or build the display string for the current type. + * Manually create a static lambda here to enable caching of the generated closure. + * This is a workaround for the missing caching for method group conversions, and should + * be removed once this issue is resolved: https://github.com/dotnet/roslyn/issues/5835. */ + return DisplayNames.GetValue(type, t => FormatDisplayString(t)); + } + } +} diff --git a/Microsoft.Toolkit/Extensions/ValueTypeExtensions.cs b/Microsoft.Toolkit/Extensions/ValueTypeExtensions.cs new file mode 100644 index 00000000000..64f73732c98 --- /dev/null +++ b/Microsoft.Toolkit/Extensions/ValueTypeExtensions.cs @@ -0,0 +1,75 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Microsoft.Toolkit.Extensions +{ + /// + /// Helpers for working with value types. + /// + public static class ValueTypeExtensions + { + /// + /// Gets the table of hex characters (doesn't allocate, maps to .text section, see ) + /// + private static ReadOnlySpan HexCharactersTable => new[] + { + (byte)'0', (byte)'1', (byte)'2', (byte)'3', + (byte)'4', (byte)'5', (byte)'6', (byte)'7', + (byte)'8', (byte)'9', (byte)'A', (byte)'B', + (byte)'C', (byte)'D', (byte)'E', (byte)'F' + }; + + /// + /// Returns a hexadecimal representation of a given value, left-padded and ordered as big-endian. + /// + /// The input type to format to . + /// The input value to format to . + /// + /// The hexadecimal representation of (with the '0x' prefix), left-padded to byte boundaries and ordered as big-endian. + /// + /// + /// As a byte (8 bits) is represented by two hexadecimal digits (each representing a group of 4 bytes), each + /// representation will always contain an even number of digits. For instance: + /// + /// Console.WriteLine(1.ToHexString()); // "0x01" + /// Console.WriteLine(((byte)255).ToHexString()); // "0xFF" + /// Console.WriteLine((-1).ToHexString()); // "0xFFFFFFFF" + /// + /// + [Pure] + [MethodImpl(MethodImplOptions.NoInlining)] + public static unsafe string ToHexString(this T value) + where T : unmanaged + { + int + sizeOfT = Unsafe.SizeOf(), + bufferSize = (2 * sizeOfT) + 2; + char* p = stackalloc char[bufferSize]; + + p[0] = '0'; + p[1] = 'x'; + + ref byte r0 = ref Unsafe.As(ref value); + ref byte rh = ref MemoryMarshal.GetReference(HexCharactersTable); + + for (int i = 0, j = bufferSize - 2; i < sizeOfT; i++, j -= 2) + { + byte b = Unsafe.Add(ref r0, i); + int + low = b & 0x0F, + high = (b & 0xF0) >> 4; + + p[j + 1] = (char)Unsafe.Add(ref rh, low); + p[j] = (char)Unsafe.Add(ref rh, high); + } + + return new string(p, 0, bufferSize); + } + } +} diff --git a/Microsoft.Toolkit/Helpers/Singleton.cs b/Microsoft.Toolkit/Helpers/Singleton.cs index 9886c7a4bd6..3e0291814a3 100644 --- a/Microsoft.Toolkit/Helpers/Singleton.cs +++ b/Microsoft.Toolkit/Helpers/Singleton.cs @@ -29,7 +29,7 @@ public static class Singleton where T : new() { // Use ConcurrentDictionary for thread safety. - private static ConcurrentDictionary _instances = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary _instances = new ConcurrentDictionary(); /// /// Gets the instance of the Singleton class. diff --git a/Microsoft.Toolkit/IncrementalLoadingCollection/IIncrementalSource.cs b/Microsoft.Toolkit/IncrementalLoadingCollection/IIncrementalSource.cs index 7dc874a2802..45059162607 100644 --- a/Microsoft.Toolkit/IncrementalLoadingCollection/IIncrementalSource.cs +++ b/Microsoft.Toolkit/IncrementalLoadingCollection/IIncrementalSource.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; diff --git a/Microsoft.Toolkit/Microsoft.Toolkit.csproj b/Microsoft.Toolkit/Microsoft.Toolkit.csproj index 8d5936399cc..011f95377f7 100644 --- a/Microsoft.Toolkit/Microsoft.Toolkit.csproj +++ b/Microsoft.Toolkit/Microsoft.Toolkit.csproj @@ -2,6 +2,8 @@ netstandard2.0 + 8.0 + true Windows Community Toolkit .NET Standard This package includes .NET Standard code only helpers such as: @@ -14,4 +16,55 @@ Full + + + + + + + TextTemplatingFileGenerator + Guard.Comparable.Numeric.g.cs + + + TextTemplatingFileGenerator + Guard.Collection.g.cs + + + TextTemplatingFileGenerator + ThrowHelper.Collection.g.cs + + + TextTemplatingFileGenerator + TypeInfo.g.cs + + + + + + + + + + + True + True + Guard.Comparable.Numeric.tt + + + True + True + Guard.Collection.tt + + + True + True + ThrowHelper.Collection.tt + + + True + True + TypeInfo.ttinclude + + + \ No newline at end of file diff --git a/UnitTests/Diagnostics/Test_Guard.Array.cs b/UnitTests/Diagnostics/Test_Guard.Array.cs new file mode 100644 index 00000000000..326cbab049c --- /dev/null +++ b/UnitTests/Diagnostics/Test_Guard.Array.cs @@ -0,0 +1,182 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using Microsoft.Toolkit.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace UnitTests.Diagnostics +{ + public partial class Test_Guard + { + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsEmpty_ArrayOk() + { + Guard.IsEmpty(new int[0], nameof(Test_Guard_IsEmpty_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsEmpty_ArrayFail() + { + Guard.IsEmpty(new int[1], nameof(Test_Guard_IsEmpty_ArrayFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsNotEmpty_ArrayOk() + { + Guard.IsNotEmpty(new int[1], nameof(Test_Guard_IsNotEmpty_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsNotEmpty_ArrayFail() + { + Guard.IsNotEmpty(new int[0], nameof(Test_Guard_IsNotEmpty_ArrayFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_HasSizeEqualTo_ArrayOk() + { + Guard.HasSizeEqualTo(new int[4], 4, nameof(Test_Guard_HasSizeEqualTo_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeEqualTo_ArrayFail() + { + Guard.HasSizeEqualTo(new int[3], 4, nameof(Test_Guard_HasSizeEqualTo_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_HasSizeNotEqualTo_ArrayOk() + { + Guard.HasSizeNotEqualTo(new int[3], 4, nameof(Test_Guard_HasSizeNotEqualTo_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeNotEqualTo_ArrayFail() + { + Guard.HasSizeNotEqualTo(new int[4], 4, nameof(Test_Guard_HasSizeNotEqualTo_ArrayFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_HasSizeOver_ArrayOk() + { + Guard.HasSizeOver(new int[5], 2, nameof(Test_Guard_HasSizeOver_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeOver_ArrayEqualFail() + { + Guard.HasSizeOver(new int[4], 4, nameof(Test_Guard_HasSizeOver_ArrayEqualFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeOver_ArraSmallerFail() + { + Guard.HasSizeOver(new int[1], 4, nameof(Test_Guard_HasSizeOver_ArraSmallerFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_HasSizeAtLeast_ArrayOk() + { + Guard.HasSizeAtLeast(new int[5], 2, nameof(Test_Guard_HasSizeAtLeast_ArrayOk)); + Guard.HasSizeAtLeast(new int[2], 2, nameof(Test_Guard_HasSizeAtLeast_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeAtLeast_ArrayFail() + { + Guard.HasSizeOver(new int[1], 4, nameof(Test_Guard_HasSizeAtLeast_ArrayFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_HasSizeLessThan_ArrayOk() + { + Guard.HasSizeLessThan(new int[1], 5, nameof(Test_Guard_HasSizeLessThan_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeLessThan_ArrayEqualFail() + { + Guard.HasSizeLessThan(new int[4], 4, nameof(Test_Guard_HasSizeLessThan_ArrayEqualFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeLessThan_ArrayGreaterFail() + { + Guard.HasSizeLessThan(new int[6], 4, nameof(Test_Guard_HasSizeLessThan_ArrayGreaterFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_HasSizeLessThanOrEqualTo_ArrayOk() + { + Guard.HasSizeLessThanOrEqualTo(new int[1], 5, nameof(Test_Guard_HasSizeLessThanOrEqualTo_ArrayOk)); + Guard.HasSizeLessThanOrEqualTo(new int[5], 5, nameof(Test_Guard_HasSizeLessThanOrEqualTo_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeLessThanOrEqualTo_ArrayFail() + { + Guard.HasSizeLessThanOrEqualTo(new int[8], 4, nameof(Test_Guard_HasSizeLessThanOrEqualTo_ArrayFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_HasSizeEqualToArray_ArrayOk() + { + Guard.HasSizeEqualTo(new int[1], new int[1], nameof(Test_Guard_HasSizeEqualToArray_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeEqualToArray_ArrayFail() + { + Guard.HasSizeEqualTo(new int[8], new int[2], nameof(Test_Guard_HasSizeEqualToArray_ArrayFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_HasSizeLessThanOrEqualToArray_ArrayOk() + { + Guard.HasSizeLessThanOrEqualTo(new int[2], new int[5], nameof(Test_Guard_HasSizeLessThanOrEqualToArray_ArrayOk)); + Guard.HasSizeLessThanOrEqualTo(new int[4], new int[4], nameof(Test_Guard_HasSizeLessThanOrEqualToArray_ArrayOk)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_HasSizeLessThanOrEqualToArray_ArrayFail() + { + Guard.HasSizeLessThanOrEqualTo(new int[8], new int[2], nameof(Test_Guard_HasSizeLessThanOrEqualToArray_ArrayFail)); + } + } +} diff --git a/UnitTests/Diagnostics/Test_Guard.Comparable.Numeric.cs b/UnitTests/Diagnostics/Test_Guard.Comparable.Numeric.cs new file mode 100644 index 00000000000..a2df22682cd --- /dev/null +++ b/UnitTests/Diagnostics/Test_Guard.Comparable.Numeric.cs @@ -0,0 +1,100 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics.CodeAnalysis; +using Microsoft.Toolkit.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace UnitTests.Diagnostics +{ + public partial class Test_Guard + { + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsCloseToInt_Ok() + { + Guard.IsCloseTo(0, 5, 10, nameof(Test_Guard_IsCloseToInt_Ok)); + Guard.IsCloseTo(0, 5, 5, nameof(Test_Guard_IsCloseToInt_Ok)); + Guard.IsCloseTo(0, int.MaxValue, int.MaxValue, nameof(Test_Guard_IsCloseToInt_Ok)); + Guard.IsCloseTo(-500, -530, 50, nameof(Test_Guard_IsCloseToInt_Ok)); + Guard.IsCloseTo(1000, 800, 200, nameof(Test_Guard_IsCloseToInt_Ok)); + Guard.IsCloseTo(int.MaxValue, int.MaxValue - 10, 10, nameof(Test_Guard_IsCloseToInt_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1000", Justification = "Value tuple")] + public void Test_Guard_IsCloseToInt_Fail() + { + foreach (var item in new (int Value, int Target, uint Delta)[] + { + (0, 20, 10), + (0, 6, 5), + (0, int.MaxValue, 500), + (-500, -530, 10), + (1000, 800, 100), + (int.MaxValue, int.MaxValue - 10, 7), + (int.MinValue, int.MaxValue, int.MaxValue) + }) + { + bool fail = false; + + try + { + Guard.IsCloseTo(item.Value, item.Target, item.Delta, nameof(Test_Guard_IsCloseToInt_Fail)); + } + catch (ArgumentException) + { + fail = true; + } + + Assert.IsTrue(fail, $"IsCloseTo didn't fail with {item}"); + } + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsCloseToFloat_Ok() + { + Guard.IsCloseTo(0f, 5, 10, nameof(Test_Guard_IsCloseToFloat_Ok)); + Guard.IsCloseTo(0f, 5, 5, nameof(Test_Guard_IsCloseToFloat_Ok)); + Guard.IsCloseTo(0f, float.MaxValue, float.MaxValue, nameof(Test_Guard_IsCloseToFloat_Ok)); + Guard.IsCloseTo(-500f, -530, 50, nameof(Test_Guard_IsCloseToFloat_Ok)); + Guard.IsCloseTo(1000f, 800, 200, nameof(Test_Guard_IsCloseToFloat_Ok)); + Guard.IsCloseTo(float.MaxValue, float.MaxValue - 10, 10, nameof(Test_Guard_IsCloseToFloat_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1000", Justification = "Value tuple")] + public void Test_Guard_IsCloseToFloat_Fail() + { + foreach (var item in new (float Value, float Target, float Delta)[] + { + (0, 20, 10), + (0, 6, 5), + (0, float.MaxValue, 500), + (-500, -530, 10), + (1000, 800, 100), + (float.MaxValue, float.MaxValue / 2, 7), + (float.MinValue, float.MaxValue, float.MaxValue) + }) + { + bool fail = false; + + try + { + Guard.IsCloseTo(item.Value, item.Target, item.Delta, nameof(Test_Guard_IsCloseToFloat_Fail)); + } + catch (ArgumentException) + { + fail = true; + } + + Assert.IsTrue(fail, $"IsCloseTo didn't fail with {item}"); + } + } + } +} diff --git a/UnitTests/Diagnostics/Test_Guard.cs b/UnitTests/Diagnostics/Test_Guard.cs new file mode 100644 index 00000000000..935c4e2a868 --- /dev/null +++ b/UnitTests/Diagnostics/Test_Guard.cs @@ -0,0 +1,561 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using Microsoft.Toolkit.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace UnitTests.Diagnostics +{ + [TestClass] + public partial class Test_Guard + { + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsNull_Ok() + { + Guard.IsNull(null, nameof(Test_Guard_IsNull_Ok)); + Guard.IsNull(null, nameof(Test_Guard_IsNull_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsNull_ClassFail() + { + Guard.IsNull(new object(), nameof(Test_Guard_IsNull_ClassFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsNull_StructFail() + { + Guard.IsNull(7, nameof(Test_Guard_IsNull_StructFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsNotNull_Ok() + { + Guard.IsNotNull(new object(), nameof(Test_Guard_IsNotNull_Ok)); + Guard.IsNotNull(7, nameof(Test_Guard_IsNotNull_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void Test_Guard_IsNotNull_ClassFail() + { + Guard.IsNotNull(null, nameof(Test_Guard_IsNotNull_ClassFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void Test_Guard_IsNotNull_StructFail() + { + Guard.IsNotNull(null, nameof(Test_Guard_IsNotNull_StructFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsOfT_Ok() + { + Guard.IsOfType("Hello", nameof(Test_Guard_IsOfT_Ok)); + Guard.IsOfType(7, nameof(Test_Guard_IsOfT_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsOfT_Fail() + { + Guard.IsOfType(7, nameof(Test_Guard_IsOfT_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsOfType_Ok() + { + Guard.IsOfType("Hello", typeof(string), nameof(Test_Guard_IsOfType_Ok)); + Guard.IsOfType(7, typeof(int), nameof(Test_Guard_IsOfType_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsOfType_Fail() + { + Guard.IsOfType(7, typeof(string), nameof(Test_Guard_IsOfType_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsAssignableToT_Ok() + { + Guard.IsAssignableToType("Hello", nameof(Test_Guard_IsAssignableToT_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsAssignableToT_Fail() + { + Guard.IsAssignableToType(7, nameof(Test_Guard_IsAssignableToT_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsAssignableToType_Ok() + { + Guard.IsAssignableToType("Hello", typeof(string), nameof(Test_Guard_IsAssignableToType_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsAssignableToType_Fail() + { + Guard.IsAssignableToType(7, typeof(string), nameof(Test_Guard_IsAssignableToType_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsEqualTo_Ok() + { + Guard.IsEqualTo("Hello", "Hello", nameof(Test_Guard_IsEqualTo_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsEqualTo_Fail() + { + Guard.IsEqualTo("Hello", "World", nameof(Test_Guard_IsEqualTo_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsNotEqualTo_Ok() + { + Guard.IsNotEqualTo("Hello", "World", nameof(Test_Guard_IsNotEqualTo_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsNotEqualTo_Fail() + { + Guard.IsNotEqualTo("Hello", "Hello", nameof(Test_Guard_IsNotEqualTo_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsBitwiseEqualTo_Ok() + { + Guard.IsBitwiseEqualTo(byte.MaxValue, byte.MaxValue, nameof(Test_Guard_IsBitwiseEqualTo_Ok)); + Guard.IsBitwiseEqualTo(DateTime.MaxValue, DateTime.MaxValue, nameof(Test_Guard_IsBitwiseEqualTo_Ok)); + Guard.IsBitwiseEqualTo(double.Epsilon, double.Epsilon, nameof(Test_Guard_IsBitwiseEqualTo_Ok)); + Guard.IsBitwiseEqualTo(MathF.PI, MathF.PI, nameof(Test_Guard_IsBitwiseEqualTo_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsBitwiseEqualTo_SingleFail() + { + Guard.IsBitwiseEqualTo(double.PositiveInfinity, double.Epsilon, nameof(Test_Guard_IsBitwiseEqualTo_SingleFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsBitwiseEqualTo_LoopFail() + { + Guard.IsBitwiseEqualTo(DateTime.Now, DateTime.Today, nameof(Test_Guard_IsBitwiseEqualTo_LoopFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsReferenceEqualTo_Ok() + { + var obj = new object(); + + Guard.IsReferenceEqualTo(obj, obj, nameof(Test_Guard_IsReferenceEqualTo_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsReferenceEqualTo_Fail() + { + Guard.IsReferenceEqualTo(new object(), new object(), nameof(Test_Guard_IsReferenceEqualTo_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsReferenceNotEqualTo_Ok() + { + Guard.IsReferenceNotEqualTo(new object(), new object(), nameof(Test_Guard_IsReferenceEqualTo_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsReferenceNotEqualTo_Fail() + { + var obj = new object(); + + Guard.IsReferenceNotEqualTo(obj, obj, nameof(Test_Guard_IsReferenceEqualTo_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsTrue_Ok() + { + Guard.IsTrue(true, nameof(Test_Guard_IsTrue_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsTrue_Fail() + { + Guard.IsTrue(false, nameof(Test_Guard_IsTrue_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsFalse_Ok() + { + Guard.IsFalse(false, nameof(Test_Guard_IsFalse_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void Test_Guard_IsFalse_Fail() + { + Guard.IsFalse(true, nameof(Test_Guard_IsFalse_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsLessThan_Ok() + { + Guard.IsLessThan(1, 2, nameof(Test_Guard_IsLessThan_Ok)); + Guard.IsLessThan(1.2f, 3.14f, nameof(Test_Guard_IsLessThan_Ok)); + Guard.IsLessThan(DateTime.Now, DateTime.MaxValue, nameof(Test_Guard_IsLessThan_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsLessThan_EqualsFalse() + { + Guard.IsLessThan(1, 1, nameof(Test_Guard_IsLessThan_EqualsFalse)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsLessThan_GreaterFalse() + { + Guard.IsLessThan(2, 1, nameof(Test_Guard_IsLessThan_GreaterFalse)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsLessThanOrEqualTo_Ok() + { + Guard.IsLessThanOrEqualTo(1, 2, nameof(Test_Guard_IsLessThanOrEqualTo_Ok)); + Guard.IsLessThanOrEqualTo(1, 1, nameof(Test_Guard_IsLessThanOrEqualTo_Ok)); + Guard.IsLessThanOrEqualTo(0.1f, MathF.PI, nameof(Test_Guard_IsLessThanOrEqualTo_Ok)); + Guard.IsLessThanOrEqualTo(MathF.PI, MathF.PI, nameof(Test_Guard_IsLessThanOrEqualTo_Ok)); + Guard.IsLessThanOrEqualTo(DateTime.Today, DateTime.MaxValue, nameof(Test_Guard_IsLessThanOrEqualTo_Ok)); + Guard.IsLessThanOrEqualTo(DateTime.MaxValue, DateTime.MaxValue, nameof(Test_Guard_IsLessThanOrEqualTo_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsLessThanOrEqualTo_False() + { + Guard.IsLessThanOrEqualTo(2, 1, nameof(Test_Guard_IsLessThanOrEqualTo_False)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsGreaterThan_Ok() + { + Guard.IsGreaterThan(2, 1, nameof(Test_Guard_IsGreaterThan_Ok)); + Guard.IsGreaterThan(3.14f, 2.1f, nameof(Test_Guard_IsGreaterThan_Ok)); + Guard.IsGreaterThan(DateTime.MaxValue, DateTime.Today, nameof(Test_Guard_IsGreaterThan_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsGreaterThan_EqualsFalse() + { + Guard.IsGreaterThan(1, 1, nameof(Test_Guard_IsGreaterThan_EqualsFalse)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsGreaterThan_LowerFalse() + { + Guard.IsGreaterThan(1, 2, nameof(Test_Guard_IsGreaterThan_LowerFalse)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsGreaterThanOrEqualTo_Ok() + { + Guard.IsGreaterThanOrEqualTo(2,1, nameof(Test_Guard_IsGreaterThanOrEqualTo_Ok)); + Guard.IsGreaterThanOrEqualTo(1, 1, nameof(Test_Guard_IsGreaterThanOrEqualTo_Ok)); + Guard.IsGreaterThanOrEqualTo(MathF.PI, 1, nameof(Test_Guard_IsGreaterThanOrEqualTo_Ok)); + Guard.IsGreaterThanOrEqualTo(MathF.PI, MathF.PI, nameof(Test_Guard_IsGreaterThanOrEqualTo_Ok)); + Guard.IsGreaterThanOrEqualTo(DateTime.MaxValue, DateTime.Today, nameof(Test_Guard_IsGreaterThanOrEqualTo_Ok)); + Guard.IsGreaterThanOrEqualTo(DateTime.MaxValue, DateTime.MaxValue, nameof(Test_Guard_IsGreaterThanOrEqualTo_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsGreaterThanOrEqualTo_False() + { + Guard.IsGreaterThanOrEqualTo(1, 2, nameof(Test_Guard_IsGreaterThanOrEqualTo_False)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsInRange_Ok() + { + Guard.IsInRange(1, 0, 4, nameof(Test_Guard_IsInRange_Ok)); + Guard.IsInRange(0, 0, 2, nameof(Test_Guard_IsInRange_Ok)); + Guard.IsInRange(3.14f, 0, 10, nameof(Test_Guard_IsInRange_Ok)); + Guard.IsInRange(1, 0, 3.14f, nameof(Test_Guard_IsInRange_Ok)); + Guard.IsInRange(1, -50, 2, nameof(Test_Guard_IsInRange_Ok)); + Guard.IsInRange(-44, -44, 0, nameof(Test_Guard_IsInRange_Ok)); + Guard.IsInRange(3.14f, -float.Epsilon, 22, nameof(Test_Guard_IsInRange_Ok)); + Guard.IsInRange(1, int.MinValue, int.MaxValue, nameof(Test_Guard_IsInRange_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsInRange_LowerFail() + { + Guard.IsInRange(-3, 0, 4, nameof(Test_Guard_IsInRange_LowerFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsInRange_EqualFail() + { + Guard.IsInRange(0, 4, 4, nameof(Test_Guard_IsInRange_EqualFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsInRange_HigherFail() + { + Guard.IsInRange(0, 20, 4, nameof(Test_Guard_IsInRange_HigherFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsNotInRange_Ok() + { + Guard.IsNotInRange(0, 4, 10, nameof(Test_Guard_IsNotInRange_Ok)); + Guard.IsNotInRange(-4, 0, 2, nameof(Test_Guard_IsNotInRange_Ok)); + Guard.IsNotInRange(12f, 0, 10, nameof(Test_Guard_IsNotInRange_Ok)); + Guard.IsNotInRange(-1, 0, 3.14f, nameof(Test_Guard_IsNotInRange_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsNotInRange_LowerEqualFail() + { + Guard.IsNotInRange(0, 0, 4, nameof(Test_Guard_IsNotInRange_LowerEqualFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsNotInRange_InnerFail() + { + Guard.IsNotInRange(2, 0, 4, nameof(Test_Guard_IsNotInRange_InnerFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsInRangeFor_Ok() + { + Span span = stackalloc int[10]; + + Guard.IsInRangeFor(0, span, nameof(Test_Guard_IsInRangeFor_Ok)); + Guard.IsInRangeFor(4, span, nameof(Test_Guard_IsInRangeFor_Ok)); + Guard.IsInRangeFor(9, span, nameof(Test_Guard_IsInRangeFor_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsInRangeFor_LowerFail() + { + Span span = stackalloc int[10]; + + Guard.IsInRangeFor(-2, span, nameof(Test_Guard_IsInRangeFor_LowerFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsInRangeFor_EqualFail() + { + Span span = stackalloc int[10]; + + Guard.IsInRangeFor(10, span, nameof(Test_Guard_IsInRangeFor_EqualFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsInRangeFor_HigherFail() + { + Span span = stackalloc int[10]; + + Guard.IsInRangeFor(99, span, nameof(Test_Guard_IsInRangeFor_HigherFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsNotInRangeFor_Ok() + { + Span span = stackalloc int[10]; + + Guard.IsNotInRangeFor(-2, span, nameof(Test_Guard_IsNotInRangeFor_Ok)); + Guard.IsNotInRangeFor(10, span, nameof(Test_Guard_IsNotInRangeFor_Ok)); + Guard.IsNotInRangeFor(2222, span, nameof(Test_Guard_IsNotInRangeFor_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsNotInRangeFor_LowerFail() + { + Span span = stackalloc int[10]; + + Guard.IsNotInRangeFor(0, span, nameof(Test_Guard_IsNotInRangeFor_LowerFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsNotInRangeFor_MiddleFail() + { + Span span = stackalloc int[10]; + + Guard.IsNotInRangeFor(6, span, nameof(Test_Guard_IsNotInRangeFor_MiddleFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsBetween_Ok() + { + Guard.IsBetween(1, 0, 4, nameof(Test_Guard_IsBetween_Ok)); + Guard.IsBetween(3.14f, 0, 10, nameof(Test_Guard_IsBetween_Ok)); + Guard.IsBetween(1, 0, 3.14, nameof(Test_Guard_IsBetween_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsBetween_LowerFail() + { + Guard.IsBetween(-1, 0, 4, nameof(Test_Guard_IsBetween_LowerFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsBetween_EqualFail() + { + Guard.IsBetween(0, 0, 4, nameof(Test_Guard_IsBetween_EqualFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsBetween_HigherFail() + { + Guard.IsBetween(6, 0, 4, nameof(Test_Guard_IsBetween_HigherFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsNotBetween_Ok() + { + Guard.IsNotBetween(0, 0, 4, nameof(Test_Guard_IsNotBetween_Ok)); + Guard.IsNotBetween(10, 0, 10, nameof(Test_Guard_IsNotBetween_Ok)); + Guard.IsNotBetween(-5, 0, 3.14, nameof(Test_Guard_IsNotBetween_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsNotBetween_Fail() + { + Guard.IsNotBetween(1, 0, 4, nameof(Test_Guard_IsNotBetween_Fail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsBetweenOrEqualTo_Ok() + { + Guard.IsBetweenOrEqualTo(1, 0, 4, nameof(Test_Guard_IsBetweenOrEqualTo_Ok)); + Guard.IsBetweenOrEqualTo(10, 0, 10, nameof(Test_Guard_IsBetweenOrEqualTo_Ok)); + Guard.IsBetweenOrEqualTo(1, 0, 3.14, nameof(Test_Guard_IsBetweenOrEqualTo_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsBetweenOrEqualTo_LowerFail() + { + Guard.IsBetweenOrEqualTo(-1, 0, 4, nameof(Test_Guard_IsBetweenOrEqualTo_LowerFail)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsBetweenOrEqualTo_HigherFail() + { + Guard.IsBetweenOrEqualTo(6, 0, 4, nameof(Test_Guard_IsBetweenOrEqualTo_HigherFail)); + } + + [TestCategory("Guard")] + [TestMethod] + public void Test_Guard_IsNotBetweenOrEqualTo_Ok() + { + Guard.IsNotBetweenOrEqualTo(6, 0, 4, nameof(Test_Guard_IsNotBetweenOrEqualTo_Ok)); + Guard.IsNotBetweenOrEqualTo(-10, 0, 10, nameof(Test_Guard_IsNotBetweenOrEqualTo_Ok)); + } + + [TestCategory("Guard")] + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void Test_Guard_IsNotBetweenOrEqualTo_Fail() + { + Guard.IsNotBetweenOrEqualTo(3, 0, 4, nameof(Test_Guard_IsNotBetweenOrEqualTo_Fail)); + } + } +} diff --git a/UnitTests/Extensions/Test_TypeExtensions.cs b/UnitTests/Extensions/Test_TypeExtensions.cs new file mode 100644 index 00000000000..5acb2392faa --- /dev/null +++ b/UnitTests/Extensions/Test_TypeExtensions.cs @@ -0,0 +1,46 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using Microsoft.Toolkit.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace UnitTests.Extensions +{ + [TestClass] + public class Test_TypeExtensions + { + [TestCategory("TypeExtensions")] + [TestMethod] + public void Test_TypeExtensions_BuiltInTypes() + { + Assert.AreEqual("bool", typeof(bool).ToTypeString()); + Assert.AreEqual("int", typeof(int).ToTypeString()); + Assert.AreEqual("float", typeof(float).ToTypeString()); + Assert.AreEqual("double", typeof(double).ToTypeString()); + Assert.AreEqual("decimal", typeof(decimal).ToTypeString()); + Assert.AreEqual("object", typeof(object).ToTypeString()); + Assert.AreEqual("string", typeof(string).ToTypeString()); + } + + [TestCategory("TypeExtensions")] + [TestMethod] + [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1009", Justification = "Nullable value tuple type")] + public void Test_TypeExtensions_GenericTypes() + { + Assert.AreEqual("int?", typeof(int?).ToTypeString()); + Assert.AreEqual("System.DateTime?", typeof(DateTime?).ToTypeString()); + Assert.AreEqual("(int, float)", typeof((int, float)).ToTypeString()); + Assert.AreEqual("(double?, string, int)?", typeof((double?, string, int)?).ToTypeString()); + Assert.AreEqual("int[]", typeof(int[]).ToTypeString()); + Assert.AreEqual(typeof(int[,]).ToTypeString(), "int[,]"); + Assert.AreEqual("System.Span", typeof(Span).ToTypeString()); + Assert.AreEqual("System.Memory", typeof(Memory).ToTypeString()); + Assert.AreEqual("System.Collections.Generic.IEnumerable", typeof(IEnumerable).ToTypeString()); + Assert.AreEqual(typeof(Dictionary>).ToTypeString(), "System.Collections.Generic.Dictionary>"); + } + } +} diff --git a/UnitTests/Extensions/Test_ValueTypeExtensions.cs b/UnitTests/Extensions/Test_ValueTypeExtensions.cs new file mode 100644 index 00000000000..da7b8eae51d --- /dev/null +++ b/UnitTests/Extensions/Test_ValueTypeExtensions.cs @@ -0,0 +1,26 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Toolkit.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace UnitTests.Extensions +{ + [TestClass] + public class Test_ValueTypeExtensions + { + [TestCategory("ValueTypeExtensions")] + [TestMethod] + public void Test_ValueTypeExtensions_ToHexString() + { + Assert.AreEqual(((byte)0).ToHexString(), "0x00"); + Assert.AreEqual(((byte)127).ToHexString(), "0x7F"); + Assert.AreEqual(((byte)255).ToHexString(), "0xFF"); + Assert.AreEqual(((ushort)6458).ToHexString(), "0x193A"); + Assert.AreEqual(6458.ToHexString(), "0x0000193A"); + Assert.AreEqual((-1).ToHexString(), "0xFFFFFFFF"); + Assert.AreEqual(true.ToHexString(), "0x01"); + } + } +} diff --git a/UnitTests/UI/Controls/Test_UniformGrid_FreeSpots.cs b/UnitTests/UI/Controls/Test_UniformGrid_FreeSpots.cs index 2c7841d5d91..1c7be7e7b22 100644 --- a/UnitTests/UI/Controls/Test_UniformGrid_FreeSpots.cs +++ b/UnitTests/UI/Controls/Test_UniformGrid_FreeSpots.cs @@ -18,8 +18,6 @@ public class Test_UniformGrid_FreeSpots [UITestMethod] public void Test_UniformGrid_GetFreeSpots_Basic() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[4, 5] { { false, true, false, true, false }, @@ -50,8 +48,6 @@ public void Test_UniformGrid_GetFreeSpots_Basic() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_FirstColumn() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[4, 5] { { true, false, false, true, false }, @@ -82,8 +78,6 @@ public void Test_UniformGrid_GetFreeSpots_FirstColumn() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBoundMinusOne() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[3, 3] { { false, false, false }, @@ -112,8 +106,6 @@ public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBoundMinusOne() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBound() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[3, 3] { { false, false, false }, @@ -142,8 +134,6 @@ public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBound() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBound_TopDown() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[3, 3] { { false, false, false }, @@ -172,8 +162,6 @@ public void Test_UniformGrid_GetFreeSpots_FirstColumnEndBound_TopDown() [UITestMethod] public void Test_UniformGrid_GetFreeSpots_VerticalOrientation() { - var grid = new UniformGrid(); - var testref = new TakenSpotsReferenceHolder(new bool[4, 5] { { false, false, false, true, false }, diff --git a/UnitTests/UnitTests.Notifications.Shared/TestToastContentBuilder.cs b/UnitTests/UnitTests.Notifications.Shared/TestToastContentBuilder.cs index 10f2f0cc401..9aacfab13a1 100644 --- a/UnitTests/UnitTests.Notifications.Shared/TestToastContentBuilder.cs +++ b/UnitTests/UnitTests.Notifications.Shared/TestToastContentBuilder.cs @@ -5,10 +5,7 @@ using Microsoft.Toolkit.Uwp.Notifications; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace UnitTests.Notifications { @@ -418,7 +415,7 @@ public void AddTextTest_WithMoreThan4LinesOfText_ThrowInvalidOperationException( ToastContentBuilder builder = new ToastContentBuilder(); // Act - ToastContentBuilder anotherReference = builder.AddText(testText1) + _ = builder.AddText(testText1) .AddText(testText2) .AddText(testText3) .AddText(testText4); @@ -433,7 +430,7 @@ public void AddTextTest_WithMaxLinesValueLargerThan2_ThrowArgumentOutOfRangeExce ToastContentBuilder builder = new ToastContentBuilder(); // Act - ToastContentBuilder anotherReference = builder.AddText(testText1, hintMaxLines: 3); + _ = builder.AddText(testText1, hintMaxLines: 3); } [TestMethod] diff --git a/UnitTests/UnitTests.csproj b/UnitTests/UnitTests.csproj index 1813e7836db..b4208dc4fef 100644 --- a/UnitTests/UnitTests.csproj +++ b/UnitTests/UnitTests.csproj @@ -132,7 +132,12 @@ + + + + + diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 2ea88f5c6d8..0c8e1ef2d5e 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -28,7 +28,7 @@ steps: - task: UseDotNet@2 inputs: packageType: 'sdk' - version: '3.0.100' + version: '3.1.101' displayName: Use .NET Core sdk - task: DotNetCoreCLI@2 diff --git a/global.json b/global.json index b63fd5c3b3f..80d84a257c6 100644 --- a/global.json +++ b/global.json @@ -1,7 +1,4 @@ { - "sdk": { - "version": "3.0.100" - }, "msbuild-sdks": { "MSBuild.Sdk.Extras": "2.0.54" } diff --git a/readme.md b/readme.md index 7b1c2226d6b..dbee68c06b9 100644 --- a/readme.md +++ b/readme.md @@ -12,7 +12,7 @@ The Windows Community Toolkit is a collection of helper functions, custom contro ## Build Status | Target | Branch | Status | Recommended package version | | ------ | ------ | ------ | ------ | -| Production | rel/5.1.1 | [![Build Status](https://dev.azure.com/dotnet/WindowsCommunityToolkit/_apis/build/status/Toolkit-CI?branchName=rel/5.1.1)](https://dev.azure.com/dotnet/WindowsCommunityToolkit/_build/latest?definitionId=10&branchName=rel/5.1.1) | [![NuGet](https://img.shields.io/nuget/v/Microsoft.Toolkit.Uwp.svg)](https://www.nuget.org/profiles/Microsoft.Toolkit) | +| Production | rel/6.0.0 | [![Build Status](https://dev.azure.com/dotnet/WindowsCommunityToolkit/_apis/build/status/Toolkit-CI?branchName=rel/6.0.0)](https://dev.azure.com/dotnet/WindowsCommunityToolkit/_build/latest?definitionId=10&branchName=rel/6.0.0) | [![NuGet](https://img.shields.io/nuget/v/Microsoft.Toolkit.Uwp.svg)](https://www.nuget.org/profiles/Microsoft.Toolkit) | | Pre-release beta testing | master | [![Build Status](https://dev.azure.com/dotnet/WindowsCommunityToolkit/_apis/build/status/Toolkit-CI?branchName=master)](https://dev.azure.com/dotnet/WindowsCommunityToolkit/_build/latest?definitionId=10) | [![MyGet](https://img.shields.io/dotnet.myget/uwpcommunitytoolkit/vpre/Microsoft.Toolkit.Uwp.svg)](https://dotnet.myget.org/gallery/uwpcommunitytoolkit) | ## Getting Started @@ -48,12 +48,8 @@ Once you do a search, you should see a list similar to the one below (versions m | Microsoft.Toolkit.Uwp.Connectivity | API helpers such as BluetoothLEHelper and Networking | | Microsoft.Toolkit.Uwp.DeveloperTools | XAML user controls and services to help developer building their app | -## Supported SDKs -* Fall Creators Update (16299) -* April 2018 Update (17134) -* October 2018 Update (17763) - -## Features +## Features +The following features can be found in the Windows Community Toolkit. Most features should work with the Falls Creator Update SDK 16299 and above; however, refer to specific documentation on each feature for more information. ### Animations * [AnimationSet](https://docs.microsoft.com/windows/uwpcommunitytoolkit/animations/AnimationSet) @@ -173,6 +169,15 @@ Once you do a search, you should see a list similar to the one below (versions m Please use [GitHub Issues](https://github.com/windows-toolkit/WindowsCommunityToolkit/issues) for bug reports and feature requests. For general questions and support, please use [Stack Overflow](https://stackoverflow.com/questions/tagged/windows-community-toolkit) where questions should be tagged with the tag `windows-community-toolkit`. +## Required Dependencies +The following dependencies are required for building the Windows Community Toolkit repo and sample app: + +* [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) +* [Windows SDK October 2018 Update 17763](https://developer.microsoft.com/en-us/windows/downloads/sdk-archive) +* [Sample App - Windows SDK May 2019 Update 18362](https://developer.microsoft.com/en-us/windows/downloads/sdk-archive) +* [.NET Core 3.1 SDK](https://dotnet.microsoft.com/download/visual-studio-sdks) +* [.NET Framework 4.6.2 Developer Pack](https://dotnet.microsoft.com/download/visual-studio-sdks) + ## Contributing Do you want to contribute? Here are our [contribution guidelines](https://github.com/windows-toolkit/WindowsCommunityToolkit/blob/master/contributing.md).