diff --git a/.editorconfig b/.editorconfig index 1a2db97..951ce01 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,74 +1,37 @@ -root = true - -[*] -charset = utf-8 -indent_size = 4 -indent_style = space -insert_final_newline = true -trim_trailing_whitespace = true - -[*.{yml,props,targets,csproj}] -indent_size = 2 - -# IDE0079: Remove unnecessary suppression -dotnet_remove_unnecessary_suppression_exclusions = category:ReSharper - -# IDE0079: Remove unnecessary suppression -# dotnet_diagnostic.IDE0079.severity = none - -# CA2255: The 'ModuleInitializer' attribute should not be used in libraries -dotnet_diagnostic.CA2255.severity = none - -# CS8600: Converting null literal or possible null value to non-nullable type. -dotnet_diagnostic.CS8600.severity = error - -# CS8601: Possible null reference assignment. -dotnet_diagnostic.CS8601.severity = error - -# CS8602: Dereference of a possibly null reference. -dotnet_diagnostic.CS8602.severity = error - -# CS8603: Possible null reference return. -dotnet_diagnostic.CS8603.severity = error - -# CS8604: Possible null reference argument. -dotnet_diagnostic.CS8604.severity = error - -# CS8610: Nullability of reference types in type of parameter doesn't match overridden member. -dotnet_diagnostic.CS8610.severity = error - -# CS8613: Nullability of reference types in return type doesn't match implicitly implemented member. -dotnet_diagnostic.CS8613.severity = error - -# CS8614: Nullability of reference types in type of parameter doesn't match implicitly implemented member. -dotnet_diagnostic.CS8614.severity = error - -# CS8618: Non-nullable field is uninitialized. Consider declaring as nullable. -dotnet_diagnostic.CS8618.severity = error - -# CS8619: Nullability of reference types in value doesn't match target type. -dotnet_diagnostic.CS8619.severity = error - -# CS8620: Argument cannot be used for parameter due to differences in the nullability of reference types. -dotnet_diagnostic.CS8620.severity = error - -# CS8625: Cannot convert null literal to non-nullable reference type. -dotnet_diagnostic.CS8625.severity = error - -# CS8634: The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint. -dotnet_diagnostic.CS8634.severity = error - -# CS8643: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. -dotnet_diagnostic.CS8643.severity = error - -# CS8653: A default expression introduces a null value for a type parameter. -dotnet_diagnostic.CS8653.severity = error - -# CS8714: The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint. -dotnet_diagnostic.CS8714.severity = error - -# IDE0059: Unnecessary assigment of a value -dotnet_diagnostic.IDE0059.severity = none - -# IDE0060: Remove unused parameter -dotnet_diagnostic.IDE0060.severity = none +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +trim_trailing_whitespace = true +insert_final_newline = true + +[*.{yml,yaml}] +indent_size = 2 + +[*.{slnx,csproj,proj,props,targets}] +indent_size = 2 + +[*.cs] +resharper_csharp_max_line_length = 160 + +# Using directive options +dotnet_sort_system_directives_first = true +dotnet_separate_import_directive_groups = true + +# Prefer var whenever possible +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion + +# Indentation preferences +csharp_indent_labels = no_change + +# IDE0079: Remove unnecessary suppression +dotnet_remove_unnecessary_suppression_exclusions = category:ReSharper + +[Ramstack.Structures.Tests/**.cs] +# CA1707: Identifiers should not contain underscores +# Tests follow the Method_Condition_ExpectedResult naming convention. +dotnet_diagnostic.CA1707.severity = none diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..176a458 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 7c3b52a..1c8c080 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,38 +1,38 @@ -name: Publish - -on: - push: - tags: - - "[0-9]+.[0-9]+.[0-9]+" - - "[0-9]+.[0-9]+.[0-9]+-[a-z]+.[0-9]+" - -permissions: - contents: write - -jobs: - publish: - if: github.repository == 'rameel/ramstack.structures' - runs-on: ubuntu-latest - steps: - - name: Install .NET - uses: actions/setup-dotnet@v3 - with: - dotnet-version: 10.0.x - - - name: Checkout - uses: actions/checkout@v4 - - - name: Build - run: dotnet build -c Release - - - name: Create NuGet Packages - run: dotnet pack -c Release -o ./nuget --no-build - - - name: Publish NuGet Packages - run: dotnet nuget push ./nuget/*.nupkg --api-key ${{secrets.NUGET_API_KEY}} --skip-duplicate -s https://api.nuget.org/v3/index.json - - - name: Create GitHub Release - uses: softprops/action-gh-release@v2 - with: - draft: true - files: nuget/* +name: Publish + +on: + push: + tags: + - "[0-9]+.[0-9]+.[0-9]+" + - "[0-9]+.[0-9]+.[0-9]+-[a-z]+.[0-9]+" + +permissions: + contents: write + +jobs: + publish: + if: github.repository == 'rameel/ramstack.structures' + runs-on: ubuntu-latest + steps: + - name: Install .NET + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 10.0.x + + - name: Checkout + uses: actions/checkout@v4 + + - name: Build + run: dotnet build -c Release + + - name: Create NuGet Packages + run: dotnet pack -c Release -o ./nuget --no-build + + - name: Publish NuGet Packages + run: dotnet nuget push ./nuget/*.nupkg --api-key ${{secrets.NUGET_API_KEY}} --skip-duplicate -s https://api.nuget.org/v3/index.json + + - name: Create GitHub Release + uses: softprops/action-gh-release@v2 + with: + draft: true + files: nuget/* diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9f09599..d5cbee7 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,30 +1,30 @@ -name: Build & Test - -on: - pull_request: - branches: [main] - -jobs: - build-and-test: - name: "Test project" - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup .NET - uses: actions/setup-dotnet@v3 - with: - dotnet-version: | - 6.x - 7.x - 8.x - 9.x - 10.x - - - name: Test (Debug) - run: dotnet test -c Debug - - - name: Test (Release) - run: dotnet test -c Release +name: Build & Test + +on: + pull_request: + branches: [main] + +jobs: + build-and-test: + name: "Test project" + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v3 + with: + dotnet-version: | + 6.x + 7.x + 8.x + 9.x + 10.x + + - name: Test (Debug) + run: dotnet test -c Debug + + - name: Test (Release) + run: dotnet test -c Release diff --git a/.gitignore b/.gitignore index 4f81b1b..bd6adb1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,37 +1,37 @@ -#Ignore thumbnails created by windows -[Tt]humbs.db - -#Ignore files build by Visual Studio -*.obj -*.exe -*.pdb -*.user -*.patch -*.aps -*.pch -*.vspscc -*_i.c -*_p.c -*.ncb -*.suo -*.tlb -*.tlh -*.bak -*.cache -*.ilk -*.log -*.lib -*.sbr -*.cs.ide -[Dd]ebug*/ -[Rr]elease*/ -bin/ -obj/ -.vs/ -.vscode/ -*.ReSharper -*.ReSharper.user -[Tt]est[Rr]esult* - -#Ignore Rider/Idea files -.idea/ +#Ignore thumbnails created by windows +[Tt]humbs.db + +#Ignore files build by Visual Studio +*.obj +*.exe +*.pdb +*.user +*.patch +*.aps +*.pch +*.vspscc +*_i.c +*_p.c +*.ncb +*.suo +*.tlb +*.tlh +*.bak +*.cache +*.ilk +*.log +*.lib +*.sbr +*.cs.ide +[Dd]ebug*/ +[Rr]elease*/ +bin/ +obj/ +.vs/ +.vscode/ +*.ReSharper +*.ReSharper.user +[Tt]est[Rr]esult* + +#Ignore Rider/Idea files +.idea/ diff --git a/Directory.Build.props b/Directory.Build.props index bf61882..9e6caca 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,5 +1,19 @@ - - - true - - + + + true + + + + $(NoWarn);CS0649 + true + + + + true + latest + Recommended + Default + true + true + + diff --git a/Directory.Packages.props b/Directory.Packages.props index 960898d..4137cad 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,13 +1,13 @@ - - - - true - - - - - - - - + + + + true + + + + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE index 6666765..92e3431 100644 --- a/LICENSE +++ b/LICENSE @@ -1,9 +1,9 @@ -MIT License - -Copyright 2024 Rameel (https://github.com/rameel) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +MIT License + +Copyright 2024 Rameel (https://github.com/rameel) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 815cac3..659dcec 100644 --- a/README.md +++ b/README.md @@ -1,64 +1,64 @@ -# Ramstack.Structures - -[![NuGet](https://img.shields.io/nuget/v/Ramstack.Structures.svg)](https://nuget.org/packages/Ramstack.Structures) -[![MIT](https://img.shields.io/github/license/rameel/ramstack.structures)](https://github.com/rameel/ramstack.structures/blob/main/LICENSE) - -Ramstack.Structures is a .NET library providing various data structures and utilities. - -## Installation - -To install the `Ramstack.Structures` [NuGet package](https://www.nuget.org/packages/Ramstack.Structures) to your project, use the following command: - -```console -dotnet add package Ramstack.Structures -``` - -## Features - -The current release includes primary types: - -* `Ramstack.Text.StringView`:
Represents a read-only view of a string, providing safe and efficient access to a subset of its characters. -* `Ramstack.Collections.ArrayView`:
A generic read-only view of an array, allowing safe and efficient access to a subset of its elements. -* `Ramstack.Collections.ReadOnlyArray`:
A generic read-only array wrapper, similar to `ImmutableArray`, but with some performance improvements and better code generation in certain cases. - -Additionally, the library provides the `StringViewComparer` class, which offers various comparators accessible through corresponding properties: - -| Property | Description | -|--------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------| -| **Ordinal** | Gets a **StringViewComparer** object that performs a case-sensitive ordinal string comparison. | -| **OrdinalIgnoreCase** | Gets a **StringViewComparer** object that performs a case-insensitive ordinal string comparison. | -| **CurrentCulture** | Gets a **StringViewComparer** object that performs case-sensitive string comparisons using the word comparison rules of the current culture. | -| **CurrentCultureIgnoreCase** | Gets a **StringViewComparer** object that performs case-insensitive string comparisons using the word comparison rules of the current culture. | -| **InvariantCulture** | Gets a **StringViewComparer** object that performs a case-sensitive string comparison using the word comparison rules of the invariant culture. | -| **InvariantCultureIgnoreCase** | Gets a **StringViewComparer** object that performs a case-insensitive string comparison using the word comparison rules of the invariant culture. | - -## Notes - -The `ArrayView` and `ReadOnlyArray` types have a `ref readonly` indexer, which provides efficient access to elements of the underlying array, -avoiding expensive copying in the case of large structures. - -This same optimization is also applied to the enumerators of these types. The `Current` property has a `ref readonly` signature, -which enables the following pattern when necessary: - -```csharp -foreach (ref readonly HeavyStruct s in view) -{ - ... -} - -``` - -## Supported versions - -| | Version | -|------|------------| -| .NET | 6, 7, 8, 9 | - -## Contributions - -Bug reports and contributions are welcome. - -## License -This package is released as open source under the **MIT License**. - -See the [LICENSE](LICENSE) file for more details. +# Ramstack.Structures + +[![NuGet](https://img.shields.io/nuget/v/Ramstack.Structures.svg)](https://nuget.org/packages/Ramstack.Structures) +[![MIT](https://img.shields.io/github/license/rameel/ramstack.structures)](https://github.com/rameel/ramstack.structures/blob/main/LICENSE) + +Ramstack.Structures is a .NET library providing various data structures and utilities. + +## Installation + +To install the `Ramstack.Structures` [NuGet package](https://www.nuget.org/packages/Ramstack.Structures) to your project, use the following command: + +```console +dotnet add package Ramstack.Structures +``` + +## Features + +The current release includes primary types: + +* `Ramstack.Text.StringView`:
Represents a read-only view of a string, providing safe and efficient access to a subset of its characters. +* `Ramstack.Collections.ArrayView`:
A generic read-only view of an array, allowing safe and efficient access to a subset of its elements. +* `Ramstack.Collections.ReadOnlyArray`:
A generic read-only array wrapper, similar to `ImmutableArray`, but with some performance improvements and better code generation in certain cases. + +Additionally, the library provides the `StringViewComparer` class, which offers various comparators accessible through corresponding properties: + +| Property | Description | +|--------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------| +| **Ordinal** | Gets a **StringViewComparer** object that performs a case-sensitive ordinal string comparison. | +| **OrdinalIgnoreCase** | Gets a **StringViewComparer** object that performs a case-insensitive ordinal string comparison. | +| **CurrentCulture** | Gets a **StringViewComparer** object that performs case-sensitive string comparisons using the word comparison rules of the current culture. | +| **CurrentCultureIgnoreCase** | Gets a **StringViewComparer** object that performs case-insensitive string comparisons using the word comparison rules of the current culture. | +| **InvariantCulture** | Gets a **StringViewComparer** object that performs a case-sensitive string comparison using the word comparison rules of the invariant culture. | +| **InvariantCultureIgnoreCase** | Gets a **StringViewComparer** object that performs a case-insensitive string comparison using the word comparison rules of the invariant culture. | + +## Notes + +The `ArrayView` and `ReadOnlyArray` types have a `ref readonly` indexer, which provides efficient access to elements of the underlying array, +avoiding expensive copying in the case of large structures. + +This same optimization is also applied to the enumerators of these types. The `Current` property has a `ref readonly` signature, +which enables the following pattern when necessary: + +```csharp +foreach (ref readonly HeavyStruct s in view) +{ + ... +} + +``` + +## Supported versions + +| | Version | +|------|------------| +| .NET | 6, 7, 8, 9 | + +## Contributions + +Bug reports and contributions are welcome. + +## License +This package is released as open source under the **MIT License**. + +See the [LICENSE](LICENSE) file for more details. diff --git a/Ramstack.Structures.Tests/Collections/ArrayViewExtensionsTests.cs b/Ramstack.Structures.Tests/Collections/ArrayViewExtensionsTests.cs index 76c0501..2c01f58 100644 --- a/Ramstack.Structures.Tests/Collections/ArrayViewExtensionsTests.cs +++ b/Ramstack.Structures.Tests/Collections/ArrayViewExtensionsTests.cs @@ -1,30 +1,30 @@ -namespace Ramstack.Collections; - -#if NET9_0_OR_GREATER - -[TestFixture] -public class ArrayViewExtensionsTests -{ - [Test] - public void List_AsView_Empty() - { - var list = new List(); - var view = list.AsView(); - - Assert.That(view.Length, Is.EqualTo(list.Count)); - Assert.That(view, Is.EquivalentTo(list)); - } - - [Test] - public void List_AsView() - { - var list = new List { "apple", "banana", "cherry", "kiwi", "elderberry" }; - var view = list.AsView(); - - Assert.That(view.Length, Is.EqualTo(list.Count)); - Assert.That(view, Is.EquivalentTo(list)); - } - -} - -#endif +namespace Ramstack.Collections; + +#if NET9_0_OR_GREATER + +[TestFixture] +public class ArrayViewExtensionsTests +{ + [Test] + public void List_AsView_Empty() + { + var list = new List(); + var view = list.AsView(); + + Assert.That(view.Length, Is.EqualTo(list.Count)); + Assert.That(view, Is.EquivalentTo(list)); + } + + [Test] + public void List_AsView() + { + var list = new List { "apple", "banana", "cherry", "kiwi", "elderberry" }; + var view = list.AsView(); + + Assert.That(view.Length, Is.EqualTo(list.Count)); + Assert.That(view, Is.EquivalentTo(list)); + } + +} + +#endif diff --git a/Ramstack.Structures.Tests/Collections/ArrayViewTests.cs b/Ramstack.Structures.Tests/Collections/ArrayViewTests.cs index 8874997..3a3dec0 100644 --- a/Ramstack.Structures.Tests/Collections/ArrayViewTests.cs +++ b/Ramstack.Structures.Tests/Collections/ArrayViewTests.cs @@ -1,512 +1,512 @@ -using System.Collections.Immutable; - -namespace Ramstack.Collections; - -[TestFixture] -[SuppressMessage("ReSharper", "ReplaceSliceWithRangeIndexer")] -public class ArrayViewTests -{ - [Test] - public void Empty_HaveZeroLength() - { - Assert.That(ArrayView.Empty.Length, Is.Zero); - } - - [Test] - public void Default_DoesNotThrow() - { - var view = default(ArrayView); - - Assert.That(view.Length, Is.Zero); - Assert.That(view.IsDefault, Is.True); - - for (var i = 0; i < view.Length; i++) - Assert.Fail(); - - foreach (var _ in view) - Assert.Fail(); - - foreach (var _ in view.AsEnumerable()) - Assert.Fail(); - - foreach (var _ in view.AsSpan()) - Assert.Fail(); - - Assert.That(view.ToArray(), Is.EquivalentTo(Array.Empty())); - Assert.That(view.AsMemory().ToArray(), Is.EquivalentTo(Array.Empty())); - Assert.That(view.Slice(0).Length, Is.Zero); - Assert.That(view.Slice(0, 0).Length, Is.Zero); - Assert.That(view, Is.EquivalentTo(Array.Empty())); - } - - [TestCase("value", 0, 0)] - [TestCase("value", 0, 5)] - [TestCase("value", 1, 4)] - [TestCase("value", 2, 3)] - [TestCase("value", 3, 2)] - [TestCase("value", 4, 1)] - [TestCase("value", 5, 0)] - public void Enumeration(string value, int index, int length) - { - var view = new ArrayView(value.ToCharArray(), index, length); - var span = value.AsSpan(index, length); - - Assert.That(view.Length, Is.EqualTo(span.Length)); - - for (var i = 0; i < view.Length; i++) - Assert.That(view[i], Is.EqualTo(span[i])); - - var j = 0; - foreach (var c in view) - Assert.That(c, Is.EqualTo(span[j++])); - - j = 0; - foreach (var c in view.AsEnumerable()) - Assert.That(c, Is.EqualTo(span[j++])); - - for (var i = 0; i < view.Length; i++) - Assert.That(view[i], Is.EqualTo(span[i])); - } - - [TestCase("")] - [TestCase("value")] - [TestCase("key=value")] - public void Ctor(string value) - { - Assert.That( - new ArrayView(value.ToCharArray()), - Is.EquivalentTo(value)); - } - - [TestCase("value", 0)] - [TestCase("value", 5)] - [TestCase("key=value", 4)] - public void Ctor_Index(string value, int index) - { - Assert.That( - new ArrayView(value.ToCharArray(), index), - Is.EquivalentTo(value.AsSpan(index).ToArray())); - } - - [TestCase("", 0, 0)] - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void Ctor_Range(string value, int index, int length) - { - Assert.That( - new ArrayView(value.ToCharArray(), index, length), - Is.EquivalentTo(value.AsSpan(index, length).ToArray())); - } - - [Test] - public void Ctor_NullInput_ShouldThrow() - { - Assert.That(() => new ArrayView(null!), Throws.TypeOf()); - Assert.That(() => new ArrayView(null!, 0), Throws.TypeOf()); - Assert.That(() => new ArrayView(null!, 0, 0), Throws.TypeOf()); - } - - [TestCase("", 1)] - [TestCase("value", -1)] - [TestCase("value", 6)] - public void Ctor_InvalidIndex_ShouldThrow(string value, int index) - { - Assert.That( - () => new ArrayView(value.ToCharArray(), index), - Throws.TypeOf()); - } - - [TestCase("", 1, 0)] - [TestCase("", 0, 1)] - [TestCase("value", -1, 0)] - [TestCase("value", 6, 0)] - [TestCase("value", 0, 6)] - [TestCase("value", 5, 1)] - [TestCase("value", 4, 2)] - public void Ctor_InvalidRange_ShouldThrow(string value, int index, int length) - { - Assert.That( - () => new ArrayView(value.ToCharArray(), index, length), - Throws.TypeOf()); - } - - [Test] - public void Slice() - { - var view = default(ArrayView); - - Assert.That(view.Slice(0).Length, Is.Zero); - Assert.That(view.Slice(0, 0).Length, Is.Zero); - } - - [TestCase("value", 0)] - [TestCase("value", 5)] - [TestCase("key=value", 4)] - public void Slice_Index(string value, int index) - { - Assert.That( - new ArrayView(value.ToCharArray()).Slice(index), - Is.EquivalentTo(value.AsSpan(index).ToArray())); - } - - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void Slice_Range(string value, int index, int length) - { - Assert.That( - new ArrayView(value.ToCharArray()).Slice(index, length), - Is.EquivalentTo(value.AsSpan(index, length).ToArray())); - } - - [TestCase("", 1)] - [TestCase("value", -1)] - [TestCase("value", 6)] - public void Slice_InvalidIndex_ShouldThrow(string value, int index) - { - Assert.That( - () => new ArrayView(value.ToCharArray()).Slice(index), - Throws.TypeOf()); - } - - [TestCase("", 1, 0)] - [TestCase("", 0, 1)] - [TestCase("value", -1, 0)] - [TestCase("value", 6, 0)] - [TestCase("value", 0, 6)] - [TestCase("value", 5, 1)] - [TestCase("value", 4, 2)] - public void Slice_InvalidRange_ShouldThrow(string value, int index, int length) - { - Assert.That( - () => new ArrayView(value.ToCharArray()).Slice(index, length), - Throws.TypeOf()); - } - - [TestCase(null, 0, 0)] - [TestCase("", 0, 0)] - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void Length(string? value, int index, int length) - { - Assert.That( - (value?.ToCharArray()).AsView(index, length).Length, - Is.EqualTo(length)); - } - - [TestCase(null, 0, 0)] - [TestCase("", 0, 0)] - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void ToArray(string? value, int index, int length) - { - Assert.That( - (value?.ToCharArray()).AsView(index, length).ToArray(), - Is.EquivalentTo(value.AsSpan(index, length).ToArray())); - } - - [TestCase("", 0, 0)] - [TestCase("id;name;lastname", 3, 0)] - [TestCase("id;name;lastname", 3, 4)] - [TestCase("id;name;lastname", 0, 2)] - [TestCase("id;name;lastname", 8, 8)] - public void GetPinnableReference(string value, int index, int length) - { - var list = value.ToCharArray(); - var view = list.AsView(index, length); - var span = list.AsSpan(index, length); - - Assert.That( - Unsafe.AreSame( - ref Unsafe.AsRef(in view.GetPinnableReference()), - ref Unsafe.AsRef(in span.GetPinnableReference())), - Is.True); - } - - [Test] - public void GetPinnableReference_Default() - { - var view = default(ArrayView); - var span = default(Span); - - Assert.That( - Unsafe.AreSame( - ref Unsafe.AsRef(in view.GetPinnableReference()), - ref Unsafe.AsRef(in span.GetPinnableReference())), - Is.True); - } - - [TestCase(null)] - [TestCase("")] - [TestCase("test")] - public void Operator_Conversions(string? value) - { - ArrayView view = value?.ToCharArray(); - ReadOnlyMemory memory = view; - ReadOnlySpan span = view; - - Assert.That( - span.ToString() == value.AsSpan().ToString(), - Is.True); - - Assert.That( - memory.ToString() == value.AsMemory().ToString(), - Is.True); - - for (var i = 0; i < view.Length; i++) - { - Assert.That(view[i], Is.EqualTo(span[i])); - Assert.That(view[i], Is.EqualTo(memory.Span[i])); - } - - var j = 0; - foreach (var c in view) - { - Assert.That(c, Is.EqualTo(span[j])); - Assert.That(c, Is.EqualTo(memory.Span[j])); - j++; - } - } - - [TestCase("", 0, 0)] - [TestCase(null, 0, 0)] - [TestCase("text", 0, 4)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - [TestCase("key=value", 5, 0)] - [TestCase("key=value", 3, 0)] - public void CopyTo(string? source, int index, int length) - { - var data = new char[length]; - var list = source?.ToCharArray(); - var view = list.AsView(index, length); - - view.CopyTo(data.AsSpan()); - - Assert.That(view, Is.EquivalentTo(data)); - } - - [TestCase("text", 0, 4)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void CopyTo_InsufficientRoom_ShouldThrow(string? source, int index, int length) - { - var data = new char[length - 1]; - var list = source?.ToCharArray(); - var view = list.AsView(index, length); - - var e = Assert.Throws(() => view.CopyTo(data.AsSpan()))!; - Assert.That(e.Message, Is.EqualTo("Destination is too short. (Parameter 'destination')")); - } - - [TestCase("", 0, 0)] - [TestCase(null, 0, 0)] - [TestCase("text", 0, 4)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - [TestCase("key=value", 5, 0)] - public void TryCopyTo(string? source, int index, int length) - { - var data = new char[length]; - var list = source?.ToCharArray(); - var view = list.AsView(index, length); - - Assert.That(view.TryCopyTo(data.AsSpan()), Is.True); - Assert.That(view, Is.EquivalentTo(data)); - } - - [TestCase("text", 0, 4)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void TryCopyTo_InsufficientRoom_ShouldReturnFalse(string? source, int index, int length) - { - var data = new char[length - 1]; - var list = source?.ToCharArray(); - var view = list.AsView(index, length); - - Assert.That(view.TryCopyTo(data.AsSpan()), Is.False); - Assert.That(data, Is.EquivalentTo(new char[length - 1])); - } - - [TestCase("kiwi")] - [TestCase("KIWI")] - [TestCase("lemon")] - public void IndexOf(string needle) - { - var source = new[] { "apple", "banana", "cherry", "kiwi", "elderberry" }; - - Assert.That( - source.AsView().IndexOf(needle), - Is.EqualTo(source.AsSpan().IndexOf(needle))); - - Assert.That( - source.AsView().IndexOf(needle, null), - Is.EqualTo(Array.IndexOf(source, needle))); - - Assert.That( - source.AsView().IndexOf(needle, StringComparer.OrdinalIgnoreCase), - Is.EqualTo(source.ToList().FindIndex(s => s.Equals(needle, StringComparison.OrdinalIgnoreCase)))); - } - - [TestCase("kiwi")] - [TestCase("KIWI")] - [TestCase("lemon")] - public void LastIndexOf(string needle) - { - var source = new[] { "apple", "banana", "cherry", "kiwi", "elderberry" }; - - Assert.That( - source.AsView().LastIndexOf(needle), - Is.EqualTo(source.AsSpan().LastIndexOf(needle))); - - Assert.That( - source.AsView(1, 3).LastIndexOf(needle), - Is.EqualTo(source.AsSpan(1, 3).LastIndexOf(needle))); - - Assert.That( - source.AsView().LastIndexOf(needle, null), - Is.EqualTo(Array.LastIndexOf(source, needle))); - - Assert.That( - source.AsView().LastIndexOf(needle, StringComparer.OrdinalIgnoreCase), - Is.EqualTo(source.ToList().FindLastIndex(s => s.Equals(needle, StringComparison.OrdinalIgnoreCase)))); - } - - [Test] - public void IndexOf() - { - var source = new[] { "apple", "banana", "cherry", "kiwi", "elderberry" }; - - Assert.That( - source.AsView().IndexOf("kiwi"), - Is.EqualTo(source.AsSpan().IndexOf("kiwi"))); - - Assert.That( - source.AsView().IndexOf("kiwi", null), - Is.EqualTo(Array.IndexOf(source, "kiwi"))); - - Assert.That( - source.AsView().IndexOf("KIWI", StringComparer.OrdinalIgnoreCase), - Is.EqualTo(source.AsSpan().IndexOf("kiwi"))); - } - - [TestCase(null)] - [TestCase("")] - [TestCase("value")] - [TestCase("key=value")] - public void AsView(string? value) - { - var list = value?.ToCharArray(); - var immutable = value.AsSpan().ToArray().ToImmutableArray(); - - Assert.That( - list.AsView(), - Is.EquivalentTo(value.AsSpan().ToArray())); - - Assert.That( - immutable.AsView(), - Is.EquivalentTo(value.AsSpan().ToArray())); - } - - [TestCase(null, 0)] - [TestCase("", 0)] - [TestCase("value", 0)] - [TestCase("value", 5)] - [TestCase("key=value", 0)] - [TestCase("key=value", 3)] - [TestCase("key=value", 4)] - public void AsView_Index(string? value, int index) - { - var list = value?.ToCharArray(); - var immutable = value.AsSpan().ToArray().ToImmutableArray(); - - Assert.That( - list.AsView(index), - Is.EquivalentTo(value.AsSpan(index).ToArray())); - - Assert.That( - immutable.AsView(index), - Is.EquivalentTo(value.AsSpan(index).ToArray())); - } - - [TestCase(null, 0, 0)] - [TestCase("", 0, 0)] - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void AsView_Range(string? value, int index, int length) - { - var list = value?.ToCharArray(); - var immutable = value.AsSpan().ToArray().ToImmutableArray(); - - Assert.That( - list.AsView(index, length), - Is.EquivalentTo(value.AsSpan(index, length).ToArray())); - - Assert.That( - immutable.AsView(index, length), - Is.EquivalentTo(value.AsSpan(index, length).ToArray())); - } - - [TestCase(null, 1)] - [TestCase("", 1)] - [TestCase("value", -1)] - [TestCase("value", 6)] - public void AsView_InvalidIndex_ShouldThrow(string? value, int index) - { - var list = value?.ToCharArray(); - var immutable = value.AsSpan().ToArray().ToImmutableArray(); - - Assert.That( - () => list.AsView(index), - Throws.TypeOf()); - - Assert.That( - () => immutable.AsView(index), - Throws.TypeOf()); - } - - [TestCase(null, 1, 0)] - [TestCase("", 1, 0)] - [TestCase("", 0, 1)] - [TestCase("value", -1, 0)] - [TestCase("value", 6, 0)] - [TestCase("value", 0, 6)] - [TestCase("value", 5, 1)] - [TestCase("value", 4, 2)] - public void AsView_InvalidRange_ShouldThrow(string? value, int index, int length) - { - var list = value?.ToCharArray(); - var immutable = value.AsSpan().ToArray().ToImmutableArray(); - - Assert.That( - () => list.AsView(index, length), - Throws.TypeOf()); - - Assert.That( - () => immutable.AsView(index, length), - Throws.TypeOf()); - } -} +using System.Collections.Immutable; + +namespace Ramstack.Collections; + +[TestFixture] +[SuppressMessage("ReSharper", "ReplaceSliceWithRangeIndexer")] +public class ArrayViewTests +{ + [Test] + public void Empty_HaveZeroLength() + { + Assert.That(ArrayView.Empty.Length, Is.Zero); + } + + [Test] + public void Default_DoesNotThrow() + { + var view = default(ArrayView); + + Assert.That(view.Length, Is.Zero); + Assert.That(view.IsDefault, Is.True); + + for (var i = 0; i < view.Length; i++) + Assert.Fail(); + + foreach (var _ in view) + Assert.Fail(); + + foreach (var _ in view.AsEnumerable()) + Assert.Fail(); + + foreach (var _ in view.AsSpan()) + Assert.Fail(); + + Assert.That(view.ToArray(), Is.EquivalentTo(Array.Empty())); + Assert.That(view.AsMemory().ToArray(), Is.EquivalentTo(Array.Empty())); + Assert.That(view.Slice(0).Length, Is.Zero); + Assert.That(view.Slice(0, 0).Length, Is.Zero); + Assert.That(view, Is.EquivalentTo(Array.Empty())); + } + + [TestCase("value", 0, 0)] + [TestCase("value", 0, 5)] + [TestCase("value", 1, 4)] + [TestCase("value", 2, 3)] + [TestCase("value", 3, 2)] + [TestCase("value", 4, 1)] + [TestCase("value", 5, 0)] + public void Enumeration(string value, int index, int length) + { + var view = new ArrayView(value.ToCharArray(), index, length); + var span = value.AsSpan(index, length); + + Assert.That(view.Length, Is.EqualTo(span.Length)); + + for (var i = 0; i < view.Length; i++) + Assert.That(view[i], Is.EqualTo(span[i])); + + var j = 0; + foreach (var c in view) + Assert.That(c, Is.EqualTo(span[j++])); + + j = 0; + foreach (var c in view.AsEnumerable()) + Assert.That(c, Is.EqualTo(span[j++])); + + for (var i = 0; i < view.Length; i++) + Assert.That(view[i], Is.EqualTo(span[i])); + } + + [TestCase("")] + [TestCase("value")] + [TestCase("key=value")] + public void Ctor(string value) + { + Assert.That( + new ArrayView(value.ToCharArray()), + Is.EquivalentTo(value)); + } + + [TestCase("value", 0)] + [TestCase("value", 5)] + [TestCase("key=value", 4)] + public void Ctor_Index(string value, int index) + { + Assert.That( + new ArrayView(value.ToCharArray(), index), + Is.EquivalentTo(value.AsSpan(index).ToArray())); + } + + [TestCase("", 0, 0)] + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void Ctor_Range(string value, int index, int length) + { + Assert.That( + new ArrayView(value.ToCharArray(), index, length), + Is.EquivalentTo(value.AsSpan(index, length).ToArray())); + } + + [Test] + public void Ctor_NullInput_ShouldThrow() + { + Assert.That(() => new ArrayView(null!), Throws.TypeOf()); + Assert.That(() => new ArrayView(null!, 0), Throws.TypeOf()); + Assert.That(() => new ArrayView(null!, 0, 0), Throws.TypeOf()); + } + + [TestCase("", 1)] + [TestCase("value", -1)] + [TestCase("value", 6)] + public void Ctor_InvalidIndex_ShouldThrow(string value, int index) + { + Assert.That( + () => new ArrayView(value.ToCharArray(), index), + Throws.TypeOf()); + } + + [TestCase("", 1, 0)] + [TestCase("", 0, 1)] + [TestCase("value", -1, 0)] + [TestCase("value", 6, 0)] + [TestCase("value", 0, 6)] + [TestCase("value", 5, 1)] + [TestCase("value", 4, 2)] + public void Ctor_InvalidRange_ShouldThrow(string value, int index, int length) + { + Assert.That( + () => new ArrayView(value.ToCharArray(), index, length), + Throws.TypeOf()); + } + + [Test] + public void Slice() + { + var view = default(ArrayView); + + Assert.That(view.Slice(0).Length, Is.Zero); + Assert.That(view.Slice(0, 0).Length, Is.Zero); + } + + [TestCase("value", 0)] + [TestCase("value", 5)] + [TestCase("key=value", 4)] + public void Slice_Index(string value, int index) + { + Assert.That( + new ArrayView(value.ToCharArray()).Slice(index), + Is.EquivalentTo(value.AsSpan(index).ToArray())); + } + + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void Slice_Range(string value, int index, int length) + { + Assert.That( + new ArrayView(value.ToCharArray()).Slice(index, length), + Is.EquivalentTo(value.AsSpan(index, length).ToArray())); + } + + [TestCase("", 1)] + [TestCase("value", -1)] + [TestCase("value", 6)] + public void Slice_InvalidIndex_ShouldThrow(string value, int index) + { + Assert.That( + () => new ArrayView(value.ToCharArray()).Slice(index), + Throws.TypeOf()); + } + + [TestCase("", 1, 0)] + [TestCase("", 0, 1)] + [TestCase("value", -1, 0)] + [TestCase("value", 6, 0)] + [TestCase("value", 0, 6)] + [TestCase("value", 5, 1)] + [TestCase("value", 4, 2)] + public void Slice_InvalidRange_ShouldThrow(string value, int index, int length) + { + Assert.That( + () => new ArrayView(value.ToCharArray()).Slice(index, length), + Throws.TypeOf()); + } + + [TestCase(null, 0, 0)] + [TestCase("", 0, 0)] + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void Length(string? value, int index, int length) + { + Assert.That( + (value?.ToCharArray()).AsView(index, length).Length, + Is.EqualTo(length)); + } + + [TestCase(null, 0, 0)] + [TestCase("", 0, 0)] + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void ToArray(string? value, int index, int length) + { + Assert.That( + (value?.ToCharArray()).AsView(index, length).ToArray(), + Is.EquivalentTo(value.AsSpan(index, length).ToArray())); + } + + [TestCase("", 0, 0)] + [TestCase("id;name;lastname", 3, 0)] + [TestCase("id;name;lastname", 3, 4)] + [TestCase("id;name;lastname", 0, 2)] + [TestCase("id;name;lastname", 8, 8)] + public void GetPinnableReference(string value, int index, int length) + { + var list = value.ToCharArray(); + var view = list.AsView(index, length); + var span = list.AsSpan(index, length); + + Assert.That( + Unsafe.AreSame( + ref Unsafe.AsRef(in view.GetPinnableReference()), + ref Unsafe.AsRef(in span.GetPinnableReference())), + Is.True); + } + + [Test] + public void GetPinnableReference_Default() + { + var view = default(ArrayView); + var span = default(Span); + + Assert.That( + Unsafe.AreSame( + ref Unsafe.AsRef(in view.GetPinnableReference()), + ref Unsafe.AsRef(in span.GetPinnableReference())), + Is.True); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("test")] + public void Operator_Conversions(string? value) + { + ArrayView view = value?.ToCharArray(); + ReadOnlyMemory memory = view; + ReadOnlySpan span = view; + + Assert.That( + span.ToString() == value.AsSpan().ToString(), + Is.True); + + Assert.That( + memory.ToString() == value.AsMemory().ToString(), + Is.True); + + for (var i = 0; i < view.Length; i++) + { + Assert.That(view[i], Is.EqualTo(span[i])); + Assert.That(view[i], Is.EqualTo(memory.Span[i])); + } + + var j = 0; + foreach (var c in view) + { + Assert.That(c, Is.EqualTo(span[j])); + Assert.That(c, Is.EqualTo(memory.Span[j])); + j++; + } + } + + [TestCase("", 0, 0)] + [TestCase(null, 0, 0)] + [TestCase("text", 0, 4)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + [TestCase("key=value", 5, 0)] + [TestCase("key=value", 3, 0)] + public void CopyTo(string? source, int index, int length) + { + var data = new char[length]; + var list = source?.ToCharArray(); + var view = list.AsView(index, length); + + view.CopyTo(data.AsSpan()); + + Assert.That(view, Is.EquivalentTo(data)); + } + + [TestCase("text", 0, 4)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void CopyTo_InsufficientRoom_ShouldThrow(string? source, int index, int length) + { + var data = new char[length - 1]; + var list = source?.ToCharArray(); + var view = list.AsView(index, length); + + var e = Assert.Throws(() => view.CopyTo(data.AsSpan()))!; + Assert.That(e.Message, Is.EqualTo("Destination is too short. (Parameter 'destination')")); + } + + [TestCase("", 0, 0)] + [TestCase(null, 0, 0)] + [TestCase("text", 0, 4)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + [TestCase("key=value", 5, 0)] + public void TryCopyTo(string? source, int index, int length) + { + var data = new char[length]; + var list = source?.ToCharArray(); + var view = list.AsView(index, length); + + Assert.That(view.TryCopyTo(data.AsSpan()), Is.True); + Assert.That(view, Is.EquivalentTo(data)); + } + + [TestCase("text", 0, 4)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void TryCopyTo_InsufficientRoom_ShouldReturnFalse(string? source, int index, int length) + { + var data = new char[length - 1]; + var list = source?.ToCharArray(); + var view = list.AsView(index, length); + + Assert.That(view.TryCopyTo(data.AsSpan()), Is.False); + Assert.That(data, Is.EquivalentTo(new char[length - 1])); + } + + [TestCase("kiwi")] + [TestCase("KIWI")] + [TestCase("lemon")] + public void IndexOf(string needle) + { + var source = new[] { "apple", "banana", "cherry", "kiwi", "elderberry" }; + + Assert.That( + source.AsView().IndexOf(needle), + Is.EqualTo(source.AsSpan().IndexOf(needle))); + + Assert.That( + source.AsView().IndexOf(needle, null), + Is.EqualTo(Array.IndexOf(source, needle))); + + Assert.That( + source.AsView().IndexOf(needle, StringComparer.OrdinalIgnoreCase), + Is.EqualTo(source.ToList().FindIndex(s => s.Equals(needle, StringComparison.OrdinalIgnoreCase)))); + } + + [TestCase("kiwi")] + [TestCase("KIWI")] + [TestCase("lemon")] + public void LastIndexOf(string needle) + { + var source = new[] { "apple", "banana", "cherry", "kiwi", "elderberry" }; + + Assert.That( + source.AsView().LastIndexOf(needle), + Is.EqualTo(source.AsSpan().LastIndexOf(needle))); + + Assert.That( + source.AsView(1, 3).LastIndexOf(needle), + Is.EqualTo(source.AsSpan(1, 3).LastIndexOf(needle))); + + Assert.That( + source.AsView().LastIndexOf(needle, null), + Is.EqualTo(Array.LastIndexOf(source, needle))); + + Assert.That( + source.AsView().LastIndexOf(needle, StringComparer.OrdinalIgnoreCase), + Is.EqualTo(source.ToList().FindLastIndex(s => s.Equals(needle, StringComparison.OrdinalIgnoreCase)))); + } + + [Test] + public void IndexOf() + { + var source = new[] { "apple", "banana", "cherry", "kiwi", "elderberry" }; + + Assert.That( + source.AsView().IndexOf("kiwi"), + Is.EqualTo(source.AsSpan().IndexOf("kiwi"))); + + Assert.That( + source.AsView().IndexOf("kiwi", null), + Is.EqualTo(Array.IndexOf(source, "kiwi"))); + + Assert.That( + source.AsView().IndexOf("KIWI", StringComparer.OrdinalIgnoreCase), + Is.EqualTo(source.AsSpan().IndexOf("kiwi"))); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("value")] + [TestCase("key=value")] + public void AsView(string? value) + { + var list = value?.ToCharArray(); + var immutable = value.AsSpan().ToArray().ToImmutableArray(); + + Assert.That( + list.AsView(), + Is.EquivalentTo(value.AsSpan().ToArray())); + + Assert.That( + immutable.AsView(), + Is.EquivalentTo(value.AsSpan().ToArray())); + } + + [TestCase(null, 0)] + [TestCase("", 0)] + [TestCase("value", 0)] + [TestCase("value", 5)] + [TestCase("key=value", 0)] + [TestCase("key=value", 3)] + [TestCase("key=value", 4)] + public void AsView_Index(string? value, int index) + { + var list = value?.ToCharArray(); + var immutable = value.AsSpan().ToArray().ToImmutableArray(); + + Assert.That( + list.AsView(index), + Is.EquivalentTo(value.AsSpan(index).ToArray())); + + Assert.That( + immutable.AsView(index), + Is.EquivalentTo(value.AsSpan(index).ToArray())); + } + + [TestCase(null, 0, 0)] + [TestCase("", 0, 0)] + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void AsView_Range(string? value, int index, int length) + { + var list = value?.ToCharArray(); + var immutable = value.AsSpan().ToArray().ToImmutableArray(); + + Assert.That( + list.AsView(index, length), + Is.EquivalentTo(value.AsSpan(index, length).ToArray())); + + Assert.That( + immutable.AsView(index, length), + Is.EquivalentTo(value.AsSpan(index, length).ToArray())); + } + + [TestCase(null, 1)] + [TestCase("", 1)] + [TestCase("value", -1)] + [TestCase("value", 6)] + public void AsView_InvalidIndex_ShouldThrow(string? value, int index) + { + var list = value?.ToCharArray(); + var immutable = value.AsSpan().ToArray().ToImmutableArray(); + + Assert.That( + () => list.AsView(index), + Throws.TypeOf()); + + Assert.That( + () => immutable.AsView(index), + Throws.TypeOf()); + } + + [TestCase(null, 1, 0)] + [TestCase("", 1, 0)] + [TestCase("", 0, 1)] + [TestCase("value", -1, 0)] + [TestCase("value", 6, 0)] + [TestCase("value", 0, 6)] + [TestCase("value", 5, 1)] + [TestCase("value", 4, 2)] + public void AsView_InvalidRange_ShouldThrow(string? value, int index, int length) + { + var list = value?.ToCharArray(); + var immutable = value.AsSpan().ToArray().ToImmutableArray(); + + Assert.That( + () => list.AsView(index, length), + Throws.TypeOf()); + + Assert.That( + () => immutable.AsView(index, length), + Throws.TypeOf()); + } +} diff --git a/Ramstack.Structures.Tests/Collections/ReadOnlyArrayTests.cs b/Ramstack.Structures.Tests/Collections/ReadOnlyArrayTests.cs index f03ba21..f6ce978 100644 --- a/Ramstack.Structures.Tests/Collections/ReadOnlyArrayTests.cs +++ b/Ramstack.Structures.Tests/Collections/ReadOnlyArrayTests.cs @@ -1,601 +1,601 @@ -using System.Collections.Immutable; - -namespace Ramstack.Collections; - -[TestFixture] -public class ReadOnlyArrayTests -{ - [Test] - [SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")] - public void Default_BehavesAsUnderlyingArray() - { - var array = new ReadOnlyArray(); - - Assert.That(array.IsDefault, Is.True); - - Assert.That(() => array.AsSpan(), Throws.Nothing); - Assert.That(() => array.AsSpan(0), Throws.Nothing); - Assert.That(() => array.AsSpan(0, 0), Throws.Nothing); - Assert.That(() => array.AsView(), Throws.Nothing); - Assert.That(() => array.AsView(0), Throws.Nothing); - Assert.That(() => array.AsView(0, 0), Throws.Nothing); - Assert.That(() => array.GetHashCode(), Throws.Nothing); - - Assert.Throws(() => _ = array.Length); - Assert.Throws(() => _ = array[0]); - Assert.Throws(() => array.GetEnumerator()); - Assert.Throws(() => array.GetPinnableReference()); - Assert.Throws(() => array.Any()); - Assert.Throws(() => array.Any(_ => true)); - Assert.Throws(() => array.All(_ => true)); - Assert.Throws(() => array.ToArray()); - Assert.Throws(() => array.Slice(0)); - Assert.Throws(() => array.Slice(0, 0)); - - Assert.Throws(() => array.IndexOf(0)); - Assert.Throws(() => array.LastIndexOf(0)); - } - - [Test] - [SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")] - public void Default_Boxed() - { - var array = (IReadOnlyList)new ReadOnlyArray(); - - Assert.Throws(() => _ = array.Count); - Assert.Throws(() => _ = array[0]); - Assert.Throws(() => array.GetEnumerator()); - } - - [Test] - public void Ctor() - { - for (var count = 1; count < 10; count++) - { - var items = CreateArray(count); - var array = count switch - { - 1 => new ReadOnlyArray(items[0]), - 2 => new ReadOnlyArray(items[0], items[1]), - 3 => new ReadOnlyArray(items[0], items[1], items[2]), - 4 => new ReadOnlyArray(items[0], items[1], items[2], items[3]), - _ => new ReadOnlyArray(items) - }; - - Assert.That(array.Length, Is.EqualTo(items.Length)); - Assert.That(array, Is.EquivalentTo(items)); - } - } - - [TestCase(0)] - [TestCase(4)] - [TestCase(9)] - public void Ctor_Span(int length) - { - ReadOnlySpan span = CreateArray(length); - var array = ReadOnlyArray.Create(span); - - Assert.That(array.Length, Is.EqualTo(length)); - Assert.That(array, Is.EquivalentTo(span.ToArray())); - } - - [Test] - public void Create() - { - #pragma warning disable IDE0303 - for (var count = 1; count < 10; count++) - { - var items = Enumerable.Range(1, count).ToArray(); - var array = count switch - { - 1 => ReadOnlyArray.Create(items[0]), - 2 => ReadOnlyArray.Create(items[0], items[1]), - 3 => ReadOnlyArray.Create(items[0], items[1], items[2]), - 4 => ReadOnlyArray.Create(items[0], items[1], items[2], items[3]), - _ => ReadOnlyArray.Create(items) - }; - - Assert.That(array.Length, Is.EqualTo(items.Length)); - Assert.That(array, Is.EquivalentTo(items)); - } - #pragma warning restore IDE0303 - } - - [TestCase(0)] - [TestCase(4)] - [TestCase(9)] - public void Create_Span(int length) - { - ReadOnlySpan span = Enumerable.Range(1, length).ToArray(); - var array = ReadOnlyArray.Create(span); - - Assert.That(array.Length, Is.EqualTo(length)); - Assert.That(array, Is.EquivalentTo(span.ToArray())); - } - - [TestCase(0)] - [TestCase(4)] - [TestCase(9)] - [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] - public void Create_Enumerable(int length) - { - var enumerable = Enumerable.Range(1, length); - var array = ReadOnlyArray.Create(enumerable); - - Assert.That(array.Length, Is.EqualTo(length)); - Assert.That(array, Is.EquivalentTo(enumerable)); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(5)] - [TestCase(9)] - public void Indexer(int count) - { - var array = Enumerable.Range(1, count).ToReadOnlyArray(); - - Assert.That(array.Length, Is.EqualTo(count)); - - for (var i = 0; i < array.Length; i++) - Assert.That(array[i], Is.EqualTo(i + 1)); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(5)] - [TestCase(9)] - public void GetEnumerator(int count) - { - var array = Enumerable.Range(1, count).ToReadOnlyArray(); - - var x = 1; - foreach (var v in array) - Assert.That(v, Is.EqualTo(x++)); - - Assert.That(array.Length, Is.EqualTo(count)); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(5)] - [TestCase(9)] - public void GetEnumerator_Boxed(int count) - { - var array = Enumerable.Range(1, count).ToReadOnlyArray(); - - var x = 1; - foreach (var v in (IEnumerable)array) - Assert.That(v, Is.EqualTo(x++)); - - Assert.That(array.Length, Is.EqualTo(count)); - } - - [Test] - public void Indexer_Ref() - { - var array = ReadOnlyArray.Create((Key: 1, Value: 1), (Key: 2, Value: 2)); - - Assert.That(array[0].Key, Is.EqualTo(1)); - Assert.That(array[1].Key, Is.EqualTo(2)); - - Unsafe.AsRef(in array[0]).Key = 3; - Unsafe.AsRef(in array[1]).Key = 4; - - Assert.That(array[0].Key, Is.EqualTo(3)); - Assert.That(array[1].Key, Is.EqualTo(4)); - } - - [Test] - public void Indexer_OutOfBounds() - { - Assert.Throws(() => _ = ReadOnlyArray.Create(1, 2, 3, 4)[5]); - Assert.Throws(() => _ = ReadOnlyArray.Empty[5]); - Assert.Throws(() => _ = ReadOnlyArray.Empty()[5]); - } - - [Test] - public void Empty() - { - Assert.That(ReadOnlyArray.Empty.Length, Is.Zero); - Assert.That(ReadOnlyArray.Empty().Length, Is.Zero); - - Assert.That(ReadOnlyArray.Empty.IsDefault, Is.False); - Assert.That(ReadOnlyArray.Empty.IsDefaultOrEmpty, Is.True); - Assert.That(ReadOnlyArray.Empty().IsDefault, Is.False); - Assert.That(ReadOnlyArray.Empty().IsDefaultOrEmpty, Is.True); - } - - [TestCase("value", 0)] - [TestCase("value", 5)] - [TestCase("key=value", 4)] - public void Slice_Index(string value, int index) - { - Assert.That( - value.ToCharArray().ToReadOnlyArray().Slice(index), - Is.EquivalentTo(value.AsSpan(index).ToArray())); - } - - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void Slice_Range(string value, int index, int length) - { - Assert.That( - value.ToCharArray().ToReadOnlyArray().Slice(index, length), - Is.EquivalentTo(value.AsSpan(index, length).ToArray())); - } - - [TestCase(1)] - [TestCase(6)] - [TestCase(-1)] - public void Slice_InvalidIndex_ShouldThrow(int index) - { - Assert.That( - () => Array.Empty().ToReadOnlyArray().Slice(index), - Throws.TypeOf()); - } - - [TestCase(1, 0)] - [TestCase(0, 1)] - [TestCase(6, 0)] - [TestCase(0, 6)] - [TestCase(5, 1)] - [TestCase(4, 2)] - [TestCase(-1, 0)] - [TestCase(4, -1)] - public void Slice_InvalidRange_ShouldThrow(int index, int length) - { - Assert.That( - () => Array.Empty().ToReadOnlyArray().Slice(index, length), - Throws.TypeOf()); - } - - [TestCase("value", 0)] - [TestCase("value", 5)] - [TestCase("key=value", 4)] - public void AsView_Index(string value, int index) - { - Assert.That( - value.ToCharArray().ToReadOnlyArray().AsView(index), - Is.EquivalentTo(value.AsSpan(index).ToArray())); - } - - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void AsView_Range(string value, int index, int length) - { - Assert.That( - value.ToCharArray().ToReadOnlyArray().AsView(index, length), - Is.EquivalentTo(value.AsSpan(index, length).ToArray())); - } - - [TestCase(1)] - [TestCase(6)] - [TestCase(-1)] - public void AsView_InvalidIndex_ShouldThrow(int index) - { - Assert.That( - () => Array.Empty().ToReadOnlyArray().AsView(index), - Throws.TypeOf()); - } - - [TestCase(1, 0)] - [TestCase(0, 1)] - [TestCase(6, 0)] - [TestCase(0, 6)] - [TestCase(5, 1)] - [TestCase(4, 2)] - [TestCase(-1, 0)] - [TestCase(4, -1)] - public void AsView_InvalidRange_ShouldThrow(int index, int length) - { - Assert.That( - () => Array.Empty().ToReadOnlyArray().AsView(index, length), - Throws.TypeOf()); - } - - [TestCase("value", 0)] - [TestCase("value", 5)] - [TestCase("key=value", 4)] - public void AsSpan_Index(string value, int index) - { - Assert.That( - value.ToCharArray().ToReadOnlyArray().AsSpan(index).ToArray(), - Is.EquivalentTo(value.AsSpan(index).ToArray())); - } - - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void AsSpan_Range(string value, int index, int length) - { - Assert.That( - value.ToCharArray().ToReadOnlyArray().AsSpan(index, length).ToArray(), - Is.EquivalentTo(value.AsSpan(index, length).ToArray())); - } - - [TestCase(1)] - [TestCase(6)] - [TestCase(-1)] - public void AsSpan_InvalidIndex_ShouldThrow(int index) - { - Assert.That( - () => Array.Empty().ToReadOnlyArray().AsSpan(index), - Throws.TypeOf()); - } - - [TestCase(1, 0)] - [TestCase(0, 1)] - [TestCase(6, 0)] - [TestCase(0, 6)] - [TestCase(5, 1)] - [TestCase(4, 2)] - [TestCase(-1, 0)] - [TestCase(4, -1)] - public void AsSpan_InvalidRange_ShouldThrow(int index, int length) - { - Assert.That( - () => Array.Empty().ToReadOnlyArray().AsSpan(index, length), - Throws.TypeOf()); - } - - [TestCase(0)] - [TestCase(3)] - [TestCase(9)] - public void GetPinnableReference(int count) - { - var items = new int[count]; - var array = ReadOnlyArray.UnsafeWrap(items); - - Assert.That( - Unsafe.AreSame( - ref Unsafe.AsRef(in array.GetPinnableReference()), - ref Unsafe.AsRef(in MemoryMarshal.GetArrayDataReference(items))), - Is.True); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(5)] - [TestCase(9)] - public void CopyTo(int length) - { - var source = CreateArray(length).ToReadOnlyArray(); - var destination = new int[length]; - - source.CopyTo(destination.AsSpan()); - - Assert.That(source, Is.EquivalentTo(destination)); - } - - [TestCase(1)] - [TestCase(5)] - [TestCase(9)] - public void CopyTo_InsufficientRoom_ShouldThrow(int length) - { - var source = CreateArray(length).ToReadOnlyArray(); - var destination = new int[length - 1]; - - Assert.Throws(() => source.CopyTo(destination.AsSpan())); - Assert.That(destination, Is.EquivalentTo(new int[length - 1])); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(5)] - [TestCase(9)] - public void TryCopyTo(int length) - { - var source = CreateArray(length).ToReadOnlyArray(); - var destination = new int[length]; - - Assert.That(source.TryCopyTo(destination.AsSpan()), Is.True); - Assert.That(source, Is.EquivalentTo(destination)); - } - - [TestCase(1)] - [TestCase(5)] - [TestCase(9)] - public void TryCopyTo_InsufficientRoom_ShouldThrow(int length) - { - var source = CreateArray(length).ToReadOnlyArray(); - var destination = new int[length - 1]; - - Assert.That(source.TryCopyTo(destination.AsSpan()), Is.False); - Assert.That(destination, Is.EquivalentTo(new int[length - 1])); - } - - [Test] - public void UnsafeWrap() - { - var array = new int[10]; - var readonlyArray = ReadOnlyArray.UnsafeWrap(array); - - array[5] = 0xABCD; - Assert.That(readonlyArray[5], Is.EqualTo(0xABCD)); - } - - [Test] - [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] - public void ToReadOnlyArray_Enumerable() - { - var enumerable = Enumerable.Range(1, 100); - - Assert.That( - enumerable.ToReadOnlyArray(), - Is.EquivalentTo(enumerable)); - } - - [Test] - public void ToReadOnlyArray_ImmutableArray() - { - var immutable = Enumerable.Range(1, 100).ToImmutableArray(); - var array = immutable.ToReadOnlyArray(); - - Assert.That( - Unsafe.AreSame( - ref Unsafe.AsRef(in array[0]), - ref Unsafe.AsRef(in immutable.ItemRef(0))), - Is.True); - } - - [Test] - public void ToReadOnlyArray_Span() - { - var source = Enumerable.Range(1, 100).ToArray(); - - Span span1 = source; - ReadOnlySpan span2 = span1; - - var array1 = span1.ToReadOnlyArray(); - var array2 = span2.ToReadOnlyArray(); - - Assert.That(array1, Is.EquivalentTo(source)); - Assert.That(array2, Is.EquivalentTo(source)); - } - - [Test] - public void ToReadOnlyArray_Array() - { - var items = Enumerable.Range(1, 100).ToArray(); - var array = items.ToReadOnlyArray(); - - Assert.That(array, Is.EquivalentTo(items)); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(9)] - public void IndexOf(int length) - { - var array = CreateArray(length); - var readonlyArray = array.ToReadOnlyArray(); - - for (var i = 0; i <= length; i++) - Assert.That( - readonlyArray.IndexOf(i), - Is.EqualTo(Array.IndexOf(array, i))); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(9)] - public void LastIndexOf(int length) - { - var array = CreateArray(length); - var readonlyArray = array.ToReadOnlyArray(); - - for (var i = 0; i <= length; i++) - Assert.That( - readonlyArray.LastIndexOf(i), - Is.EqualTo(Array.LastIndexOf(array, i))); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(9)] - public void Contains(int length) - { - var array = CreateArray(length); - var readonlyArray = array.ToReadOnlyArray(); - - for (var i = -1; i <= length; i++) - Assert.That( - readonlyArray.Contains(i), - Is.EqualTo(Array.LastIndexOf(array, i) >= 0)); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(9)] - public void Interface_IEnumerable(int count) - { - var array = CreateArray(count); - var collection = (IEnumerable)array.ToReadOnlyArray(); - - var value = 0; - foreach (var item in collection) - Assert.That(item, Is.EqualTo(value++)); - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(9)] - [SuppressMessage("ReSharper", "ForCanBeConvertedToForeach")] - public void Interface_IReadOnlyList(int count) - { - var array = CreateArray(count); - var collection = (IReadOnlyList)array.ToReadOnlyArray(); - - Assert.That(collection.Count, Is.EqualTo(count)); - - var value = 0; - for (var i = 0; i < collection.Count; i++) - Assert.That(collection[i], Is.EqualTo(value++)); - } - - [TestCase(null)] - [TestCase("")] - [TestCase("test")] - public void Operator_Conversions(string? value) - { - var array = ReadOnlyArray.UnsafeWrap(value?.ToCharArray()!); - - ArrayView view = array; - ReadOnlyMemory memory = array; - ReadOnlySpan span = array; - ImmutableArray immutable = array; - ReadOnlyArray @readonly = immutable; - - Assert.That(view.Length, Is.EqualTo(value?.Length ?? 0)); - Assert.That(span.Length, Is.EqualTo(value?.Length ?? 0)); - Assert.That(memory.Length, Is.EqualTo(value?.Length ?? 0)); - - Assert.That(array.IsDefault, Is.EqualTo(immutable.IsDefault)); - Assert.That(array.IsDefault, Is.EqualTo(@readonly.IsDefault)); - Assert.That(array.IsDefaultOrEmpty, Is.EqualTo(immutable.IsDefaultOrEmpty)); - Assert.That(array.IsDefaultOrEmpty, Is.EqualTo(@readonly.IsDefaultOrEmpty)); - - if (!array.IsDefault) - { - Assert.That(array.Length, Is.EqualTo(value!.Length)); - Assert.That(immutable.Length, Is.EqualTo(value.Length)); - Assert.That(@readonly.Length, Is.EqualTo(value.Length)); - } - - if (view.Length != 0) - { - Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in view[0])), Is.True); - Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in span[0])), Is.True); - Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in memory.Span[0])), Is.True); - Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in immutable.ItemRef(0))), Is.True); - Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in @readonly[0])), Is.True); - } - } - - [TestCase(0)] - [TestCase(1)] - [TestCase(9)] - public void Linq_ToList(int count) - { - var array = CreateArray(count).ToReadOnlyArray(); - var list = array.ToList(); - - Assert.That(list.Count, Is.EqualTo(count)); - Assert.That(list.Capacity, Is.EqualTo(count)); - Assert.That(list, Is.EqualTo(array)); - } - - private static int[] CreateArray(int length) => - Enumerable.Range(0, length).ToArray(); -} +using System.Collections.Immutable; + +namespace Ramstack.Collections; + +[TestFixture] +public class ReadOnlyArrayTests +{ + [Test] + [SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")] + public void Default_BehavesAsUnderlyingArray() + { + var array = new ReadOnlyArray(); + + Assert.That(array.IsDefault, Is.True); + + Assert.That(() => array.AsSpan(), Throws.Nothing); + Assert.That(() => array.AsSpan(0), Throws.Nothing); + Assert.That(() => array.AsSpan(0, 0), Throws.Nothing); + Assert.That(() => array.AsView(), Throws.Nothing); + Assert.That(() => array.AsView(0), Throws.Nothing); + Assert.That(() => array.AsView(0, 0), Throws.Nothing); + Assert.That(() => array.GetHashCode(), Throws.Nothing); + + Assert.Throws(() => _ = array.Length); + Assert.Throws(() => _ = array[0]); + Assert.Throws(() => array.GetEnumerator()); + Assert.Throws(() => array.GetPinnableReference()); + Assert.Throws(() => array.Any()); + Assert.Throws(() => array.Any(_ => true)); + Assert.Throws(() => array.All(_ => true)); + Assert.Throws(() => array.ToArray()); + Assert.Throws(() => array.Slice(0)); + Assert.Throws(() => array.Slice(0, 0)); + + Assert.Throws(() => array.IndexOf(0)); + Assert.Throws(() => array.LastIndexOf(0)); + } + + [Test] + [SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")] + public void Default_Boxed() + { + var array = (IReadOnlyList)new ReadOnlyArray(); + + Assert.Throws(() => _ = array.Count); + Assert.Throws(() => _ = array[0]); + Assert.Throws(() => array.GetEnumerator()); + } + + [Test] + public void Ctor() + { + for (var count = 1; count < 10; count++) + { + var items = CreateArray(count); + var array = count switch + { + 1 => new ReadOnlyArray(items[0]), + 2 => new ReadOnlyArray(items[0], items[1]), + 3 => new ReadOnlyArray(items[0], items[1], items[2]), + 4 => new ReadOnlyArray(items[0], items[1], items[2], items[3]), + _ => new ReadOnlyArray(items) + }; + + Assert.That(array.Length, Is.EqualTo(items.Length)); + Assert.That(array, Is.EquivalentTo(items)); + } + } + + [TestCase(0)] + [TestCase(4)] + [TestCase(9)] + public void Ctor_Span(int length) + { + ReadOnlySpan span = CreateArray(length); + var array = ReadOnlyArray.Create(span); + + Assert.That(array.Length, Is.EqualTo(length)); + Assert.That(array, Is.EquivalentTo(span.ToArray())); + } + + [Test] + public void Create() + { + #pragma warning disable IDE0303 + for (var count = 1; count < 10; count++) + { + var items = Enumerable.Range(1, count).ToArray(); + var array = count switch + { + 1 => ReadOnlyArray.Create(items[0]), + 2 => ReadOnlyArray.Create(items[0], items[1]), + 3 => ReadOnlyArray.Create(items[0], items[1], items[2]), + 4 => ReadOnlyArray.Create(items[0], items[1], items[2], items[3]), + _ => ReadOnlyArray.Create(items) + }; + + Assert.That(array.Length, Is.EqualTo(items.Length)); + Assert.That(array, Is.EquivalentTo(items)); + } + #pragma warning restore IDE0303 + } + + [TestCase(0)] + [TestCase(4)] + [TestCase(9)] + public void Create_Span(int length) + { + ReadOnlySpan span = Enumerable.Range(1, length).ToArray(); + var array = ReadOnlyArray.Create(span); + + Assert.That(array.Length, Is.EqualTo(length)); + Assert.That(array, Is.EquivalentTo(span.ToArray())); + } + + [TestCase(0)] + [TestCase(4)] + [TestCase(9)] + [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] + public void Create_Enumerable(int length) + { + var enumerable = Enumerable.Range(1, length); + var array = ReadOnlyArray.Create(enumerable); + + Assert.That(array.Length, Is.EqualTo(length)); + Assert.That(array, Is.EquivalentTo(enumerable)); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(5)] + [TestCase(9)] + public void Indexer(int count) + { + var array = Enumerable.Range(1, count).ToReadOnlyArray(); + + Assert.That(array.Length, Is.EqualTo(count)); + + for (var i = 0; i < array.Length; i++) + Assert.That(array[i], Is.EqualTo(i + 1)); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(5)] + [TestCase(9)] + public void GetEnumerator(int count) + { + var array = Enumerable.Range(1, count).ToReadOnlyArray(); + + var x = 1; + foreach (var v in array) + Assert.That(v, Is.EqualTo(x++)); + + Assert.That(array.Length, Is.EqualTo(count)); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(5)] + [TestCase(9)] + public void GetEnumerator_Boxed(int count) + { + var array = Enumerable.Range(1, count).ToReadOnlyArray(); + + var x = 1; + foreach (var v in (IEnumerable)array) + Assert.That(v, Is.EqualTo(x++)); + + Assert.That(array.Length, Is.EqualTo(count)); + } + + [Test] + public void Indexer_Ref() + { + var array = ReadOnlyArray.Create((Key: 1, Value: 1), (Key: 2, Value: 2)); + + Assert.That(array[0].Key, Is.EqualTo(1)); + Assert.That(array[1].Key, Is.EqualTo(2)); + + Unsafe.AsRef(in array[0]).Key = 3; + Unsafe.AsRef(in array[1]).Key = 4; + + Assert.That(array[0].Key, Is.EqualTo(3)); + Assert.That(array[1].Key, Is.EqualTo(4)); + } + + [Test] + public void Indexer_OutOfBounds() + { + Assert.Throws(() => _ = ReadOnlyArray.Create(1, 2, 3, 4)[5]); + Assert.Throws(() => _ = ReadOnlyArray.Empty[5]); + Assert.Throws(() => _ = ReadOnlyArray.Empty()[5]); + } + + [Test] + public void Empty() + { + Assert.That(ReadOnlyArray.Empty.Length, Is.Zero); + Assert.That(ReadOnlyArray.Empty().Length, Is.Zero); + + Assert.That(ReadOnlyArray.Empty.IsDefault, Is.False); + Assert.That(ReadOnlyArray.Empty.IsDefaultOrEmpty, Is.True); + Assert.That(ReadOnlyArray.Empty().IsDefault, Is.False); + Assert.That(ReadOnlyArray.Empty().IsDefaultOrEmpty, Is.True); + } + + [TestCase("value", 0)] + [TestCase("value", 5)] + [TestCase("key=value", 4)] + public void Slice_Index(string value, int index) + { + Assert.That( + value.ToCharArray().ToReadOnlyArray().Slice(index), + Is.EquivalentTo(value.AsSpan(index).ToArray())); + } + + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void Slice_Range(string value, int index, int length) + { + Assert.That( + value.ToCharArray().ToReadOnlyArray().Slice(index, length), + Is.EquivalentTo(value.AsSpan(index, length).ToArray())); + } + + [TestCase(1)] + [TestCase(6)] + [TestCase(-1)] + public void Slice_InvalidIndex_ShouldThrow(int index) + { + Assert.That( + () => Array.Empty().ToReadOnlyArray().Slice(index), + Throws.TypeOf()); + } + + [TestCase(1, 0)] + [TestCase(0, 1)] + [TestCase(6, 0)] + [TestCase(0, 6)] + [TestCase(5, 1)] + [TestCase(4, 2)] + [TestCase(-1, 0)] + [TestCase(4, -1)] + public void Slice_InvalidRange_ShouldThrow(int index, int length) + { + Assert.That( + () => Array.Empty().ToReadOnlyArray().Slice(index, length), + Throws.TypeOf()); + } + + [TestCase("value", 0)] + [TestCase("value", 5)] + [TestCase("key=value", 4)] + public void AsView_Index(string value, int index) + { + Assert.That( + value.ToCharArray().ToReadOnlyArray().AsView(index), + Is.EquivalentTo(value.AsSpan(index).ToArray())); + } + + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void AsView_Range(string value, int index, int length) + { + Assert.That( + value.ToCharArray().ToReadOnlyArray().AsView(index, length), + Is.EquivalentTo(value.AsSpan(index, length).ToArray())); + } + + [TestCase(1)] + [TestCase(6)] + [TestCase(-1)] + public void AsView_InvalidIndex_ShouldThrow(int index) + { + Assert.That( + () => Array.Empty().ToReadOnlyArray().AsView(index), + Throws.TypeOf()); + } + + [TestCase(1, 0)] + [TestCase(0, 1)] + [TestCase(6, 0)] + [TestCase(0, 6)] + [TestCase(5, 1)] + [TestCase(4, 2)] + [TestCase(-1, 0)] + [TestCase(4, -1)] + public void AsView_InvalidRange_ShouldThrow(int index, int length) + { + Assert.That( + () => Array.Empty().ToReadOnlyArray().AsView(index, length), + Throws.TypeOf()); + } + + [TestCase("value", 0)] + [TestCase("value", 5)] + [TestCase("key=value", 4)] + public void AsSpan_Index(string value, int index) + { + Assert.That( + value.ToCharArray().ToReadOnlyArray().AsSpan(index).ToArray(), + Is.EquivalentTo(value.AsSpan(index).ToArray())); + } + + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void AsSpan_Range(string value, int index, int length) + { + Assert.That( + value.ToCharArray().ToReadOnlyArray().AsSpan(index, length).ToArray(), + Is.EquivalentTo(value.AsSpan(index, length).ToArray())); + } + + [TestCase(1)] + [TestCase(6)] + [TestCase(-1)] + public void AsSpan_InvalidIndex_ShouldThrow(int index) + { + Assert.That( + () => Array.Empty().ToReadOnlyArray().AsSpan(index), + Throws.TypeOf()); + } + + [TestCase(1, 0)] + [TestCase(0, 1)] + [TestCase(6, 0)] + [TestCase(0, 6)] + [TestCase(5, 1)] + [TestCase(4, 2)] + [TestCase(-1, 0)] + [TestCase(4, -1)] + public void AsSpan_InvalidRange_ShouldThrow(int index, int length) + { + Assert.That( + () => Array.Empty().ToReadOnlyArray().AsSpan(index, length), + Throws.TypeOf()); + } + + [TestCase(0)] + [TestCase(3)] + [TestCase(9)] + public void GetPinnableReference(int count) + { + var items = new int[count]; + var array = ReadOnlyArray.UnsafeWrap(items); + + Assert.That( + Unsafe.AreSame( + ref Unsafe.AsRef(in array.GetPinnableReference()), + ref Unsafe.AsRef(in MemoryMarshal.GetArrayDataReference(items))), + Is.True); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(5)] + [TestCase(9)] + public void CopyTo(int length) + { + var source = CreateArray(length).ToReadOnlyArray(); + var destination = new int[length]; + + source.CopyTo(destination.AsSpan()); + + Assert.That(source, Is.EquivalentTo(destination)); + } + + [TestCase(1)] + [TestCase(5)] + [TestCase(9)] + public void CopyTo_InsufficientRoom_ShouldThrow(int length) + { + var source = CreateArray(length).ToReadOnlyArray(); + var destination = new int[length - 1]; + + Assert.Throws(() => source.CopyTo(destination.AsSpan())); + Assert.That(destination, Is.EquivalentTo(new int[length - 1])); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(5)] + [TestCase(9)] + public void TryCopyTo(int length) + { + var source = CreateArray(length).ToReadOnlyArray(); + var destination = new int[length]; + + Assert.That(source.TryCopyTo(destination.AsSpan()), Is.True); + Assert.That(source, Is.EquivalentTo(destination)); + } + + [TestCase(1)] + [TestCase(5)] + [TestCase(9)] + public void TryCopyTo_InsufficientRoom_ShouldThrow(int length) + { + var source = CreateArray(length).ToReadOnlyArray(); + var destination = new int[length - 1]; + + Assert.That(source.TryCopyTo(destination.AsSpan()), Is.False); + Assert.That(destination, Is.EquivalentTo(new int[length - 1])); + } + + [Test] + public void UnsafeWrap() + { + var array = new int[10]; + var readonlyArray = ReadOnlyArray.UnsafeWrap(array); + + array[5] = 0xABCD; + Assert.That(readonlyArray[5], Is.EqualTo(0xABCD)); + } + + [Test] + [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] + public void ToReadOnlyArray_Enumerable() + { + var enumerable = Enumerable.Range(1, 100); + + Assert.That( + enumerable.ToReadOnlyArray(), + Is.EquivalentTo(enumerable)); + } + + [Test] + public void ToReadOnlyArray_ImmutableArray() + { + var immutable = Enumerable.Range(1, 100).ToImmutableArray(); + var array = immutable.ToReadOnlyArray(); + + Assert.That( + Unsafe.AreSame( + ref Unsafe.AsRef(in array[0]), + ref Unsafe.AsRef(in immutable.ItemRef(0))), + Is.True); + } + + [Test] + public void ToReadOnlyArray_Span() + { + var source = Enumerable.Range(1, 100).ToArray(); + + Span span1 = source; + ReadOnlySpan span2 = span1; + + var array1 = span1.ToReadOnlyArray(); + var array2 = span2.ToReadOnlyArray(); + + Assert.That(array1, Is.EquivalentTo(source)); + Assert.That(array2, Is.EquivalentTo(source)); + } + + [Test] + public void ToReadOnlyArray_Array() + { + var items = Enumerable.Range(1, 100).ToArray(); + var array = items.ToReadOnlyArray(); + + Assert.That(array, Is.EquivalentTo(items)); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(9)] + public void IndexOf(int length) + { + var array = CreateArray(length); + var readonlyArray = array.ToReadOnlyArray(); + + for (var i = 0; i <= length; i++) + Assert.That( + readonlyArray.IndexOf(i), + Is.EqualTo(Array.IndexOf(array, i))); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(9)] + public void LastIndexOf(int length) + { + var array = CreateArray(length); + var readonlyArray = array.ToReadOnlyArray(); + + for (var i = 0; i <= length; i++) + Assert.That( + readonlyArray.LastIndexOf(i), + Is.EqualTo(Array.LastIndexOf(array, i))); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(9)] + public void Contains(int length) + { + var array = CreateArray(length); + var readonlyArray = array.ToReadOnlyArray(); + + for (var i = -1; i <= length; i++) + Assert.That( + readonlyArray.Contains(i), + Is.EqualTo(Array.LastIndexOf(array, i) >= 0)); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(9)] + public void Interface_IEnumerable(int count) + { + var array = CreateArray(count); + var collection = (IEnumerable)array.ToReadOnlyArray(); + + var value = 0; + foreach (var item in collection) + Assert.That(item, Is.EqualTo(value++)); + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(9)] + [SuppressMessage("ReSharper", "ForCanBeConvertedToForeach")] + public void Interface_IReadOnlyList(int count) + { + var array = CreateArray(count); + var collection = (IReadOnlyList)array.ToReadOnlyArray(); + + Assert.That(collection.Count, Is.EqualTo(count)); + + var value = 0; + for (var i = 0; i < collection.Count; i++) + Assert.That(collection[i], Is.EqualTo(value++)); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("test")] + public void Operator_Conversions(string? value) + { + var array = ReadOnlyArray.UnsafeWrap(value?.ToCharArray()!); + + ArrayView view = array; + ReadOnlyMemory memory = array; + ReadOnlySpan span = array; + ImmutableArray immutable = array; + ReadOnlyArray @readonly = immutable; + + Assert.That(view.Length, Is.EqualTo(value?.Length ?? 0)); + Assert.That(span.Length, Is.EqualTo(value?.Length ?? 0)); + Assert.That(memory.Length, Is.EqualTo(value?.Length ?? 0)); + + Assert.That(array.IsDefault, Is.EqualTo(immutable.IsDefault)); + Assert.That(array.IsDefault, Is.EqualTo(@readonly.IsDefault)); + Assert.That(array.IsDefaultOrEmpty, Is.EqualTo(immutable.IsDefaultOrEmpty)); + Assert.That(array.IsDefaultOrEmpty, Is.EqualTo(@readonly.IsDefaultOrEmpty)); + + if (!array.IsDefault) + { + Assert.That(array.Length, Is.EqualTo(value!.Length)); + Assert.That(immutable.Length, Is.EqualTo(value.Length)); + Assert.That(@readonly.Length, Is.EqualTo(value.Length)); + } + + if (view.Length != 0) + { + Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in view[0])), Is.True); + Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in span[0])), Is.True); + Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in memory.Span[0])), Is.True); + Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in immutable.ItemRef(0))), Is.True); + Assert.That(Unsafe.AreSame(ref Unsafe.AsRef(in array[0]), ref Unsafe.AsRef(in @readonly[0])), Is.True); + } + } + + [TestCase(0)] + [TestCase(1)] + [TestCase(9)] + public void Linq_ToList(int count) + { + var array = CreateArray(count).ToReadOnlyArray(); + var list = array.ToList(); + + Assert.That(list.Count, Is.EqualTo(count)); + Assert.That(list.Capacity, Is.EqualTo(count)); + Assert.That(list, Is.EqualTo(array)); + } + + private static int[] CreateArray(int length) => + Enumerable.Range(0, length).ToArray(); +} diff --git a/Ramstack.Structures.Tests/InteropServices/MemoryMarshalTests.cs b/Ramstack.Structures.Tests/InteropServices/MemoryMarshalTests.cs index 88e2b72..97ca14f 100644 --- a/Ramstack.Structures.Tests/InteropServices/MemoryMarshalTests.cs +++ b/Ramstack.Structures.Tests/InteropServices/MemoryMarshalTests.cs @@ -1,142 +1,142 @@ -namespace Ramstack.InteropServices; - -[TestFixture] -public class MemoryMarshalTests -{ - [Test] - public void CreateStringView() - { - Assert.That( - MemoryMarshal.CreateStringView("Hello, World!", 7).ToString(), - Is.EqualTo("World!")); - - Assert.That( - MemoryMarshal.CreateStringView("Hello, World!", 7).Length, - Is.EqualTo(6)); - - Assert.That( - MemoryMarshal.CreateStringView("Hello, World!", 0, 5).ToString(), - Is.EqualTo("Hello")); - - Assert.That( - MemoryMarshal.CreateStringView("Hello, World!", 0, 5).Length, - Is.EqualTo(5)); - } - - [Test] - public void CreateArrayView() - { - var array = "Hello, World!".ToArray(); - - Assert.That( - MemoryMarshal.CreateArrayView(array, 7).AsSpan().ToString(), - Is.EqualTo("World!")); - - Assert.That( - MemoryMarshal.CreateArrayView(array, 7).Length, - Is.EqualTo(6)); - - Assert.That( - MemoryMarshal.CreateArrayView(array, 0, 5).AsSpan().ToString(), - Is.EqualTo("Hello")); - - Assert.That( - MemoryMarshal.CreateArrayView(array, 0, 5).Length, - Is.EqualTo(5)); - } - - [Test] - public static void ReadOnlyMemory_TryGetStringView() - { - const string Input = "0123456789"; - - var memory = Input.AsMemory(); - Assert.That(memory.IsEmpty, Is.False); - - Assert.That(MemoryMarshal.TryGetStringView(memory, out var view), Is.True); - Assert.That(view, Is.EqualTo(Input)); - - memory = memory[1..]; - Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); - Assert.That(view, Is.EqualTo(Input[1..])); - Assert.That(view.Length, Is.EqualTo(Input.Length - 1)); - - memory = memory[1..]; - Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); - Assert.That(view, Is.EqualTo(Input[2..])); - Assert.That(view.Length, Is.EqualTo(Input.Length - 2)); - - memory = memory.Slice(3, 2); - Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); - Assert.That(view, Is.EqualTo(Input[5..7])); - Assert.That(view.Length, Is.EqualTo(2)); - - memory = memory[memory.Length..]; - Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); - Assert.That(view.Length, Is.Zero); - - memory = memory[..]; - Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); - Assert.That(view.Length, Is.Zero); - - memory = memory[..0]; - Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); - Assert.That(view.Length, Is.Zero); - - Assert.That(memory.IsEmpty, Is.True); - } - - [Test] - public static void ReadOnlyMemory_TryGetStringView_Array_ReturnsFalse() - { - var memory = new char[10].AsMemory(); - Assert.That(MemoryMarshal.TryGetStringView(memory, out var view), Is.False); - Assert.That(view.IsDefault, Is.True); - } - - [Test] - public static void ReadOnlyMemory_TryGetArrayView() - { - var buffer = Enumerable.Range(0, 10).ToArray(); - var memory = buffer.AsMemory(); - - Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.True); - Assert.That(view, Is.EquivalentTo(buffer)); - } - - [Test] - public static void ReadOnlyMemory_TryGetArrayView_EmptyArray() - { - var buffer = Array.Empty(); - var memory = buffer.AsMemory(); - - Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.True); - Assert.That(view, Is.EquivalentTo(buffer)); - } - - [Test] - public static void ReadOnlyMemory_TryGetArrayView_Default() - { - var memory = default(ReadOnlyMemory); - - Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.True); - Assert.That(view, Is.EquivalentTo(Array.Empty())); - } - - [Test] - public static void ReadOnlyMemory_TryGetArrayView_Empty() - { - var memory = ReadOnlyMemory.Empty; - - Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.True); - Assert.That(view, Is.EquivalentTo(Array.Empty())); - } - - [Test] - public static void ReadOnlyMemory_TryGetArrayView_String_ReturnsFalse() - { - var memory = "0123456789".AsMemory(); - Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.False); - Assert.That(view.IsDefault, Is.True); - } -} +namespace Ramstack.InteropServices; + +[TestFixture] +public class MemoryMarshalTests +{ + [Test] + public void CreateStringView() + { + Assert.That( + MemoryMarshal.CreateStringView("Hello, World!", 7).ToString(), + Is.EqualTo("World!")); + + Assert.That( + MemoryMarshal.CreateStringView("Hello, World!", 7).Length, + Is.EqualTo(6)); + + Assert.That( + MemoryMarshal.CreateStringView("Hello, World!", 0, 5).ToString(), + Is.EqualTo("Hello")); + + Assert.That( + MemoryMarshal.CreateStringView("Hello, World!", 0, 5).Length, + Is.EqualTo(5)); + } + + [Test] + public void CreateArrayView() + { + var array = "Hello, World!".ToArray(); + + Assert.That( + MemoryMarshal.CreateArrayView(array, 7).AsSpan().ToString(), + Is.EqualTo("World!")); + + Assert.That( + MemoryMarshal.CreateArrayView(array, 7).Length, + Is.EqualTo(6)); + + Assert.That( + MemoryMarshal.CreateArrayView(array, 0, 5).AsSpan().ToString(), + Is.EqualTo("Hello")); + + Assert.That( + MemoryMarshal.CreateArrayView(array, 0, 5).Length, + Is.EqualTo(5)); + } + + [Test] + public static void ReadOnlyMemory_TryGetStringView() + { + const string Input = "0123456789"; + + var memory = Input.AsMemory(); + Assert.That(memory.IsEmpty, Is.False); + + Assert.That(MemoryMarshal.TryGetStringView(memory, out var view), Is.True); + Assert.That(view, Is.EqualTo(Input)); + + memory = memory[1..]; + Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); + Assert.That(view, Is.EqualTo(Input[1..])); + Assert.That(view.Length, Is.EqualTo(Input.Length - 1)); + + memory = memory[1..]; + Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); + Assert.That(view, Is.EqualTo(Input[2..])); + Assert.That(view.Length, Is.EqualTo(Input.Length - 2)); + + memory = memory.Slice(3, 2); + Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); + Assert.That(view, Is.EqualTo(Input[5..7])); + Assert.That(view.Length, Is.EqualTo(2)); + + memory = memory[memory.Length..]; + Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); + Assert.That(view.Length, Is.Zero); + + memory = memory[..]; + Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); + Assert.That(view.Length, Is.Zero); + + memory = memory[..0]; + Assert.That(MemoryMarshal.TryGetStringView(memory, out view), Is.True); + Assert.That(view.Length, Is.Zero); + + Assert.That(memory.IsEmpty, Is.True); + } + + [Test] + public static void ReadOnlyMemory_TryGetStringView_Array_ReturnsFalse() + { + var memory = new char[10].AsMemory(); + Assert.That(MemoryMarshal.TryGetStringView(memory, out var view), Is.False); + Assert.That(view.IsDefault, Is.True); + } + + [Test] + public static void ReadOnlyMemory_TryGetArrayView() + { + var buffer = Enumerable.Range(0, 10).ToArray(); + var memory = buffer.AsMemory(); + + Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.True); + Assert.That(view, Is.EquivalentTo(buffer)); + } + + [Test] + public static void ReadOnlyMemory_TryGetArrayView_EmptyArray() + { + var buffer = Array.Empty(); + var memory = buffer.AsMemory(); + + Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.True); + Assert.That(view, Is.EquivalentTo(buffer)); + } + + [Test] + public static void ReadOnlyMemory_TryGetArrayView_Default() + { + var memory = default(ReadOnlyMemory); + + Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.True); + Assert.That(view, Is.EquivalentTo(Array.Empty())); + } + + [Test] + public static void ReadOnlyMemory_TryGetArrayView_Empty() + { + var memory = ReadOnlyMemory.Empty; + + Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.True); + Assert.That(view, Is.EquivalentTo(Array.Empty())); + } + + [Test] + public static void ReadOnlyMemory_TryGetArrayView_String_ReturnsFalse() + { + var memory = "0123456789".AsMemory(); + Assert.That(MemoryMarshal.TryGetArrayView(memory, out var view), Is.False); + Assert.That(view.IsDefault, Is.True); + } +} diff --git a/Ramstack.Structures.Tests/Ramstack.Structures.Tests.csproj b/Ramstack.Structures.Tests/Ramstack.Structures.Tests.csproj index 2835311..64da15d 100644 --- a/Ramstack.Structures.Tests/Ramstack.Structures.Tests.csproj +++ b/Ramstack.Structures.Tests/Ramstack.Structures.Tests.csproj @@ -1,32 +1,32 @@ - - - net6.0;net7.0;net8.0;net9.0 - enable - enable - preview - true - true - Ramstack - - - - - - - - - - - - - - - - - - - - - - - + + + net6.0;net7.0;net8.0;net9.0 + enable + enable + preview + true + true + Ramstack + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Ramstack.Structures.Tests/Text/StringViewComparerTests.cs b/Ramstack.Structures.Tests/Text/StringViewComparerTests.cs index 97a95fa..a68cfbd 100644 --- a/Ramstack.Structures.Tests/Text/StringViewComparerTests.cs +++ b/Ramstack.Structures.Tests/Text/StringViewComparerTests.cs @@ -1,169 +1,169 @@ -namespace Ramstack.Text; - -[TestFixture] -public class StringViewComparerTests -{ - [Test] - public void Equals_Ordinal() - { - var comparer = StringViewComparer.Ordinal; - - Assert.That(comparer.Equals("test", "test"), Is.True); - Assert.That(comparer.Equals("test", "Test"), Is.False); - } - - [Test] - public void Equals_OrdinalIgnoreCase() - { - var comparer = StringViewComparer.OrdinalIgnoreCase; - Assert.That(comparer.Equals("test", "Test"), Is.True); - } - - [Test] - public void Equals_CultureCulture() - { - var comparer = StringViewComparer.CurrentCulture; - Assert.That(comparer.Equals("test", "test"), Is.True); - Assert.That(comparer.Equals("test", "Test"), Is.False); - } - - [Test] - public void Equals_CultureCultureIgnoreCase() - { - var comparer = StringViewComparer.CurrentCultureIgnoreCase; - Assert.That(comparer.Equals("test", "Test"), Is.True); - } - - [Test] - public void Equals_InvariantCulture() - { - var comparer = StringViewComparer.InvariantCulture; - Assert.That(comparer.Equals("test", "test"), Is.True); - Assert.That(comparer.Equals("test", "Test"), Is.False); - } - - [Test] - public void Equals_InvariantCultureIgnoreCase() - { - var comparer = StringViewComparer.CurrentCultureIgnoreCase; - Assert.That(comparer.Equals("test", "Test"), Is.True); - } - - [Test] - public void Compare_Ordinal() - { - var comparer = StringViewComparer.Ordinal; - Assert.That(comparer.Compare("test", "test"), Is.Zero); - Assert.That(comparer.Compare("test", "Test"), Is.Not.Zero); - } - - [Test] - public void Compare_OrdinalIgnoreCase() - { - var comparer = StringViewComparer.OrdinalIgnoreCase; - Assert.That(comparer.Compare("test", "Test"), Is.Zero); - } - - [Test] - public void FromComparison_Ordinal() - { - var comparer = StringViewComparer.FromComparison(StringComparison.Ordinal); - Assert.That(comparer, Is.SameAs(StringViewComparer.Ordinal)); - } - - [Test] - public void FromComparison_OrdinalIgnoreCase() - { - var comparer = StringViewComparer.FromComparison(StringComparison.OrdinalIgnoreCase); - Assert.That(comparer, Is.SameAs(StringViewComparer.OrdinalIgnoreCase)); - } - - [Test] - public void FromComparison_CurrentCulture() - { - var comparer = StringViewComparer.CurrentCulture; - Assert.That(comparer.Equals("test", "test"), Is.True); - Assert.That(comparer.Equals("test", "Test"), Is.False); - } - - [Test] - public void FromComparison_CurrentCultureIgnoreCase() - { - var comparer = StringViewComparer.CurrentCultureIgnoreCase; - Assert.That(comparer.Equals("test", "Test"), Is.True); - } - - [Test] - public void FromComparison_InvariantCulture() - { - var comparer = StringViewComparer.FromComparison(StringComparison.InvariantCulture); - Assert.That(comparer, Is.SameAs(StringViewComparer.InvariantCulture)); - } - - [Test] - public void FromComparison_InvariantCultureIgnoreCase() - { - var comparer = StringViewComparer.FromComparison(StringComparison.InvariantCultureIgnoreCase); - Assert.That(comparer, Is.SameAs(StringViewComparer.InvariantCultureIgnoreCase)); - } - - [Test] - public void FromComparison_InvalidComparison() - { - Assert.Throws( - () => StringViewComparer.FromComparison((StringComparison)999)); - } - - [Test] - public void Create() - { - var c1 = StringViewComparer.Create(CultureInfo.InvariantCulture, false); - var c2 = StringViewComparer.Create(CultureInfo.InvariantCulture, CompareOptions.None); - - Assert.That(c1.Equals("test", "test"), Is.True); - Assert.That(c2.Equals("test", "test"), Is.True); - - Assert.That(c1.Equals("test", "TEST"), Is.False); - Assert.That(c2.Equals("test", "TEST"), Is.False); - } - - [Test] - public void Create_IgnoreCase() - { - var c1 = StringViewComparer.Create(CultureInfo.InvariantCulture, true); - var c2 = StringViewComparer.Create(CultureInfo.InvariantCulture, CompareOptions.IgnoreCase); - - Assert.That(c1.Equals("test", "TEST"), Is.True); - Assert.That(c2.Equals("test", "TEST"), Is.True); - } - - #if NET9_0_OR_GREATER - [Test] - public void AlternateComparer_Ordinal() - { - var dictionary = new Dictionary(StringViewComparer.Ordinal) - { - ["test"] = 1 - }; - - var lookup = dictionary.GetAlternateLookup>(); - Assert.That(lookup.TryGetValue("TEST", out _), Is.False); - Assert.That(lookup.TryGetValue("test", out var v), Is.True); - Assert.That(v, Is.EqualTo(1)); - } - - [Test] - public void AlternateComparer_OrdinalIgnoreCase() - { - var dictionary = new Dictionary(StringViewComparer.OrdinalIgnoreCase) - { - ["TEST"] = 1 - }; - - var lookup = dictionary.GetAlternateLookup>(); - Assert.That(lookup.TryGetValue("text", out _), Is.False); - Assert.That(lookup.TryGetValue("test", out var v), Is.True); - Assert.That(v, Is.EqualTo(1)); - } - #endif -} +namespace Ramstack.Text; + +[TestFixture] +public class StringViewComparerTests +{ + [Test] + public void Equals_Ordinal() + { + var comparer = StringViewComparer.Ordinal; + + Assert.That(comparer.Equals("test", "test"), Is.True); + Assert.That(comparer.Equals("test", "Test"), Is.False); + } + + [Test] + public void Equals_OrdinalIgnoreCase() + { + var comparer = StringViewComparer.OrdinalIgnoreCase; + Assert.That(comparer.Equals("test", "Test"), Is.True); + } + + [Test] + public void Equals_CultureCulture() + { + var comparer = StringViewComparer.CurrentCulture; + Assert.That(comparer.Equals("test", "test"), Is.True); + Assert.That(comparer.Equals("test", "Test"), Is.False); + } + + [Test] + public void Equals_CultureCultureIgnoreCase() + { + var comparer = StringViewComparer.CurrentCultureIgnoreCase; + Assert.That(comparer.Equals("test", "Test"), Is.True); + } + + [Test] + public void Equals_InvariantCulture() + { + var comparer = StringViewComparer.InvariantCulture; + Assert.That(comparer.Equals("test", "test"), Is.True); + Assert.That(comparer.Equals("test", "Test"), Is.False); + } + + [Test] + public void Equals_InvariantCultureIgnoreCase() + { + var comparer = StringViewComparer.CurrentCultureIgnoreCase; + Assert.That(comparer.Equals("test", "Test"), Is.True); + } + + [Test] + public void Compare_Ordinal() + { + var comparer = StringViewComparer.Ordinal; + Assert.That(comparer.Compare("test", "test"), Is.Zero); + Assert.That(comparer.Compare("test", "Test"), Is.Not.Zero); + } + + [Test] + public void Compare_OrdinalIgnoreCase() + { + var comparer = StringViewComparer.OrdinalIgnoreCase; + Assert.That(comparer.Compare("test", "Test"), Is.Zero); + } + + [Test] + public void FromComparison_Ordinal() + { + var comparer = StringViewComparer.FromComparison(StringComparison.Ordinal); + Assert.That(comparer, Is.SameAs(StringViewComparer.Ordinal)); + } + + [Test] + public void FromComparison_OrdinalIgnoreCase() + { + var comparer = StringViewComparer.FromComparison(StringComparison.OrdinalIgnoreCase); + Assert.That(comparer, Is.SameAs(StringViewComparer.OrdinalIgnoreCase)); + } + + [Test] + public void FromComparison_CurrentCulture() + { + var comparer = StringViewComparer.CurrentCulture; + Assert.That(comparer.Equals("test", "test"), Is.True); + Assert.That(comparer.Equals("test", "Test"), Is.False); + } + + [Test] + public void FromComparison_CurrentCultureIgnoreCase() + { + var comparer = StringViewComparer.CurrentCultureIgnoreCase; + Assert.That(comparer.Equals("test", "Test"), Is.True); + } + + [Test] + public void FromComparison_InvariantCulture() + { + var comparer = StringViewComparer.FromComparison(StringComparison.InvariantCulture); + Assert.That(comparer, Is.SameAs(StringViewComparer.InvariantCulture)); + } + + [Test] + public void FromComparison_InvariantCultureIgnoreCase() + { + var comparer = StringViewComparer.FromComparison(StringComparison.InvariantCultureIgnoreCase); + Assert.That(comparer, Is.SameAs(StringViewComparer.InvariantCultureIgnoreCase)); + } + + [Test] + public void FromComparison_InvalidComparison() + { + Assert.Throws( + () => StringViewComparer.FromComparison((StringComparison)999)); + } + + [Test] + public void Create() + { + var c1 = StringViewComparer.Create(CultureInfo.InvariantCulture, false); + var c2 = StringViewComparer.Create(CultureInfo.InvariantCulture, CompareOptions.None); + + Assert.That(c1.Equals("test", "test"), Is.True); + Assert.That(c2.Equals("test", "test"), Is.True); + + Assert.That(c1.Equals("test", "TEST"), Is.False); + Assert.That(c2.Equals("test", "TEST"), Is.False); + } + + [Test] + public void Create_IgnoreCase() + { + var c1 = StringViewComparer.Create(CultureInfo.InvariantCulture, true); + var c2 = StringViewComparer.Create(CultureInfo.InvariantCulture, CompareOptions.IgnoreCase); + + Assert.That(c1.Equals("test", "TEST"), Is.True); + Assert.That(c2.Equals("test", "TEST"), Is.True); + } + + #if NET9_0_OR_GREATER + [Test] + public void AlternateComparer_Ordinal() + { + var dictionary = new Dictionary(StringViewComparer.Ordinal) + { + ["test"] = 1 + }; + + var lookup = dictionary.GetAlternateLookup>(); + Assert.That(lookup.TryGetValue("TEST", out _), Is.False); + Assert.That(lookup.TryGetValue("test", out var v), Is.True); + Assert.That(v, Is.EqualTo(1)); + } + + [Test] + public void AlternateComparer_OrdinalIgnoreCase() + { + var dictionary = new Dictionary(StringViewComparer.OrdinalIgnoreCase) + { + ["TEST"] = 1 + }; + + var lookup = dictionary.GetAlternateLookup>(); + Assert.That(lookup.TryGetValue("text", out _), Is.False); + Assert.That(lookup.TryGetValue("test", out var v), Is.True); + Assert.That(v, Is.EqualTo(1)); + } + #endif +} diff --git a/Ramstack.Structures.Tests/Text/StringViewTests.cs b/Ramstack.Structures.Tests/Text/StringViewTests.cs index 9451e12..44bdac0 100644 --- a/Ramstack.Structures.Tests/Text/StringViewTests.cs +++ b/Ramstack.Structures.Tests/Text/StringViewTests.cs @@ -1,923 +1,923 @@ -namespace Ramstack.Text; - -[TestFixture] -[SuppressMessage("ReSharper", "ReplaceSliceWithRangeIndexer")] -public sealed class StringViewTests -{ - [Test] - public void Empty_HaveZeroLength() - { - Assert.That(StringView.Empty.Length, Is.Zero); - } - - [Test] - public void Default_DoesNotThrow() - { - var view = default(StringView); - - Assert.That(view.Length, Is.Zero); - Assert.That(view.IsDefault, Is.True); - - for (var i = 0; i < view.Length; i++) - Assert.Fail(); - - foreach (var _ in view) - Assert.Fail(); - - foreach (var _ in view.AsEnumerable()) - Assert.Fail(); - - foreach (var _ in view.AsSpan()) - Assert.Fail(); - - Assert.That(view.ToArray(), Is.EquivalentTo(Array.Empty())); - Assert.That(view.ToString(), Is.EqualTo("")); - Assert.That(view.AsMemory().ToString(), Is.EqualTo("")); - Assert.That(view.Slice(0).Length, Is.Zero); - Assert.That(view.Slice(0, 0).Length, Is.Zero); - - Assert.That(view == "", Is.True); - Assert.That(view == "".AsView(), Is.True); - } - - [TestCase("", 0, 0)] - [TestCase(" ", 0, 4)] - [TestCase(" ", 1, 3)] - [TestCase(" ", 3, 1)] - [TestCase("value", 0, 5)] - [TestCase(" value", 0, 8)] - [TestCase(" value", 3, 5)] - [TestCase(" value", 2, 6)] - [TestCase("value ", 0, 6)] - public void TrimStart(string value, int index, int length) - { - Assert.That( - value.AsView(index, length).TrimStart().ToString(), - Is.EqualTo(value.AsSpan(index, length).TrimStart().ToString())); - } - - [TestCase("", '-')] - [TestCase("--------", '-')] - [TestCase("--++value", '-')] - [TestCase("--++value", '+')] - [TestCase(" value", '-')] - [TestCase(" value", ' ')] - [TestCase("value", '-')] - public void TrimStart_TrimChar(string value, char trimChar) - { - Assert.That( - value.AsView().TrimStart(trimChar).ToString(), - Is.EqualTo(value.TrimStart(trimChar))); - } - - [TestCase("", "-+")] - [TestCase("--++--++-", "-+")] - [TestCase("--++value", "-+")] - [TestCase("--++value", "?=")] - [TestCase(" value", "-+")] - [TestCase(" value", "-+")] - [TestCase(" value", "")] - [TestCase(" value", null)] - [TestCase("value", "+-")] - [TestCase("value", null)] - public void TrimStart_TrimChars(string value, string? trimChars) - { - Assert.That( - value.AsView().TrimStart(trimChars?.ToCharArray()).ToString(), - Is.EqualTo(value.TrimStart(trimChars?.ToCharArray()))); - - Assert.That( - value.AsView().TrimStart(trimChars.AsSpan()).ToString(), - Is.EqualTo(value.TrimStart(trimChars?.ToCharArray()))); - } - - [TestCase("", 0, 0)] - [TestCase(" ", 0, 4)] - [TestCase(" ", 1, 3)] - [TestCase(" ", 3, 1)] - [TestCase("value", 0, 5)] - [TestCase("value ", 0, 8)] - [TestCase("value ", 0, 5)] - [TestCase("value ", 0, 6)] - [TestCase(" value", 0, 6)] - public void TrimEnd(string value, int index, int length) - { - Assert.That( - value.AsView(index, length).TrimEnd().ToString(), - Is.EqualTo(value.AsSpan(index, length).TrimEnd().ToString())); - } - - [TestCase("", '-')] - [TestCase("---------", '-')] - [TestCase("value--++", '-')] - [TestCase("value--++", '-')] - [TestCase("value--++", '+')] - [TestCase("value ", '-')] - [TestCase("value ", ' ')] - [TestCase("value", '-')] - public void TrimEnd_TrimChar(string value, char trimChar) - { - Assert.That( - value.AsView().TrimEnd(trimChar).ToString(), - Is.EqualTo(value.TrimEnd(trimChar))); - } - - [TestCase("", "-+")] - [TestCase("++--++--+", "-+")] - [TestCase("value++--", "-+")] - [TestCase("value++--", "?=")] - [TestCase("value ", "-+")] - [TestCase("value ", "-+")] - [TestCase("value ", "")] - [TestCase("value ", null)] - [TestCase("value", "+-")] - [TestCase("value", null)] - public void TrimEnd_TrimChars(string value, string? trimChars) - { - Assert.That( - value.AsView().TrimEnd(trimChars?.ToCharArray()).ToString(), - Is.EqualTo(value.TrimEnd(trimChars?.ToCharArray()))); - - Assert.That( - value.AsView().TrimEnd(trimChars.AsSpan()).ToString(), - Is.EqualTo(value.TrimEnd(trimChars?.ToCharArray()))); - } - - [TestCase("", 0, 0)] - [TestCase(" ", 0, 4)] - [TestCase(" ", 1, 3)] - [TestCase(" ", 3, 1)] - [TestCase("value", 0, 5)] - [TestCase(" value", 0, 8)] - [TestCase(" value", 3, 5)] - [TestCase(" value", 2, 6)] - [TestCase("value ", 0, 8)] - [TestCase("value ", 0, 5)] - [TestCase("value ", 0, 6)] - [TestCase(" value ", 0, 11)] - [TestCase(" value ", 1, 9)] - public void Trim(string value, int index, int length) - { - Assert.That( - value.AsView(index, length).Trim().ToString(), - Is.EqualTo(value.AsSpan(index, length).Trim().ToString())); - } - - [TestCase("", '-')] - [TestCase("---------", '-')] - [TestCase("++--value--++", '-')] - [TestCase("++--value--++", '-')] - [TestCase("++--value--++", '+')] - [TestCase(" value ", '-')] - [TestCase(" value ", ' ')] - [TestCase("value", '-')] - public void Trim_TrimChar(string value, char trimChar) - { - Assert.That( - value.AsView().Trim(trimChar).ToString(), - Is.EqualTo(value.Trim(trimChar))); - } - - [TestCase("", "-+")] - [TestCase("++--++--+", "-+")] - [TestCase("--++value++--", "-+")] - [TestCase("--++value++--", "?=")] - [TestCase(" value ", "-+")] - [TestCase(" value ", "-+")] - [TestCase(" value ", "")] - [TestCase(" value ", null)] - [TestCase("value", "+-")] - [TestCase("value", null)] - public void Trim_TrimChars(string value, string? trimChars) - { - Assert.That( - value.AsView().Trim(trimChars?.ToCharArray()).ToString(), - Is.EqualTo(value.Trim(trimChars?.ToCharArray()))); - - Assert.That( - value.AsView().Trim(trimChars.AsSpan()).ToString(), - Is.EqualTo(value.Trim(trimChars?.ToCharArray()))); - } - - [TestCase("value", 0, 0)] - [TestCase("value", 0, 5)] - [TestCase("value", 1, 4)] - [TestCase("value", 2, 3)] - [TestCase("value", 3, 2)] - [TestCase("value", 4, 1)] - [TestCase("value", 5, 0)] - public void Enumeration(string value, int index, int length) - { - var view = new StringView(value, index, length); - var span = value.AsSpan(index, length); - - Assert.That(view.Length, Is.EqualTo(span.Length)); - - for (var i = 0; i < view.Length; i++) - Assert.That(view[i], Is.EqualTo(span[i])); - - var j = 0; - foreach (var c in view) - Assert.That(c, Is.EqualTo(span[j++])); - - j = 0; - foreach (var c in view.AsEnumerable()) - Assert.That(c, Is.EqualTo(span[j++])); - - for (var i = 0; i < view.Length; i++) - Assert.That(view[i], Is.EqualTo(span[i])); - } - - [TestCase("")] - [TestCase("value")] - [TestCase("key=value")] - public void Ctor(string value) - { - Assert.That( - new StringView(value).ToString(), - Is.EqualTo(value.AsSpan().ToString())); - } - - [TestCase("value", 0)] - [TestCase("value", 5)] - [TestCase("key=value", 4)] - public void Ctor_Index(string value, int index) - { - Assert.That( - new StringView(value, index).ToString(), - Is.EqualTo(value.AsSpan(index).ToString())); - } - - [TestCase("", 0, 0)] - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void Ctor_Range(string value, int index, int length) - { - Assert.That( - new StringView(value, index, length).ToString(), - Is.EqualTo(value.AsSpan(index, length).ToString())); - } - - [Test] - public void Ctor_NullInput_ShouldThrow() - { - Assert.That(() => new StringView(null!), Throws.TypeOf()); - Assert.That(() => new StringView(null!, 0), Throws.TypeOf()); - Assert.That(() => new StringView(null!, 0, 0), Throws.TypeOf()); - } - - [TestCase("", 1)] - [TestCase("value", -1)] - [TestCase("value", 6)] - public void Ctor_InvalidIndex_ShouldThrow(string value, int index) - { - Assert.That( - () => new StringView(value, index), - Throws.TypeOf()); - } - - [TestCase("", 1, 0)] - [TestCase("", 0, 1)] - [TestCase("value", -1, 0)] - [TestCase("value", 6, 0)] - [TestCase("value", 0, 6)] - [TestCase("value", 5, 1)] - [TestCase("value", 4, 2)] - public void Ctor_InvalidRange_ShouldThrow(string value, int index, int length) - { - Assert.That( - () => new StringView(value, index, length), - Throws.TypeOf()); - } - - [Test] - public void Slice() - { - var view = default(StringView); - - Assert.That(view.Slice(0).Length, Is.Zero); - Assert.That(view.Slice(0, 0).Length, Is.Zero); - } - - [TestCase("value", 0)] - [TestCase("value", 5)] - [TestCase("key=value", 4)] - public void Slice_Index(string value, int index) - { - Assert.That( - new StringView(value).Slice(index).ToString(), - Is.EqualTo(value.AsSpan(index).ToString())); - } - - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void Slice_Range(string value, int index, int length) - { - Assert.That( - new StringView(value).Slice(index, length).ToString(), - Is.EqualTo(value.AsSpan(index, length).ToString())); - } - - [TestCase("", 1)] - [TestCase("value", -1)] - [TestCase("value", 6)] - public void Slice_InvalidIndex_ShouldThrow(string value, int index) - { - Assert.That( - () => new StringView(value).Slice(index), - Throws.TypeOf()); - } - - [TestCase("", 1, 0)] - [TestCase("", 0, 1)] - [TestCase("value", -1, 0)] - [TestCase("value", 6, 0)] - [TestCase("value", 0, 6)] - [TestCase("value", 5, 1)] - [TestCase("value", 4, 2)] - public void Slice_InvalidRange_ShouldThrow(string value, int index, int length) - { - Assert.That( - () => new StringView(value).Slice(index, length), - Throws.TypeOf()); - } - - [TestCase("value", "value", 0, 5)] - [TestCase("key=value", "value", 4, 5)] - [TestCase("key=value", "key", 0, 3)] - [TestCase("key=value", "=", 3, 1)] - [TestCase("key=value", ">", 3, 1)] - [TestCase("value", "final", 0, 5)] - [TestCase("key=value", "final", 0, 5)] - [TestCase("key=value", "source", 0, 5)] - [TestCase(null, null, 0, 0)] - [TestCase(null, "", 0, 0)] - [TestCase("", null, 0, 0)] - [TestCase("", "", 0, 0)] - public void Equals(string? value, string? other, int index, int length) - { - var view1 = value.AsView(index, length); - var view2 = other.AsView(); - - var span1 = value.AsSpan(index, length); - var span2 = other.AsSpan(); - - Assert.That(view1.Equals(other), Is.EqualTo(span1.SequenceEqual(span2))); - - // ReSharper disable once SuspiciousTypeConversion.Global - Assert.That(view1.Equals((object?)other), Is.EqualTo(span1.SequenceEqual(span2))); - Assert.That(view1.Equals((object?)other.AsView()), Is.EqualTo(span1.SequenceEqual(span2))); - - Assert.That(StringView.Equals(view1, other), Is.EqualTo(span1.SequenceEqual(span2))); - Assert.That(StringView.Equals(view1, view2), Is.EqualTo(span1.SequenceEqual(span2))); - } - - [TestCase("value", "VALUE", 0, 5)] - [TestCase("key=value", "VALUE", 4, 5)] - [TestCase("key=value", "Key", 0, 3)] - [TestCase("key=value", "=", 3, 1)] - [TestCase("key=value", ">", 3, 1)] - [TestCase("value", "final", 0, 5)] - [TestCase("key=value", "final", 0, 5)] - [TestCase("key=value", "source", 0, 5)] - [TestCase(null, null, 0, 0)] - [TestCase(null, "", 0, 0)] - [TestCase("", null, 0, 0)] - [TestCase("", "", 0, 0)] - public void Equals_StringComparison(string? value, string? other, int index, int length) - { - var view1 = value.AsView(index, length); - var view2 = other.AsView(); - - var span1 = value.AsSpan(index, length); - var span2 = other.AsSpan(); - - Assert.That( - view1.Equals(other, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(span1.Equals(span2, StringComparison.OrdinalIgnoreCase))); - - Assert.That( - view1.Equals(view2, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(span1.Equals(span2, StringComparison.OrdinalIgnoreCase))); - - Assert.That( - StringView.Equals(view1, other, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(span1.Equals(span2, StringComparison.OrdinalIgnoreCase))); - - Assert.That( - StringView.Equals(view1, view2, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(span1.Equals(span2, StringComparison.OrdinalIgnoreCase))); - } - - [TestCase("")] - [TestCase("value")] - [TestCase(null)] - public void GetHashCode(string? value) - { - Assert.That( - value.AsView().GetHashCode(), - Is.EqualTo(string.GetHashCode(value.AsSpan()))); - - Assert.That( - (value?.ToUpper()).AsView().GetHashCode(StringComparison.OrdinalIgnoreCase), - Is.EqualTo(string.GetHashCode(value.AsSpan(), StringComparison.OrdinalIgnoreCase))); - } - - [TestCase("Abcd", "Abcd")] - [TestCase("abcd", "abcd")] - [TestCase("1234", "2345")] - [TestCase("2345", "1234")] - [TestCase("", "1234")] - [TestCase("1234", "")] - [TestCase("", null)] - [TestCase(null, "")] - [TestCase("ABCD", "abcd")] - [TestCase("abcde", "abc")] - [TestCase("abc", "abcde")] - public void Compare(string? value, string? other) - { - CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; - - var view1 = value.AsView(); - var view2 = other.AsView(); - - var span1 = value.AsSpan(); - var span2 = other.AsSpan(); - - Assert.That( - StringView.Compare(view1, other, StringComparison.CurrentCulture), - Is.EqualTo(span1.CompareTo(span2, StringComparison.CurrentCulture))); - - Assert.That( - StringView.Compare(view1, view2, StringComparison.CurrentCulture), - Is.EqualTo(span1.CompareTo(span2, StringComparison.CurrentCulture))); - - Assert.That( - view1.CompareTo(view2), - Is.EqualTo(span1.CompareTo(span2, StringComparison.CurrentCulture))); - - Assert.That( - view1.CompareTo(other), - Is.EqualTo(span1.CompareTo(span2, StringComparison.CurrentCulture))); - - Assert.That( - view1.CompareTo(view2, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(span1.CompareTo(span2, StringComparison.OrdinalIgnoreCase))); - - Assert.That( - view1.CompareTo(other, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(span1.CompareTo(span2, StringComparison.OrdinalIgnoreCase))); - } - - [TestCase("Abcd", "Abcd")] - [TestCase("abcd", "abcd")] - [TestCase("1234", "2345")] - [TestCase("2345", "1234")] - [TestCase("", "1234")] - [TestCase("1234", "")] - [TestCase("", null)] - [TestCase(null, "")] - [TestCase("ABCD", "abcd")] - [TestCase("abcde", "abc")] - [TestCase("abc", "abcde")] - public void CompareOrdinal(string? value, string? other) - { - var view1 = value.AsView(); - var view2 = other.AsView(); - - var span1 = value.AsSpan(); - var span2 = other.AsSpan(); - - Assert.That(StringView.CompareOrdinal(view1, other), Is.EqualTo(span1.CompareTo(span2, StringComparison.Ordinal))); - Assert.That(StringView.CompareOrdinal(view1, view2), Is.EqualTo(span1.CompareTo(span2, StringComparison.Ordinal))); - } - - [TestCase("", 0, 0)] - [TestCase(null, 0, 0)] - [TestCase("text", 0, 4)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - [TestCase("key=value", 5, 0)] - [TestCase("key=value", 3, 0)] - public void CopyTo(string? source, int index, int length) - { - var data = new char[length]; - var view = source.AsView(index, length); - - view.CopyTo(data.AsSpan()); - - Assert.That(view, Is.EquivalentTo(data)); - } - - [TestCase("text", 0, 4)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void CopyTo_InsufficientRoom_ShouldThrow(string? source, int index, int length) - { - var data = new char[length - 1]; - var view = source.AsView(index, length); - - var e = Assert.Throws(() => view.CopyTo(data.AsSpan()))!; - Assert.That(e.Message, Is.EqualTo("Destination is too short. (Parameter 'destination')")); - } - - [TestCase("", 0, 0)] - [TestCase(null, 0, 0)] - [TestCase("text", 0, 4)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - [TestCase("key=value", 5, 0)] - public void TryCopyTo(string? source, int index, int length) - { - var data = new char[length]; - var view = source.AsView(index, length); - - Assert.That(view.TryCopyTo(data.AsSpan()), Is.True); - Assert.That(view, Is.EquivalentTo(data)); - } - - [TestCase("text", 0, 4)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void TryCopyTo_InsufficientRoom_ShouldReturnFalse(string? source, int index, int length) - { - var data = new char[length - 1]; - var view = source.AsView(index, length); - - Assert.That(view.TryCopyTo(data.AsSpan()), Is.False); - Assert.That(data, Is.EquivalentTo(new char[length - 1])); - } - - [TestCase(null)] - [TestCase("")] - [TestCase("value")] - [TestCase("key=value")] - public void AsView(string? value) - { - Assert.That( - value.AsView().ToString(), - Is.EqualTo(value.AsSpan().ToString())); - } - - [TestCase(null, 0)] - [TestCase("", 0)] - [TestCase("value", 0)] - [TestCase("value", 5)] - [TestCase("key=value", 0)] - [TestCase("key=value", 3)] - [TestCase("key=value", 4)] - public void AsView_Index(string? value, int index) - { - Assert.That( - value.AsView(index).ToString(), - Is.EqualTo(value.AsSpan(index).ToString())); - } - - [TestCase(null, 0, 0)] - [TestCase("", 0, 0)] - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void AsView_Range(string? value, int index, int length) - { - Assert.That( - value.AsView(index, length).ToString(), - Is.EqualTo(value.AsSpan(index, length).ToString())); - } - - [TestCase(null, 1)] - [TestCase("", 1)] - [TestCase("value", -1)] - [TestCase("value", 6)] - public void AsView_InvalidIndex_ShouldThrow(string? value, int index) - { - Assert.That( - () => value.AsView(index), - Throws.TypeOf()); - } - - [TestCase(null, 1, 0)] - [TestCase("", 1, 0)] - [TestCase("", 0, 1)] - [TestCase("value", -1, 0)] - [TestCase("value", 6, 0)] - [TestCase("value", 0, 6)] - [TestCase("value", 5, 1)] - [TestCase("value", 4, 2)] - public void AsView_InvalidRange_ShouldThrow(string? value, int index, int length) - { - Assert.That( - () => value.AsView(index, length), - Throws.TypeOf()); - } - - [TestCase("Hello", 'H', true)] - [TestCase("Hello", 'h', false)] - [TestCase("", 'A', false)] - [TestCase(null, 'A', false)] - public void StartsWith_Char(string? source, char needle, bool expected) - { - Assert.That(source.AsView().StartsWith(needle), Is.EqualTo(expected)); - } - - [TestCase("Hello", "H")] - [TestCase("Hello", "h")] - [TestCase("Hello", "O")] - [TestCase("", "A")] - [TestCase(null, "A")] - [TestCase("", "")] - [TestCase(null, "")] - [TestCase(null, null)] - [TestCase("", null)] - public void StartsWith_Text(string? source, string? needle) - { - Assert.That( - source.AsView().StartsWith(needle), - Is.EqualTo(source.AsSpan().StartsWith(needle))); - - Assert.That( - source.AsView().StartsWith(needle, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(source.AsSpan().StartsWith(needle, StringComparison.OrdinalIgnoreCase))); - } - - [TestCase("Hello", 'o', true)] - [TestCase("Hello", 'h', false)] - [TestCase("", 'a', false)] - [TestCase(null, 'a', false)] - public void EndsWith_Char(string? source, char needle, bool expected) - { - Assert.That( - source.AsView().EndsWith(needle), - Is.EqualTo(expected)); - } - - [TestCase("Hello", "o")] - [TestCase("Hello", "O")] - [TestCase("Hello", "h")] - [TestCase("", "A")] - [TestCase(null, "A")] - [TestCase("", "")] - [TestCase(null, "")] - [TestCase(null, null)] - [TestCase("", null)] - public void EndsWith_Text(string? source, string? needle) - { - Assert.That( - source.AsView().EndsWith(needle), - Is.EqualTo(source.AsSpan().EndsWith(needle))); - - Assert.That( - source.AsView().EndsWith(needle, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(source.AsSpan().EndsWith(needle, StringComparison.OrdinalIgnoreCase))); - } - - [TestCase("Hello, world!", 'H')] - [TestCase("Hello, world!", 'd')] - [TestCase("Hello, world!", 'o')] - [TestCase("Hello, world!", '!')] - [TestCase("Hello, world!", ',')] - [TestCase("Hello, world!", 'A')] - [TestCase("", 'A')] - [TestCase(null, 'A')] - public void IndexOf_Char(string? source, char needle) - { - Assert.That( - source.AsView().IndexOf(needle), - Is.EqualTo(source.AsSpan().IndexOf(needle))); - } - - [TestCase("Hello, world!", "world")] - [TestCase("Hello, world!", "World")] - [TestCase("Hello, world!", "hello")] - [TestCase("Hello, world!", "Hello")] - [TestCase("Hello, world!", "w")] - [TestCase("Hello, world!", ",")] - [TestCase("Hello, world!", "?")] - [TestCase("Hello, world!", "")] - [TestCase("", "")] - [TestCase(null, "")] - public void IndexOf_Text(string? source, string needle) - { - Assert.That( - source.AsView().IndexOf(needle), - Is.EqualTo(source.AsSpan().IndexOf(needle))); - - Assert.That( - source.AsView().IndexOf(needle, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(source.AsSpan().IndexOf(needle, StringComparison.OrdinalIgnoreCase))); - } - - [TestCase("Hello, world!", 'H')] - [TestCase("Hello, world!", 'd')] - [TestCase("Hello, world!", 'o')] - [TestCase("Hello, world!", '!')] - [TestCase("Hello, world!", ',')] - [TestCase("Hello, world!", 'A')] - [TestCase("", 'A')] - [TestCase(null, 'A')] - public void LastIndexOf_Char(string? source, char needle) - { - Assert.That( - source.AsView().LastIndexOf(needle), - Is.EqualTo(source.AsSpan().LastIndexOf(needle))); - } - - [TestCase("Hello, world!", "World")] - [TestCase("Hello, world!", "hello")] - [TestCase("Hello, world!", "?")] - [TestCase("", "")] - [TestCase(null, "")] - public void LastIndexOf_Text(string? source, string needle) - { - Assert.That( - source.AsView().LastIndexOf(needle), - Is.EqualTo(source.AsSpan().LastIndexOf(needle))); - - Assert.That( - source.AsView().LastIndexOf(needle, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(source.AsSpan().LastIndexOf(needle, StringComparison.OrdinalIgnoreCase))); - } - - [TestCase("Hello, world!", 'H')] - [TestCase("Hello, world!", '!')] - [TestCase("Hello, world!", ',')] - [TestCase("Hello, world!", 'A')] - [TestCase("", 'A')] - [TestCase(null, 'A')] - public void Contains_Char(string? source, char needle) - { - Assert.That( - source.AsView().Contains(needle), - Is.EqualTo(source.AsSpan().Contains(needle))); - } - - [TestCase("Hello, world!", "world")] - [TestCase("Hello, world!", "World")] - [TestCase("Hello, world!", "w")] - [TestCase("Hello, world!", ",")] - [TestCase("Hello, world!", "?")] - [TestCase("Hello, world!", "")] - [TestCase("", "")] - [TestCase(null, "")] - public void Contains_Text(string? source, string needle) - { - Assert.That( - source.AsView().Contains(needle), - Is.EqualTo(source.AsSpan().Contains(needle, StringComparison.Ordinal))); - - Assert.That( - source.AsView().Contains(needle, StringComparison.OrdinalIgnoreCase), - Is.EqualTo(source.AsSpan().Contains(needle, StringComparison.OrdinalIgnoreCase))); - } - - [TestCase(null, 0, 0)] - [TestCase("", 0, 0)] - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void Length(string? value, int index, int length) - { - Assert.That( - value.AsView(index, length).Length, - Is.EqualTo(length)); - } - - [TestCase(null, 0, 0)] - [TestCase("", 0, 0)] - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void ToString(string? value, int index, int length) - { - Assert.That( - value.AsView(index, length).ToString(), - Is.EqualTo(value.AsSpan(index, length).ToString())); - } - - [TestCase(null, 0, 0)] - [TestCase("", 0, 0)] - [TestCase("value", 0, 0)] - [TestCase("value", 5, 0)] - [TestCase("value", 0, 5)] - [TestCase("key=value", 0, 3)] - [TestCase("key=value", 3, 1)] - [TestCase("key=value", 4, 5)] - public void ToArray(string? value, int index, int length) - { - Assert.That( - value.AsView(index, length).ToArray(), - Is.EquivalentTo(value.AsSpan(index, length).ToArray())); - } - - [TestCase("", 0, 0)] - [TestCase(null, 0, 0)] - [TestCase("id;name;lastname", 3, 0)] - [TestCase("id;name;lastname", 3, 4)] - [TestCase("id;name;lastname", 0, 2)] - [TestCase("id;name;lastname", 8, 8)] - public void GetPinnableReference(string? value, int index, int length) - { - var view = value.AsView(index, length); - var span = value.AsSpan(index, length); - - Assert.That( - Unsafe.AreSame( - ref Unsafe.AsRef(in view.GetPinnableReference()), - ref Unsafe.AsRef(in span.GetPinnableReference())), - Is.True); - } - - [Test] - public void GetPinnableReference_Default() - { - var view = default(StringView); - view.GetPinnableReference(); - } - - [TestCase("value", "value", 0, 5, true)] - [TestCase("key=value", "value", 4, 5, true)] - [TestCase("key=value", "key", 0, 3, true)] - [TestCase("key=value", "=", 3, 1, true)] - [TestCase("key=value", ">", 3, 1, false)] - [TestCase("value", "final", 0, 5, false)] - [TestCase("key=value", "final", 0, 5, false)] - [TestCase("key=value", "source", 0, 5, false)] - [TestCase("key=value", "", 0, 0, true)] - [TestCase("key=value", null, 0, 0, true)] - [TestCase(null, null, 0, 0, true)] - [TestCase(null, "", 0, 0, true)] - [TestCase("", null, 0, 0, true)] - [TestCase("", "", 0, 0, true)] - public void Operator_Equals(string? source, string? value, int index, int length, bool expected) - { - Assert.That(source.AsView(index, length) == value, Is.EqualTo(expected)); - Assert.That(source.AsView(index, length) == value.AsView(), Is.EqualTo(expected)); - } - - [TestCase("value", "key", true)] - [TestCase("key", "value", true)] - [TestCase("key", "Key", true)] - [TestCase("key", "key", false)] - [TestCase("key", "", true)] - [TestCase("key", null, true)] - [TestCase("", "key", true)] - [TestCase(null, "key", true)] - public void Operator_NotEquals(string? source, string? value, bool expected) - { - Assert.That(source.AsView() != value, Is.EqualTo(expected)); - Assert.That(source.AsView() != value.AsView(), Is.EqualTo(expected)); - } - - [TestCase(null)] - [TestCase("")] - [TestCase("test")] - public void Operator_Conversions(string? value) - { - StringView view = value; - ReadOnlyMemory memory = view; - ReadOnlySpan span = view; - - Assert.That( - span.ToString() == value.AsSpan().ToString(), - Is.True); - - Assert.That( - memory.ToString() == value.AsMemory().ToString(), - Is.True); - - for (var i = 0; i < view.Length; i++) - { - Assert.That(view[i], Is.EqualTo(span[i])); - Assert.That(view[i], Is.EqualTo(memory.Span[i])); - } - - var j = 0; - foreach (var c in view) - { - Assert.That(c, Is.EqualTo(span[j])); - Assert.That(c, Is.EqualTo(memory.Span[j])); - j++; - } - } -} +namespace Ramstack.Text; + +[TestFixture] +[SuppressMessage("ReSharper", "ReplaceSliceWithRangeIndexer")] +public sealed class StringViewTests +{ + [Test] + public void Empty_HaveZeroLength() + { + Assert.That(StringView.Empty.Length, Is.Zero); + } + + [Test] + public void Default_DoesNotThrow() + { + var view = default(StringView); + + Assert.That(view.Length, Is.Zero); + Assert.That(view.IsDefault, Is.True); + + for (var i = 0; i < view.Length; i++) + Assert.Fail(); + + foreach (var _ in view) + Assert.Fail(); + + foreach (var _ in view.AsEnumerable()) + Assert.Fail(); + + foreach (var _ in view.AsSpan()) + Assert.Fail(); + + Assert.That(view.ToArray(), Is.EquivalentTo(Array.Empty())); + Assert.That(view.ToString(), Is.EqualTo("")); + Assert.That(view.AsMemory().ToString(), Is.EqualTo("")); + Assert.That(view.Slice(0).Length, Is.Zero); + Assert.That(view.Slice(0, 0).Length, Is.Zero); + + Assert.That(view == "", Is.True); + Assert.That(view == "".AsView(), Is.True); + } + + [TestCase("", 0, 0)] + [TestCase(" ", 0, 4)] + [TestCase(" ", 1, 3)] + [TestCase(" ", 3, 1)] + [TestCase("value", 0, 5)] + [TestCase(" value", 0, 8)] + [TestCase(" value", 3, 5)] + [TestCase(" value", 2, 6)] + [TestCase("value ", 0, 6)] + public void TrimStart(string value, int index, int length) + { + Assert.That( + value.AsView(index, length).TrimStart().ToString(), + Is.EqualTo(value.AsSpan(index, length).TrimStart().ToString())); + } + + [TestCase("", '-')] + [TestCase("--------", '-')] + [TestCase("--++value", '-')] + [TestCase("--++value", '+')] + [TestCase(" value", '-')] + [TestCase(" value", ' ')] + [TestCase("value", '-')] + public void TrimStart_TrimChar(string value, char trimChar) + { + Assert.That( + value.AsView().TrimStart(trimChar).ToString(), + Is.EqualTo(value.TrimStart(trimChar))); + } + + [TestCase("", "-+")] + [TestCase("--++--++-", "-+")] + [TestCase("--++value", "-+")] + [TestCase("--++value", "?=")] + [TestCase(" value", "-+")] + [TestCase(" value", "-+")] + [TestCase(" value", "")] + [TestCase(" value", null)] + [TestCase("value", "+-")] + [TestCase("value", null)] + public void TrimStart_TrimChars(string value, string? trimChars) + { + Assert.That( + value.AsView().TrimStart(trimChars?.ToCharArray()).ToString(), + Is.EqualTo(value.TrimStart(trimChars?.ToCharArray()))); + + Assert.That( + value.AsView().TrimStart(trimChars.AsSpan()).ToString(), + Is.EqualTo(value.TrimStart(trimChars?.ToCharArray()))); + } + + [TestCase("", 0, 0)] + [TestCase(" ", 0, 4)] + [TestCase(" ", 1, 3)] + [TestCase(" ", 3, 1)] + [TestCase("value", 0, 5)] + [TestCase("value ", 0, 8)] + [TestCase("value ", 0, 5)] + [TestCase("value ", 0, 6)] + [TestCase(" value", 0, 6)] + public void TrimEnd(string value, int index, int length) + { + Assert.That( + value.AsView(index, length).TrimEnd().ToString(), + Is.EqualTo(value.AsSpan(index, length).TrimEnd().ToString())); + } + + [TestCase("", '-')] + [TestCase("---------", '-')] + [TestCase("value--++", '-')] + [TestCase("value--++", '-')] + [TestCase("value--++", '+')] + [TestCase("value ", '-')] + [TestCase("value ", ' ')] + [TestCase("value", '-')] + public void TrimEnd_TrimChar(string value, char trimChar) + { + Assert.That( + value.AsView().TrimEnd(trimChar).ToString(), + Is.EqualTo(value.TrimEnd(trimChar))); + } + + [TestCase("", "-+")] + [TestCase("++--++--+", "-+")] + [TestCase("value++--", "-+")] + [TestCase("value++--", "?=")] + [TestCase("value ", "-+")] + [TestCase("value ", "-+")] + [TestCase("value ", "")] + [TestCase("value ", null)] + [TestCase("value", "+-")] + [TestCase("value", null)] + public void TrimEnd_TrimChars(string value, string? trimChars) + { + Assert.That( + value.AsView().TrimEnd(trimChars?.ToCharArray()).ToString(), + Is.EqualTo(value.TrimEnd(trimChars?.ToCharArray()))); + + Assert.That( + value.AsView().TrimEnd(trimChars.AsSpan()).ToString(), + Is.EqualTo(value.TrimEnd(trimChars?.ToCharArray()))); + } + + [TestCase("", 0, 0)] + [TestCase(" ", 0, 4)] + [TestCase(" ", 1, 3)] + [TestCase(" ", 3, 1)] + [TestCase("value", 0, 5)] + [TestCase(" value", 0, 8)] + [TestCase(" value", 3, 5)] + [TestCase(" value", 2, 6)] + [TestCase("value ", 0, 8)] + [TestCase("value ", 0, 5)] + [TestCase("value ", 0, 6)] + [TestCase(" value ", 0, 11)] + [TestCase(" value ", 1, 9)] + public void Trim(string value, int index, int length) + { + Assert.That( + value.AsView(index, length).Trim().ToString(), + Is.EqualTo(value.AsSpan(index, length).Trim().ToString())); + } + + [TestCase("", '-')] + [TestCase("---------", '-')] + [TestCase("++--value--++", '-')] + [TestCase("++--value--++", '-')] + [TestCase("++--value--++", '+')] + [TestCase(" value ", '-')] + [TestCase(" value ", ' ')] + [TestCase("value", '-')] + public void Trim_TrimChar(string value, char trimChar) + { + Assert.That( + value.AsView().Trim(trimChar).ToString(), + Is.EqualTo(value.Trim(trimChar))); + } + + [TestCase("", "-+")] + [TestCase("++--++--+", "-+")] + [TestCase("--++value++--", "-+")] + [TestCase("--++value++--", "?=")] + [TestCase(" value ", "-+")] + [TestCase(" value ", "-+")] + [TestCase(" value ", "")] + [TestCase(" value ", null)] + [TestCase("value", "+-")] + [TestCase("value", null)] + public void Trim_TrimChars(string value, string? trimChars) + { + Assert.That( + value.AsView().Trim(trimChars?.ToCharArray()).ToString(), + Is.EqualTo(value.Trim(trimChars?.ToCharArray()))); + + Assert.That( + value.AsView().Trim(trimChars.AsSpan()).ToString(), + Is.EqualTo(value.Trim(trimChars?.ToCharArray()))); + } + + [TestCase("value", 0, 0)] + [TestCase("value", 0, 5)] + [TestCase("value", 1, 4)] + [TestCase("value", 2, 3)] + [TestCase("value", 3, 2)] + [TestCase("value", 4, 1)] + [TestCase("value", 5, 0)] + public void Enumeration(string value, int index, int length) + { + var view = new StringView(value, index, length); + var span = value.AsSpan(index, length); + + Assert.That(view.Length, Is.EqualTo(span.Length)); + + for (var i = 0; i < view.Length; i++) + Assert.That(view[i], Is.EqualTo(span[i])); + + var j = 0; + foreach (var c in view) + Assert.That(c, Is.EqualTo(span[j++])); + + j = 0; + foreach (var c in view.AsEnumerable()) + Assert.That(c, Is.EqualTo(span[j++])); + + for (var i = 0; i < view.Length; i++) + Assert.That(view[i], Is.EqualTo(span[i])); + } + + [TestCase("")] + [TestCase("value")] + [TestCase("key=value")] + public void Ctor(string value) + { + Assert.That( + new StringView(value).ToString(), + Is.EqualTo(value.AsSpan().ToString())); + } + + [TestCase("value", 0)] + [TestCase("value", 5)] + [TestCase("key=value", 4)] + public void Ctor_Index(string value, int index) + { + Assert.That( + new StringView(value, index).ToString(), + Is.EqualTo(value.AsSpan(index).ToString())); + } + + [TestCase("", 0, 0)] + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void Ctor_Range(string value, int index, int length) + { + Assert.That( + new StringView(value, index, length).ToString(), + Is.EqualTo(value.AsSpan(index, length).ToString())); + } + + [Test] + public void Ctor_NullInput_ShouldThrow() + { + Assert.That(() => new StringView(null!), Throws.TypeOf()); + Assert.That(() => new StringView(null!, 0), Throws.TypeOf()); + Assert.That(() => new StringView(null!, 0, 0), Throws.TypeOf()); + } + + [TestCase("", 1)] + [TestCase("value", -1)] + [TestCase("value", 6)] + public void Ctor_InvalidIndex_ShouldThrow(string value, int index) + { + Assert.That( + () => new StringView(value, index), + Throws.TypeOf()); + } + + [TestCase("", 1, 0)] + [TestCase("", 0, 1)] + [TestCase("value", -1, 0)] + [TestCase("value", 6, 0)] + [TestCase("value", 0, 6)] + [TestCase("value", 5, 1)] + [TestCase("value", 4, 2)] + public void Ctor_InvalidRange_ShouldThrow(string value, int index, int length) + { + Assert.That( + () => new StringView(value, index, length), + Throws.TypeOf()); + } + + [Test] + public void Slice() + { + var view = default(StringView); + + Assert.That(view.Slice(0).Length, Is.Zero); + Assert.That(view.Slice(0, 0).Length, Is.Zero); + } + + [TestCase("value", 0)] + [TestCase("value", 5)] + [TestCase("key=value", 4)] + public void Slice_Index(string value, int index) + { + Assert.That( + new StringView(value).Slice(index).ToString(), + Is.EqualTo(value.AsSpan(index).ToString())); + } + + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void Slice_Range(string value, int index, int length) + { + Assert.That( + new StringView(value).Slice(index, length).ToString(), + Is.EqualTo(value.AsSpan(index, length).ToString())); + } + + [TestCase("", 1)] + [TestCase("value", -1)] + [TestCase("value", 6)] + public void Slice_InvalidIndex_ShouldThrow(string value, int index) + { + Assert.That( + () => new StringView(value).Slice(index), + Throws.TypeOf()); + } + + [TestCase("", 1, 0)] + [TestCase("", 0, 1)] + [TestCase("value", -1, 0)] + [TestCase("value", 6, 0)] + [TestCase("value", 0, 6)] + [TestCase("value", 5, 1)] + [TestCase("value", 4, 2)] + public void Slice_InvalidRange_ShouldThrow(string value, int index, int length) + { + Assert.That( + () => new StringView(value).Slice(index, length), + Throws.TypeOf()); + } + + [TestCase("value", "value", 0, 5)] + [TestCase("key=value", "value", 4, 5)] + [TestCase("key=value", "key", 0, 3)] + [TestCase("key=value", "=", 3, 1)] + [TestCase("key=value", ">", 3, 1)] + [TestCase("value", "final", 0, 5)] + [TestCase("key=value", "final", 0, 5)] + [TestCase("key=value", "source", 0, 5)] + [TestCase(null, null, 0, 0)] + [TestCase(null, "", 0, 0)] + [TestCase("", null, 0, 0)] + [TestCase("", "", 0, 0)] + public void Equals(string? value, string? other, int index, int length) + { + var view1 = value.AsView(index, length); + var view2 = other.AsView(); + + var span1 = value.AsSpan(index, length); + var span2 = other.AsSpan(); + + Assert.That(view1.Equals(other), Is.EqualTo(span1.SequenceEqual(span2))); + + // ReSharper disable once SuspiciousTypeConversion.Global + Assert.That(view1.Equals((object?)other), Is.EqualTo(span1.SequenceEqual(span2))); + Assert.That(view1.Equals((object?)other.AsView()), Is.EqualTo(span1.SequenceEqual(span2))); + + Assert.That(StringView.Equals(view1, other), Is.EqualTo(span1.SequenceEqual(span2))); + Assert.That(StringView.Equals(view1, view2), Is.EqualTo(span1.SequenceEqual(span2))); + } + + [TestCase("value", "VALUE", 0, 5)] + [TestCase("key=value", "VALUE", 4, 5)] + [TestCase("key=value", "Key", 0, 3)] + [TestCase("key=value", "=", 3, 1)] + [TestCase("key=value", ">", 3, 1)] + [TestCase("value", "final", 0, 5)] + [TestCase("key=value", "final", 0, 5)] + [TestCase("key=value", "source", 0, 5)] + [TestCase(null, null, 0, 0)] + [TestCase(null, "", 0, 0)] + [TestCase("", null, 0, 0)] + [TestCase("", "", 0, 0)] + public void Equals_StringComparison(string? value, string? other, int index, int length) + { + var view1 = value.AsView(index, length); + var view2 = other.AsView(); + + var span1 = value.AsSpan(index, length); + var span2 = other.AsSpan(); + + Assert.That( + view1.Equals(other, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(span1.Equals(span2, StringComparison.OrdinalIgnoreCase))); + + Assert.That( + view1.Equals(view2, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(span1.Equals(span2, StringComparison.OrdinalIgnoreCase))); + + Assert.That( + StringView.Equals(view1, other, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(span1.Equals(span2, StringComparison.OrdinalIgnoreCase))); + + Assert.That( + StringView.Equals(view1, view2, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(span1.Equals(span2, StringComparison.OrdinalIgnoreCase))); + } + + [TestCase("")] + [TestCase("value")] + [TestCase(null)] + public void GetHashCode(string? value) + { + Assert.That( + value.AsView().GetHashCode(), + Is.EqualTo(string.GetHashCode(value.AsSpan()))); + + Assert.That( + (value?.ToUpperInvariant()).AsView().GetHashCode(StringComparison.OrdinalIgnoreCase), + Is.EqualTo(string.GetHashCode(value.AsSpan(), StringComparison.OrdinalIgnoreCase))); + } + + [TestCase("Abcd", "Abcd")] + [TestCase("abcd", "abcd")] + [TestCase("1234", "2345")] + [TestCase("2345", "1234")] + [TestCase("", "1234")] + [TestCase("1234", "")] + [TestCase("", null)] + [TestCase(null, "")] + [TestCase("ABCD", "abcd")] + [TestCase("abcde", "abc")] + [TestCase("abc", "abcde")] + public void Compare(string? value, string? other) + { + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + + var view1 = value.AsView(); + var view2 = other.AsView(); + + var span1 = value.AsSpan(); + var span2 = other.AsSpan(); + + Assert.That( + StringView.Compare(view1, other, StringComparison.CurrentCulture), + Is.EqualTo(span1.CompareTo(span2, StringComparison.CurrentCulture))); + + Assert.That( + StringView.Compare(view1, view2, StringComparison.CurrentCulture), + Is.EqualTo(span1.CompareTo(span2, StringComparison.CurrentCulture))); + + Assert.That( + view1.CompareTo(view2), + Is.EqualTo(span1.CompareTo(span2, StringComparison.CurrentCulture))); + + Assert.That( + view1.CompareTo(other), + Is.EqualTo(span1.CompareTo(span2, StringComparison.CurrentCulture))); + + Assert.That( + view1.CompareTo(view2, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(span1.CompareTo(span2, StringComparison.OrdinalIgnoreCase))); + + Assert.That( + view1.CompareTo(other, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(span1.CompareTo(span2, StringComparison.OrdinalIgnoreCase))); + } + + [TestCase("Abcd", "Abcd")] + [TestCase("abcd", "abcd")] + [TestCase("1234", "2345")] + [TestCase("2345", "1234")] + [TestCase("", "1234")] + [TestCase("1234", "")] + [TestCase("", null)] + [TestCase(null, "")] + [TestCase("ABCD", "abcd")] + [TestCase("abcde", "abc")] + [TestCase("abc", "abcde")] + public void CompareOrdinal(string? value, string? other) + { + var view1 = value.AsView(); + var view2 = other.AsView(); + + var span1 = value.AsSpan(); + var span2 = other.AsSpan(); + + Assert.That(StringView.CompareOrdinal(view1, other), Is.EqualTo(span1.CompareTo(span2, StringComparison.Ordinal))); + Assert.That(StringView.CompareOrdinal(view1, view2), Is.EqualTo(span1.CompareTo(span2, StringComparison.Ordinal))); + } + + [TestCase("", 0, 0)] + [TestCase(null, 0, 0)] + [TestCase("text", 0, 4)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + [TestCase("key=value", 5, 0)] + [TestCase("key=value", 3, 0)] + public void CopyTo(string? source, int index, int length) + { + var data = new char[length]; + var view = source.AsView(index, length); + + view.CopyTo(data.AsSpan()); + + Assert.That(view, Is.EquivalentTo(data)); + } + + [TestCase("text", 0, 4)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void CopyTo_InsufficientRoom_ShouldThrow(string? source, int index, int length) + { + var data = new char[length - 1]; + var view = source.AsView(index, length); + + var e = Assert.Throws(() => view.CopyTo(data.AsSpan()))!; + Assert.That(e.Message, Is.EqualTo("Destination is too short. (Parameter 'destination')")); + } + + [TestCase("", 0, 0)] + [TestCase(null, 0, 0)] + [TestCase("text", 0, 4)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + [TestCase("key=value", 5, 0)] + public void TryCopyTo(string? source, int index, int length) + { + var data = new char[length]; + var view = source.AsView(index, length); + + Assert.That(view.TryCopyTo(data.AsSpan()), Is.True); + Assert.That(view, Is.EquivalentTo(data)); + } + + [TestCase("text", 0, 4)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void TryCopyTo_InsufficientRoom_ShouldReturnFalse(string? source, int index, int length) + { + var data = new char[length - 1]; + var view = source.AsView(index, length); + + Assert.That(view.TryCopyTo(data.AsSpan()), Is.False); + Assert.That(data, Is.EquivalentTo(new char[length - 1])); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("value")] + [TestCase("key=value")] + public void AsView(string? value) + { + Assert.That( + value.AsView().ToString(), + Is.EqualTo(value.AsSpan().ToString())); + } + + [TestCase(null, 0)] + [TestCase("", 0)] + [TestCase("value", 0)] + [TestCase("value", 5)] + [TestCase("key=value", 0)] + [TestCase("key=value", 3)] + [TestCase("key=value", 4)] + public void AsView_Index(string? value, int index) + { + Assert.That( + value.AsView(index).ToString(), + Is.EqualTo(value.AsSpan(index).ToString())); + } + + [TestCase(null, 0, 0)] + [TestCase("", 0, 0)] + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void AsView_Range(string? value, int index, int length) + { + Assert.That( + value.AsView(index, length).ToString(), + Is.EqualTo(value.AsSpan(index, length).ToString())); + } + + [TestCase(null, 1)] + [TestCase("", 1)] + [TestCase("value", -1)] + [TestCase("value", 6)] + public void AsView_InvalidIndex_ShouldThrow(string? value, int index) + { + Assert.That( + () => value.AsView(index), + Throws.TypeOf()); + } + + [TestCase(null, 1, 0)] + [TestCase("", 1, 0)] + [TestCase("", 0, 1)] + [TestCase("value", -1, 0)] + [TestCase("value", 6, 0)] + [TestCase("value", 0, 6)] + [TestCase("value", 5, 1)] + [TestCase("value", 4, 2)] + public void AsView_InvalidRange_ShouldThrow(string? value, int index, int length) + { + Assert.That( + () => value.AsView(index, length), + Throws.TypeOf()); + } + + [TestCase("Hello", 'H', true)] + [TestCase("Hello", 'h', false)] + [TestCase("", 'A', false)] + [TestCase(null, 'A', false)] + public void StartsWith_Char(string? source, char needle, bool expected) + { + Assert.That(source.AsView().StartsWith(needle), Is.EqualTo(expected)); + } + + [TestCase("Hello", "H")] + [TestCase("Hello", "h")] + [TestCase("Hello", "O")] + [TestCase("", "A")] + [TestCase(null, "A")] + [TestCase("", "")] + [TestCase(null, "")] + [TestCase(null, null)] + [TestCase("", null)] + public void StartsWith_Text(string? source, string? needle) + { + Assert.That( + source.AsView().StartsWith(needle), + Is.EqualTo(source.AsSpan().StartsWith(needle))); + + Assert.That( + source.AsView().StartsWith(needle, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(source.AsSpan().StartsWith(needle, StringComparison.OrdinalIgnoreCase))); + } + + [TestCase("Hello", 'o', true)] + [TestCase("Hello", 'h', false)] + [TestCase("", 'a', false)] + [TestCase(null, 'a', false)] + public void EndsWith_Char(string? source, char needle, bool expected) + { + Assert.That( + source.AsView().EndsWith(needle), + Is.EqualTo(expected)); + } + + [TestCase("Hello", "o")] + [TestCase("Hello", "O")] + [TestCase("Hello", "h")] + [TestCase("", "A")] + [TestCase(null, "A")] + [TestCase("", "")] + [TestCase(null, "")] + [TestCase(null, null)] + [TestCase("", null)] + public void EndsWith_Text(string? source, string? needle) + { + Assert.That( + source.AsView().EndsWith(needle), + Is.EqualTo(source.AsSpan().EndsWith(needle))); + + Assert.That( + source.AsView().EndsWith(needle, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(source.AsSpan().EndsWith(needle, StringComparison.OrdinalIgnoreCase))); + } + + [TestCase("Hello, world!", 'H')] + [TestCase("Hello, world!", 'd')] + [TestCase("Hello, world!", 'o')] + [TestCase("Hello, world!", '!')] + [TestCase("Hello, world!", ',')] + [TestCase("Hello, world!", 'A')] + [TestCase("", 'A')] + [TestCase(null, 'A')] + public void IndexOf_Char(string? source, char needle) + { + Assert.That( + source.AsView().IndexOf(needle), + Is.EqualTo(source.AsSpan().IndexOf(needle))); + } + + [TestCase("Hello, world!", "world")] + [TestCase("Hello, world!", "World")] + [TestCase("Hello, world!", "hello")] + [TestCase("Hello, world!", "Hello")] + [TestCase("Hello, world!", "w")] + [TestCase("Hello, world!", ",")] + [TestCase("Hello, world!", "?")] + [TestCase("Hello, world!", "")] + [TestCase("", "")] + [TestCase(null, "")] + public void IndexOf_Text(string? source, string needle) + { + Assert.That( + source.AsView().IndexOf(needle), + Is.EqualTo(source.AsSpan().IndexOf(needle))); + + Assert.That( + source.AsView().IndexOf(needle, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(source.AsSpan().IndexOf(needle, StringComparison.OrdinalIgnoreCase))); + } + + [TestCase("Hello, world!", 'H')] + [TestCase("Hello, world!", 'd')] + [TestCase("Hello, world!", 'o')] + [TestCase("Hello, world!", '!')] + [TestCase("Hello, world!", ',')] + [TestCase("Hello, world!", 'A')] + [TestCase("", 'A')] + [TestCase(null, 'A')] + public void LastIndexOf_Char(string? source, char needle) + { + Assert.That( + source.AsView().LastIndexOf(needle), + Is.EqualTo(source.AsSpan().LastIndexOf(needle))); + } + + [TestCase("Hello, world!", "World")] + [TestCase("Hello, world!", "hello")] + [TestCase("Hello, world!", "?")] + [TestCase("", "")] + [TestCase(null, "")] + public void LastIndexOf_Text(string? source, string needle) + { + Assert.That( + source.AsView().LastIndexOf(needle), + Is.EqualTo(source.AsSpan().LastIndexOf(needle))); + + Assert.That( + source.AsView().LastIndexOf(needle, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(source.AsSpan().LastIndexOf(needle, StringComparison.OrdinalIgnoreCase))); + } + + [TestCase("Hello, world!", 'H')] + [TestCase("Hello, world!", '!')] + [TestCase("Hello, world!", ',')] + [TestCase("Hello, world!", 'A')] + [TestCase("", 'A')] + [TestCase(null, 'A')] + public void Contains_Char(string? source, char needle) + { + Assert.That( + source.AsView().Contains(needle), + Is.EqualTo(source.AsSpan().Contains(needle))); + } + + [TestCase("Hello, world!", "world")] + [TestCase("Hello, world!", "World")] + [TestCase("Hello, world!", "w")] + [TestCase("Hello, world!", ",")] + [TestCase("Hello, world!", "?")] + [TestCase("Hello, world!", "")] + [TestCase("", "")] + [TestCase(null, "")] + public void Contains_Text(string? source, string needle) + { + Assert.That( + source.AsView().Contains(needle), + Is.EqualTo(source.AsSpan().Contains(needle, StringComparison.Ordinal))); + + Assert.That( + source.AsView().Contains(needle, StringComparison.OrdinalIgnoreCase), + Is.EqualTo(source.AsSpan().Contains(needle, StringComparison.OrdinalIgnoreCase))); + } + + [TestCase(null, 0, 0)] + [TestCase("", 0, 0)] + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void Length(string? value, int index, int length) + { + Assert.That( + value.AsView(index, length).Length, + Is.EqualTo(length)); + } + + [TestCase(null, 0, 0)] + [TestCase("", 0, 0)] + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void ToString(string? value, int index, int length) + { + Assert.That( + value.AsView(index, length).ToString(), + Is.EqualTo(value.AsSpan(index, length).ToString())); + } + + [TestCase(null, 0, 0)] + [TestCase("", 0, 0)] + [TestCase("value", 0, 0)] + [TestCase("value", 5, 0)] + [TestCase("value", 0, 5)] + [TestCase("key=value", 0, 3)] + [TestCase("key=value", 3, 1)] + [TestCase("key=value", 4, 5)] + public void ToArray(string? value, int index, int length) + { + Assert.That( + value.AsView(index, length).ToArray(), + Is.EquivalentTo(value.AsSpan(index, length).ToArray())); + } + + [TestCase("", 0, 0)] + [TestCase(null, 0, 0)] + [TestCase("id;name;lastname", 3, 0)] + [TestCase("id;name;lastname", 3, 4)] + [TestCase("id;name;lastname", 0, 2)] + [TestCase("id;name;lastname", 8, 8)] + public void GetPinnableReference(string? value, int index, int length) + { + var view = value.AsView(index, length); + var span = value.AsSpan(index, length); + + Assert.That( + Unsafe.AreSame( + ref Unsafe.AsRef(in view.GetPinnableReference()), + ref Unsafe.AsRef(in span.GetPinnableReference())), + Is.True); + } + + [Test] + public void GetPinnableReference_Default() + { + var view = default(StringView); + view.GetPinnableReference(); + } + + [TestCase("value", "value", 0, 5, true)] + [TestCase("key=value", "value", 4, 5, true)] + [TestCase("key=value", "key", 0, 3, true)] + [TestCase("key=value", "=", 3, 1, true)] + [TestCase("key=value", ">", 3, 1, false)] + [TestCase("value", "final", 0, 5, false)] + [TestCase("key=value", "final", 0, 5, false)] + [TestCase("key=value", "source", 0, 5, false)] + [TestCase("key=value", "", 0, 0, true)] + [TestCase("key=value", null, 0, 0, true)] + [TestCase(null, null, 0, 0, true)] + [TestCase(null, "", 0, 0, true)] + [TestCase("", null, 0, 0, true)] + [TestCase("", "", 0, 0, true)] + public void Operator_Equals(string? source, string? value, int index, int length, bool expected) + { + Assert.That(source.AsView(index, length) == value, Is.EqualTo(expected)); + Assert.That(source.AsView(index, length) == value.AsView(), Is.EqualTo(expected)); + } + + [TestCase("value", "key", true)] + [TestCase("key", "value", true)] + [TestCase("key", "Key", true)] + [TestCase("key", "key", false)] + [TestCase("key", "", true)] + [TestCase("key", null, true)] + [TestCase("", "key", true)] + [TestCase(null, "key", true)] + public void Operator_NotEquals(string? source, string? value, bool expected) + { + Assert.That(source.AsView() != value, Is.EqualTo(expected)); + Assert.That(source.AsView() != value.AsView(), Is.EqualTo(expected)); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("test")] + public void Operator_Conversions(string? value) + { + StringView view = value; + ReadOnlyMemory memory = view; + ReadOnlySpan span = view; + + Assert.That( + span.ToString() == value.AsSpan().ToString(), + Is.True); + + Assert.That( + memory.ToString() == value.AsMemory().ToString(), + Is.True); + + for (var i = 0; i < view.Length; i++) + { + Assert.That(view[i], Is.EqualTo(span[i])); + Assert.That(view[i], Is.EqualTo(memory.Span[i])); + } + + var j = 0; + foreach (var c in view) + { + Assert.That(c, Is.EqualTo(span[j])); + Assert.That(c, Is.EqualTo(memory.Span[j])); + j++; + } + } +} diff --git a/Ramstack.Structures/Collections/ArrayView.cs b/Ramstack.Structures/Collections/ArrayView.cs index 86b42bb..a8d1913 100644 --- a/Ramstack.Structures/Collections/ArrayView.cs +++ b/Ramstack.Structures/Collections/ArrayView.cs @@ -1,36 +1,36 @@ -namespace Ramstack.Collections; - -/// -/// Provides methods for creating array views. -/// -public static class ArrayView -{ - /// - /// Creates an array view for the specified array. - /// - /// The type of items stored in the array. - /// The array of items for which an array view will be created. - /// - /// An array view for the specified array. - /// - public static ArrayView Create(params T[] items) => - new(items); - - /// - /// Creates an array view for the specified read-only span. - /// - /// - /// This method allocates an array to convert the span into an array. - /// It is used by the C# compiler to create an - /// from the collection expression introduced in C#12. - /// - /// The type of items stored in the span. - /// The array of items for which an array view will be created. - /// - /// An instance for the specified read-only span. - /// - public static ArrayView Create(params ReadOnlySpan items) => - items.Length != 0 - ? new ArrayView(items.ToArray()) - : ArrayView.Empty; -} +namespace Ramstack.Collections; + +/// +/// Provides methods for creating array views. +/// +public static class ArrayView +{ + /// + /// Creates an array view for the specified array. + /// + /// The type of items stored in the array. + /// The array of items for which an array view will be created. + /// + /// An array view for the specified array. + /// + public static ArrayView Create(params T[] items) => + new(items); + + /// + /// Creates an array view for the specified read-only span. + /// + /// + /// This method allocates an array to convert the span into an array. + /// It is used by the C# compiler to create an + /// from the collection expression introduced in C#12. + /// + /// The type of items stored in the span. + /// The array of items for which an array view will be created. + /// + /// An instance for the specified read-only span. + /// + public static ArrayView Create(params ReadOnlySpan items) => + items.Length != 0 + ? new ArrayView(items.ToArray()) + : ArrayView.Empty; +} diff --git a/Ramstack.Structures/Collections/ArrayViewDebugView.cs b/Ramstack.Structures/Collections/ArrayViewDebugView.cs index a85533b..f09004f 100644 --- a/Ramstack.Structures/Collections/ArrayViewDebugView.cs +++ b/Ramstack.Structures/Collections/ArrayViewDebugView.cs @@ -1,14 +1,14 @@ -namespace Ramstack.Collections; - -/// -/// Represents a debugger view for the structure, allowing inspection of its contents. -/// -/// The type of items in the . -internal sealed class ArrayViewDebugView(ArrayView view) -{ - /// - /// Gets the array of items contained in the for debugging purposes. - /// - [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public T[] Items => view.ToArray(); -} +namespace Ramstack.Collections; + +/// +/// Represents a debugger view for the structure, allowing inspection of its contents. +/// +/// The type of items in the . +internal sealed class ArrayViewDebugView(ArrayView view) +{ + /// + /// Gets the array of items contained in the for debugging purposes. + /// + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public T[] Items => view.ToArray(); +} diff --git a/Ramstack.Structures/Collections/ArrayViewExtensions.cs b/Ramstack.Structures/Collections/ArrayViewExtensions.cs index 0cf30c3..5d15f80 100644 --- a/Ramstack.Structures/Collections/ArrayViewExtensions.cs +++ b/Ramstack.Structures/Collections/ArrayViewExtensions.cs @@ -1,167 +1,167 @@ -namespace Ramstack.Collections; - -/// -/// Provides extension methods for the structure. -/// -public static class ArrayViewExtensions -{ - /// - /// Creates a new over an array. - /// - /// The type of elements in the array. - /// The target array. - /// - /// An representing the specified array. - /// - public static ArrayView AsView(this T[]? value) => - new(value ?? []); - - /// - /// Creates a new over a portion of the specified array, - /// starting at a specified position to the end of the array. - /// - /// The type of elements in the array. - /// The array to create a view over. - /// The zero-based starting position of the view in the array. - /// - /// An representing the specified portion of the array. - /// - public static ArrayView AsView(this T[]? value, int index) => - new(value ?? [], index); - - /// - /// Creates a new over a portion of the specified array - /// starting at a specified position for a specified number of elements. - /// - /// The type of elements in the array. - /// The array to create a view over. - /// The zero-based starting position of the view in the array. - /// The number of elements to include in the view. - /// - /// An representing the specified portion of the array. - /// - public static ArrayView AsView(this T[]? value, int index, int count) => - new(value ?? [], index, count); - - /// - /// Finds the index of the first occurrence of a specified value in this instance. - /// - /// The instance. - /// The value to locate in the array view. - /// - /// The zero-based index of the first occurrence of the value in this instance; otherwise, -1. - /// - public static int IndexOf(this ArrayView view, T value) where T : IEquatable => - view.AsSpan().IndexOf(value); - - /// - /// Finds the index of the first occurrence of a specified value in the array view. - /// - /// The instance. - /// The value to locate in the array view. - /// The equality comparer to use for the search. - /// If , the default equality comparer is used. - /// - /// The zero-based index of the first occurrence of the value in the array view; otherwise, -1. - /// - public static int IndexOf(this ArrayView view, T value, IEqualityComparer? comparer) - { - return Impl(view.AsSpan(), value, comparer); - - static int Impl(ReadOnlySpan span, T value, IEqualityComparer? comparer) - { - if (typeof(T).IsValueType && (comparer is null || ReferenceEquals(comparer, EqualityComparer.Default))) - { - for (var i = 0; i < span.Length; i++) - if (EqualityComparer.Default.Equals(span[i], value)) - return i; - } - else - { - comparer ??= EqualityComparer.Default; - - for (var i = 0; i < span.Length; i++) - if (comparer.Equals(span[i], value)) - return i; - } - - return -1; - } - } - - /// - /// Finds the index of the last occurrence of a specified value in the array view. - /// - /// The instance. - /// The value to locate in the array view. - /// - /// The zero-based index of the last occurrence of the value in the array view; otherwise, -1. - /// - public static int LastIndexOf(this ArrayView view, T value) where T : IEquatable => - view.AsSpan().LastIndexOf(value); - - /// - /// Finds the index of the last occurrence of a specified value in the array view. - /// - /// The instance. - /// The value to locate in the array view. - /// The equality comparer to use for the search. - /// If , the default equality comparer is used. - /// - /// The zero-based index of the last occurrence of the value in the array view; otherwise, -1. - /// - public static int LastIndexOf(this ArrayView view, T value, IEqualityComparer? comparer) - { - return Impl(view.AsSpan(), value, comparer); - - static int Impl(ReadOnlySpan span, T value, IEqualityComparer? comparer) - { - if (typeof(T).IsValueType && (comparer is null || ReferenceEquals(comparer, EqualityComparer.Default))) - { - for (var i = span.Length - 1; i >= 0; i--) - if (EqualityComparer.Default.Equals(span[i], value)) - return i; - } - else - { - comparer ??= EqualityComparer.Default; - for (var i = span.Length - 1; i >= 0; i--) - if (comparer.Equals(span[i], value)) - return i; - } - - return -1; - } - } - - #if NET9_0_OR_GREATER - - /// - /// Returns an over the specified list. - /// Items should not be added or removed from the - /// while the is in use. - /// - /// The type of the elements in the list. - /// The list to get the data view over. - /// - /// A instance over the specified list. - /// - public static ArrayView AsView(this List? list) - { - if (list is not null) - { - var array = ListAccessor.GetArray(list); - _ = array.Length; - - // - // SCG.List maintains internal invariants, so we can safely use the unchecked constructor - // to bypass redundant bounds checks for better performance. - // - return new ArrayView(array, 0, list.Count, unused: 0); - } - - return ArrayView.Empty; - } - - #endif -} +namespace Ramstack.Collections; + +/// +/// Provides extension methods for the structure. +/// +public static class ArrayViewExtensions +{ + /// + /// Creates a new over an array. + /// + /// The type of elements in the array. + /// The target array. + /// + /// An representing the specified array. + /// + public static ArrayView AsView(this T[]? value) => + new(value ?? []); + + /// + /// Creates a new over a portion of the specified array, + /// starting at a specified position to the end of the array. + /// + /// The type of elements in the array. + /// The array to create a view over. + /// The zero-based starting position of the view in the array. + /// + /// An representing the specified portion of the array. + /// + public static ArrayView AsView(this T[]? value, int index) => + new(value ?? [], index); + + /// + /// Creates a new over a portion of the specified array + /// starting at a specified position for a specified number of elements. + /// + /// The type of elements in the array. + /// The array to create a view over. + /// The zero-based starting position of the view in the array. + /// The number of elements to include in the view. + /// + /// An representing the specified portion of the array. + /// + public static ArrayView AsView(this T[]? value, int index, int count) => + new(value ?? [], index, count); + + /// + /// Finds the index of the first occurrence of a specified value in this instance. + /// + /// The instance. + /// The value to locate in the array view. + /// + /// The zero-based index of the first occurrence of the value in this instance; otherwise, -1. + /// + public static int IndexOf(this ArrayView view, T value) where T : IEquatable => + view.AsSpan().IndexOf(value); + + /// + /// Finds the index of the first occurrence of a specified value in the array view. + /// + /// The instance. + /// The value to locate in the array view. + /// The equality comparer to use for the search. + /// If , the default equality comparer is used. + /// + /// The zero-based index of the first occurrence of the value in the array view; otherwise, -1. + /// + public static int IndexOf(this ArrayView view, T value, IEqualityComparer? comparer) + { + return Impl(view.AsSpan(), value, comparer); + + static int Impl(ReadOnlySpan span, T value, IEqualityComparer? comparer) + { + if (typeof(T).IsValueType && (comparer is null || ReferenceEquals(comparer, EqualityComparer.Default))) + { + for (var i = 0; i < span.Length; i++) + if (EqualityComparer.Default.Equals(span[i], value)) + return i; + } + else + { + comparer ??= EqualityComparer.Default; + + for (var i = 0; i < span.Length; i++) + if (comparer.Equals(span[i], value)) + return i; + } + + return -1; + } + } + + /// + /// Finds the index of the last occurrence of a specified value in the array view. + /// + /// The instance. + /// The value to locate in the array view. + /// + /// The zero-based index of the last occurrence of the value in the array view; otherwise, -1. + /// + public static int LastIndexOf(this ArrayView view, T value) where T : IEquatable => + view.AsSpan().LastIndexOf(value); + + /// + /// Finds the index of the last occurrence of a specified value in the array view. + /// + /// The instance. + /// The value to locate in the array view. + /// The equality comparer to use for the search. + /// If , the default equality comparer is used. + /// + /// The zero-based index of the last occurrence of the value in the array view; otherwise, -1. + /// + public static int LastIndexOf(this ArrayView view, T value, IEqualityComparer? comparer) + { + return Impl(view.AsSpan(), value, comparer); + + static int Impl(ReadOnlySpan span, T value, IEqualityComparer? comparer) + { + if (typeof(T).IsValueType && (comparer is null || ReferenceEquals(comparer, EqualityComparer.Default))) + { + for (var i = span.Length - 1; i >= 0; i--) + if (EqualityComparer.Default.Equals(span[i], value)) + return i; + } + else + { + comparer ??= EqualityComparer.Default; + for (var i = span.Length - 1; i >= 0; i--) + if (comparer.Equals(span[i], value)) + return i; + } + + return -1; + } + } + + #if NET9_0_OR_GREATER + + /// + /// Returns an over the specified list. + /// Items should not be added or removed from the + /// while the is in use. + /// + /// The type of the elements in the list. + /// The list to get the data view over. + /// + /// A instance over the specified list. + /// + public static ArrayView AsView(this List? list) + { + if (list is not null) + { + var array = ListAccessor.GetArray(list); + _ = array.Length; + + // + // SCG.List maintains internal invariants, so we can safely use the unchecked constructor + // to bypass redundant bounds checks for better performance. + // + return new ArrayView(array, 0, list.Count, unused: 0); + } + + return ArrayView.Empty; + } + + #endif +} diff --git a/Ramstack.Structures/Collections/ArrayView`1.cs b/Ramstack.Structures/Collections/ArrayView`1.cs index f74a60f..17a6b50 100644 --- a/Ramstack.Structures/Collections/ArrayView`1.cs +++ b/Ramstack.Structures/Collections/ArrayView`1.cs @@ -1,447 +1,449 @@ -namespace Ramstack.Collections; - -/// -/// Represents a read-only view of an array, providing safe and efficient access to a subset of its elements. -/// -/// The type of the elements in the array view. -[DebuggerDisplay("{ToStringDebugger(),nq}")] -[DebuggerTypeProxy(typeof(ArrayViewDebugView<>))] -[CollectionBuilder(typeof(ArrayView), nameof(ArrayView.Create))] -public readonly struct ArrayView : IReadOnlyList -{ - private readonly T[]? _array; - private readonly int _index; - private readonly int _count; - - /// - /// Gets the empty array view. - /// - public static ArrayView Empty => default; - - /// - /// Gets the number of elements in the current object. - /// - public int Length => _count; - - /// - /// Gets a value indicating whether the was declared but not initialized. - /// - public bool IsDefault => _array is null; - - /// - public ref readonly T this[int index] - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - if ((uint)index >= (uint)_count) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - return ref _array!.GetRawArrayData(_index + index); - } - } - - /// - /// Initializes a new instance of the structure that creates a view - /// for the all elements in the specified array. - /// - /// The array to wrap. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ArrayView(T[] array) - { - _index = 0; - _count = array.Length; - _array = array; - } - - /// - /// Initializes a new instance of the structure that creates - /// a view for the specified range of the elements in the specified array. - /// - /// The array to wrap. - /// The zero-based starting position of the view in the array. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ArrayView(T[] array, int index) - { - if ((uint)index > (uint)array.Length) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - _index = index; - _count = array.Length - index; - _array = array; - } - - /// - /// Initializes a new instance of the structure that creates - /// a view for the specified range of the elements in the specified array. - /// - /// The array to wrap. - /// The zero-based starting position of the view in the array. - /// The number of characters to include in the view. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ArrayView(T[] array, int index, int length) - { - // - // https://github.com/dotnet/runtime/issues/119689 - // - if ((uint)index > (uint)array.Length || (uint)length > (uint)(array.Length - index)) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - _index = index; - _count = length; - _array = array; - } - - /// - /// Initializes a new instance of the structure that creates - /// a view for the specified range of the elements in the specified array. - /// - /// - /// This constructor is intentionally minimal and skips all argument validations, - /// as the caller is responsible for ensuring correctness (e.g., - /// is non-null, and - /// are within bounds). - /// - /// The array to wrap. - /// The zero-based starting position of the view in the array. - /// The number of characters to include in the view. - /// Unused parameter used only to differentiate between overloads. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ArrayView(T[] array, int index, int length, int unused) - { - _index = index; - _count = length; - _array = array; - _ = unused; - } - - /// - public Enumerator GetEnumerator() => - new(this); - - /// - /// Forms a slice out of the current array view starting at the specified index. - /// - /// The index at which to begin the slice. - /// - /// An array view that consists of all elements of the current array view - /// from to the end of the array view. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ArrayView Slice(int index) - { - if ((uint)index > (uint)_count) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - return new ArrayView(_array!, _index + index, _count - index, unused: 0); - } - - /// - /// Forms a slice of the specified length out of the current array view starting at the specified index. - /// - /// The index at which to begin the slice. - /// The length of the slice. - /// - /// An array view of elements starting at . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ArrayView Slice(int index, int count) - { - if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index)) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - return new ArrayView(_array!, _index + index, count, unused: 0); - } - - /// - /// Copies the contents of this array view into a new array. - /// - /// - /// An array containing the data in the current array view. - /// - public T[] ToArray() => - ((ReadOnlySpan)this).ToArray(); - - /// - /// Returns a read-only span over the current array view. - /// - /// - /// The read-only span representation of the array view. - /// - public ReadOnlySpan AsSpan() => - this; - - /// - /// Returns a read-only a memory region over the current array view. - /// - /// - /// The memory representation of the read-only array. - /// - public ReadOnlyMemory AsMemory() => - this; - - /// - /// Returns a reference to the element of the at index zero. - /// - /// - /// A reference to the element of the at index zero. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ref readonly T GetPinnableReference() - { - // - // Normalize the returned reference. - // We must not return a reference to an element outside the bounds of our view - // when the view is empty (_count = 0), even if it points to a valid element - // in the underlying array. In this case, we return a null reference. - // - // Examples: - // - // Full array (_array): - // [0][1][2][3][4][5][6][7][8][9] - // |--------------------------| - // - // Case 1: Non-empty view (_index = 3, _count = 4) - // [3][4][5][6] - // ^ ^ - // |--------| <- valid range for this view - // - // Case 2: Empty view (_index = 3, _count = 0) - // [3][4][5][6] - // ^ - // | <- no valid reference for this view - // - - ref var p = ref Unsafe.NullRef(); - - if (_count != 0) - p = ref _array!.GetRawArrayData(_index)!; - - return ref p!; - } - - /// - /// Copies the contents of this into a destination . - /// - /// The span to copy items into. - public void CopyTo(Span destination) => - AsSpan().CopyTo(destination); - - /// - /// Attempts to copy the contents of this - /// into a destination and returns a value to indicate - /// whether the operation succeeded. - /// - /// The span to copy items into. - /// - /// if the copy operation succeeded; otherwise, . - /// - public bool TryCopyTo(Span destination) => - AsSpan().TryCopyTo(destination); - - /// - /// Defines an implicit conversion of an array of type to . - /// - /// The array to convert. - /// - /// An array view representation of the array. - /// - public static implicit operator ArrayView(T[]? array) => - new(array ?? []); - - /// - /// Defines an implicit conversion of a read-only array of type to an array view. - /// - /// The array to convert. - /// - /// An array view representation of the read-only array. - /// - public static implicit operator ArrayView(ReadOnlyArray array) => - array.AsView(); - - /// - /// Defines an implicit conversion of a read-only array of type to an array view. - /// - /// The array to convert. - /// - /// An array view representation of the read-only array. - /// - public static implicit operator ArrayView(ImmutableArray array) - { - #if NET8_0_OR_GREATER - return ImmutableCollectionsMarshal.AsArray(array); - #else - return Unsafe.As, ReadOnlyArray>(ref array).AsView(); - #endif - } - - /// - /// Defines an implicit conversion of an array view to the . - /// - /// The array view to convert. - /// - /// A representation of the array view. - /// - public static implicit operator ReadOnlyMemory(ArrayView view) => - new(view._array ?? [], view._index, view._count); - - /// - /// Defines an implicit conversion of an array view to the . - /// - /// The array view to convert. - /// - /// A representation of the array view. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator ReadOnlySpan(ArrayView view) - { - var array = view._array ?? []; - return MemoryMarshal.CreateReadOnlySpan( - ref array.GetRawArrayData(view._index), - length: view._count); - } - - /// - /// Defines an implicit conversion of an array segment to the . - /// - /// The array segment to convert. - /// - /// A representation of the array segment. - /// - public static implicit operator ArrayView(ArraySegment segment) => - new(segment.Array!, segment.Offset, segment.Count, unused: 0); - - /// - /// Returns a string representation of the current instance's state, - /// intended for debugging purposes. - /// - /// - /// A string containing information about the current instance. - /// - private string ToStringDebugger() => - _array is null ? "Uninitialized" : $"Length = {_count}"; - - #region IEnumerable implementation - - IEnumerator IEnumerable.GetEnumerator() => - new ArrayViewEnumerator(this); - - IEnumerator IEnumerable.GetEnumerator() => - new ArrayViewEnumerator(this); - - #endregion - - #region IReadOnlyCollection implementation - - int IReadOnlyCollection.Count => _count; - - #endregion - - #region IReadOnlyList implementation - - T IReadOnlyList.this[int index] => this[index]; - - #endregion - - #region Inner type: Enumerator - - /// - /// Provides the ability to iterate through the elements of the . - /// - public struct Enumerator - { - private readonly T[]? _array; - private int _index; - private readonly int _final; - - /// - public readonly ref readonly T Current - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - if ((uint)_index >= (uint)_final) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - return ref _array!.GetRawArrayData(_index); - } - } - - /// - /// Initializes a new instance of the structure. - /// - /// The to iterate through its elements. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal Enumerator(ArrayView view) - { - _index = view._index - 1; - _final = view._index + view._count; - _array = view._array; - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool MoveNext() - { - ++_index; - return (uint)_final > (uint)_index; - } - } - - #endregion - - #region Inner type: ArrayViewEnumerator - - /// - /// Provides the ability to iterate through the elements of the . - /// - private sealed class ArrayViewEnumerator : IEnumerator - { - private readonly T[]? _array; - private int _index; - private readonly int _final; - - /// - public T Current - { - get - { - if ((uint)_index >= (uint)_final) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - return _array!.GetRawArrayData(_index); - } - } - - /// - /// Initializes a new instance of the class. - /// - /// The to iterate through its elements. - public ArrayViewEnumerator(ArrayView view) - { - _index = view._index - 1; - _final = view._index + view._count; - _array = view._array; - } - - /// - public bool MoveNext() - { - ++_index; - return (uint)_index < (uint)_final; - } - - /// - public void Dispose() - { } - - /// - object? IEnumerator.Current => Current; - - /// - void IEnumerator.Reset() => - ThrowHelper.ThrowNotSupportedException(); - } - - #endregion -} +namespace Ramstack.Collections; + +/// +/// Represents a read-only view of an array, providing safe and efficient access to a subset of its elements. +/// +/// The type of the elements in the array view. +[DebuggerDisplay("{ToStringDebugger(),nq}")] +[DebuggerTypeProxy(typeof(ArrayViewDebugView<>))] +[CollectionBuilder(typeof(ArrayView), nameof(ArrayView.Create))] +public readonly struct ArrayView : IReadOnlyList +{ + private readonly T[]? _array; + private readonly int _index; + private readonly int _count; + + /// + /// Gets the empty array view. + /// + [SuppressMessage("Design", "CA1000:Do not declare static members on generic types", + Justification = "Like ImmutableArray.Empty, the empty instance belongs to the generic type, and removing it would break the public API.")] + public static ArrayView Empty => default; + + /// + /// Gets the number of elements in the current object. + /// + public int Length => _count; + + /// + /// Gets a value indicating whether the was declared but not initialized. + /// + public bool IsDefault => _array is null; + + /// + public ref readonly T this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)index >= (uint)_count) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return ref _array!.GetRawArrayData(_index + index); + } + } + + /// + /// Initializes a new instance of the structure that creates a view + /// for the all elements in the specified array. + /// + /// The array to wrap. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ArrayView(T[] array) + { + _index = 0; + _count = array.Length; + _array = array; + } + + /// + /// Initializes a new instance of the structure that creates + /// a view for the specified range of the elements in the specified array. + /// + /// The array to wrap. + /// The zero-based starting position of the view in the array. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ArrayView(T[] array, int index) + { + if ((uint)index > (uint)array.Length) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + _index = index; + _count = array.Length - index; + _array = array; + } + + /// + /// Initializes a new instance of the structure that creates + /// a view for the specified range of the elements in the specified array. + /// + /// The array to wrap. + /// The zero-based starting position of the view in the array. + /// The number of characters to include in the view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ArrayView(T[] array, int index, int length) + { + // + // https://github.com/dotnet/runtime/issues/119689 + // + if ((uint)index > (uint)array.Length || (uint)length > (uint)(array.Length - index)) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + _index = index; + _count = length; + _array = array; + } + + /// + /// Initializes a new instance of the structure that creates + /// a view for the specified range of the elements in the specified array. + /// + /// + /// This constructor is intentionally minimal and skips all argument validations, + /// as the caller is responsible for ensuring correctness (e.g., + /// is non-null, and + /// are within bounds). + /// + /// The array to wrap. + /// The zero-based starting position of the view in the array. + /// The number of characters to include in the view. + /// Unused parameter used only to differentiate between overloads. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ArrayView(T[] array, int index, int length, int unused) + { + _index = index; + _count = length; + _array = array; + _ = unused; + } + + /// + public Enumerator GetEnumerator() => + new(this); + + /// + /// Forms a slice out of the current array view starting at the specified index. + /// + /// The index at which to begin the slice. + /// + /// An array view that consists of all elements of the current array view + /// from to the end of the array view. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ArrayView Slice(int index) + { + if ((uint)index > (uint)_count) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return new ArrayView(_array!, _index + index, _count - index, unused: 0); + } + + /// + /// Forms a slice of the specified length out of the current array view starting at the specified index. + /// + /// The index at which to begin the slice. + /// The length of the slice. + /// + /// An array view of elements starting at . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ArrayView Slice(int index, int count) + { + if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index)) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return new ArrayView(_array!, _index + index, count, unused: 0); + } + + /// + /// Copies the contents of this array view into a new array. + /// + /// + /// An array containing the data in the current array view. + /// + public T[] ToArray() => + ((ReadOnlySpan)this).ToArray(); + + /// + /// Returns a read-only span over the current array view. + /// + /// + /// The read-only span representation of the array view. + /// + public ReadOnlySpan AsSpan() => + this; + + /// + /// Returns a read-only a memory region over the current array view. + /// + /// + /// The memory representation of the read-only array. + /// + public ReadOnlyMemory AsMemory() => + this; + + /// + /// Returns a reference to the element of the at index zero. + /// + /// + /// A reference to the element of the at index zero. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ref readonly T GetPinnableReference() + { + // + // Normalize the returned reference. + // We must not return a reference to an element outside the bounds of our view + // when the view is empty (_count = 0), even if it points to a valid element + // in the underlying array. In this case, we return a null reference. + // + // Examples: + // + // Full array (_array): + // [0][1][2][3][4][5][6][7][8][9] + // |--------------------------| + // + // Case 1: Non-empty view (_index = 3, _count = 4) + // [3][4][5][6] + // ^ ^ + // |--------| <- valid range for this view + // + // Case 2: Empty view (_index = 3, _count = 0) + // [3][4][5][6] + // ^ + // | <- no valid reference for this view + // + + ref var p = ref Unsafe.NullRef(); + + if (_count != 0) + p = ref _array!.GetRawArrayData(_index)!; + + return ref p!; + } + + /// + /// Copies the contents of this into a destination . + /// + /// The span to copy items into. + public void CopyTo(Span destination) => + AsSpan().CopyTo(destination); + + /// + /// Attempts to copy the contents of this + /// into a destination and returns a value to indicate + /// whether the operation succeeded. + /// + /// The span to copy items into. + /// + /// if the copy operation succeeded; otherwise, . + /// + public bool TryCopyTo(Span destination) => + AsSpan().TryCopyTo(destination); + + /// + /// Defines an implicit conversion of an array of type to . + /// + /// The array to convert. + /// + /// An array view representation of the array. + /// + public static implicit operator ArrayView(T[]? array) => + new(array ?? []); + + /// + /// Defines an implicit conversion of a read-only array of type to an array view. + /// + /// The array to convert. + /// + /// An array view representation of the read-only array. + /// + public static implicit operator ArrayView(ReadOnlyArray array) => + array.AsView(); + + /// + /// Defines an implicit conversion of a read-only array of type to an array view. + /// + /// The array to convert. + /// + /// An array view representation of the read-only array. + /// + public static implicit operator ArrayView(ImmutableArray array) + { + #if NET8_0_OR_GREATER + return ImmutableCollectionsMarshal.AsArray(array); + #else + return Unsafe.As, ReadOnlyArray>(ref array).AsView(); + #endif + } + + /// + /// Defines an implicit conversion of an array view to the . + /// + /// The array view to convert. + /// + /// A representation of the array view. + /// + public static implicit operator ReadOnlyMemory(ArrayView view) => + new(view._array ?? [], view._index, view._count); + + /// + /// Defines an implicit conversion of an array view to the . + /// + /// The array view to convert. + /// + /// A representation of the array view. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlySpan(ArrayView view) + { + var array = view._array ?? []; + return MemoryMarshal.CreateReadOnlySpan( + ref array.GetRawArrayData(view._index), + length: view._count); + } + + /// + /// Defines an implicit conversion of an array segment to the . + /// + /// The array segment to convert. + /// + /// A representation of the array segment. + /// + public static implicit operator ArrayView(ArraySegment segment) => + new(segment.Array!, segment.Offset, segment.Count, unused: 0); + + /// + /// Returns a string representation of the current instance's state, + /// intended for debugging purposes. + /// + /// + /// A string containing information about the current instance. + /// + private string ToStringDebugger() => + _array is null ? "Uninitialized" : $"Length = {_count}"; + + #region IEnumerable implementation + + IEnumerator IEnumerable.GetEnumerator() => + new ArrayViewEnumerator(this); + + IEnumerator IEnumerable.GetEnumerator() => + new ArrayViewEnumerator(this); + + #endregion + + #region IReadOnlyCollection implementation + + int IReadOnlyCollection.Count => _count; + + #endregion + + #region IReadOnlyList implementation + + T IReadOnlyList.this[int index] => this[index]; + + #endregion + + #region Inner type: Enumerator + + /// + /// Provides the ability to iterate through the elements of the . + /// + public struct Enumerator + { + private readonly T[]? _array; + private int _index; + private readonly int _final; + + /// + public readonly ref readonly T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)_index >= (uint)_final) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return ref _array!.GetRawArrayData(_index); + } + } + + /// + /// Initializes a new instance of the structure. + /// + /// The to iterate through its elements. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(ArrayView view) + { + _index = view._index - 1; + _final = view._index + view._count; + _array = view._array; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + ++_index; + return (uint)_final > (uint)_index; + } + } + + #endregion + + #region Inner type: ArrayViewEnumerator + + /// + /// Provides the ability to iterate through the elements of the . + /// + private sealed class ArrayViewEnumerator : IEnumerator + { + private readonly T[]? _array; + private int _index; + private readonly int _final; + + /// + public T Current + { + get + { + if ((uint)_index >= (uint)_final) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return _array!.GetRawArrayData(_index); + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The to iterate through its elements. + public ArrayViewEnumerator(ArrayView view) + { + _index = view._index - 1; + _final = view._index + view._count; + _array = view._array; + } + + /// + public bool MoveNext() + { + ++_index; + return (uint)_index < (uint)_final; + } + + /// + public void Dispose() + { } + + /// + object? IEnumerator.Current => Current; + + /// + void IEnumerator.Reset() => + ThrowHelper.ThrowNotSupportedException(); + } + + #endregion +} diff --git a/Ramstack.Structures/Collections/ImmutableArrayExtensions.cs b/Ramstack.Structures/Collections/ImmutableArrayExtensions.cs index 8e66946..39b93e8 100644 --- a/Ramstack.Structures/Collections/ImmutableArrayExtensions.cs +++ b/Ramstack.Structures/Collections/ImmutableArrayExtensions.cs @@ -1,50 +1,50 @@ -namespace Ramstack.Collections; - -/// -/// Provides extension methods for the structure. -/// -public static class ImmutableArrayExtensions -{ - /// - /// Returns a over an immutable array. - /// - /// The immutable array. - /// - /// The read-only array over an immutable array. - /// - public static ReadOnlyArray AsReadOnlyArray(this ImmutableArray value) => - value; - - /// - /// Creates an over an immutable array. - /// - /// The immutable array to wrap. - /// - /// The read-only view of the array. - /// - public static ArrayView AsView(this ImmutableArray value) => - value.AsReadOnlyArray().AsView(); - - /// - /// Creates an over an immutable array starting at a specified position to the end of the array. - /// - /// The immutable array to wrap. - /// The index at which to begin the array view. - /// - /// The read-only view of the array. - /// - public static ArrayView AsView(this ImmutableArray value, int index) => - value.AsReadOnlyArray().AsView(index); - - /// - /// Creates an over an immutable array starting at a specified position for a specified length. - /// - /// The immutable array to wrap. - /// The index at which to begin the array view. - /// The number of items in the array view. - /// - /// The read-only view of the array. - /// - public static ArrayView AsView(this ImmutableArray value, int index, int count) => - value.AsReadOnlyArray().AsView(index, count); -} +namespace Ramstack.Collections; + +/// +/// Provides extension methods for the structure. +/// +public static class ImmutableArrayExtensions +{ + /// + /// Returns a over an immutable array. + /// + /// The immutable array. + /// + /// The read-only array over an immutable array. + /// + public static ReadOnlyArray AsReadOnlyArray(this ImmutableArray value) => + value; + + /// + /// Creates an over an immutable array. + /// + /// The immutable array to wrap. + /// + /// The read-only view of the array. + /// + public static ArrayView AsView(this ImmutableArray value) => + value.AsReadOnlyArray().AsView(); + + /// + /// Creates an over an immutable array starting at a specified position to the end of the array. + /// + /// The immutable array to wrap. + /// The index at which to begin the array view. + /// + /// The read-only view of the array. + /// + public static ArrayView AsView(this ImmutableArray value, int index) => + value.AsReadOnlyArray().AsView(index); + + /// + /// Creates an over an immutable array starting at a specified position for a specified length. + /// + /// The immutable array to wrap. + /// The index at which to begin the array view. + /// The number of items in the array view. + /// + /// The read-only view of the array. + /// + public static ArrayView AsView(this ImmutableArray value, int index, int count) => + value.AsReadOnlyArray().AsView(index, count); +} diff --git a/Ramstack.Structures/Collections/ReadOnlyArray.cs b/Ramstack.Structures/Collections/ReadOnlyArray.cs index 763614e..2dea686 100644 --- a/Ramstack.Structures/Collections/ReadOnlyArray.cs +++ b/Ramstack.Structures/Collections/ReadOnlyArray.cs @@ -1,70 +1,70 @@ -namespace Ramstack.Collections; - -/// -/// Provides methods for creating an array that is read-only. -/// -public static class ReadOnlyArray -{ - /// - /// Returns a read-only array that just wraps the . - /// - /// The type of items stored in the array. - /// The array of items to get a read-only wrapper for. - /// - /// A read-only array. - /// - public static ReadOnlyArray UnsafeWrap(params T[] array) => - new(array); - - /// - /// Creates a read-only array from the specified array of items. - /// - /// The type of items stored in the array. - /// The array of items to populate the array with. - /// - /// A read-only array that contains the array of items. - /// - public static ReadOnlyArray Create(params T[] items) - { - _ = items.Length; - return new ReadOnlyArray( - new ReadOnlySpan(items)); - } - - /// - /// Creates a read-only array with the specified items. - /// - /// - /// This method allocates an array to convert the span into an array. - /// It is used by the C# compiler to create an - /// from the collection expression introduced in C#12. - /// - /// The type of items stored in the array. - /// The items to populate the array with. - /// - /// A read-only array that contains the specified items. - /// - public static ReadOnlyArray Create(ReadOnlySpan items) => - new(items); - - /// - /// Creates a read-only array with the specified items. - /// - /// The type of items stored in the array. - /// The items to populate the array with. - /// - /// A read-only array that contains the specified items. - /// - public static ReadOnlyArray Create([InstantHandle] IEnumerable items) => - new(items.ToArray()); - - /// - /// Returns an empty read-only array. - /// - /// The type of elements stored in the array. - /// - /// An empty read-only array. - /// - public static ReadOnlyArray Empty() => - new(Array.Empty()); -} +namespace Ramstack.Collections; + +/// +/// Provides methods for creating an array that is read-only. +/// +public static class ReadOnlyArray +{ + /// + /// Returns a read-only array that just wraps the . + /// + /// The type of items stored in the array. + /// The array of items to get a read-only wrapper for. + /// + /// A read-only array. + /// + public static ReadOnlyArray UnsafeWrap(params T[] array) => + new(array); + + /// + /// Creates a read-only array from the specified array of items. + /// + /// The type of items stored in the array. + /// The array of items to populate the array with. + /// + /// A read-only array that contains the array of items. + /// + public static ReadOnlyArray Create(params T[] items) + { + _ = items.Length; + return new ReadOnlyArray( + new ReadOnlySpan(items)); + } + + /// + /// Creates a read-only array with the specified items. + /// + /// + /// This method allocates an array to convert the span into an array. + /// It is used by the C# compiler to create an + /// from the collection expression introduced in C#12. + /// + /// The type of items stored in the array. + /// The items to populate the array with. + /// + /// A read-only array that contains the specified items. + /// + public static ReadOnlyArray Create(ReadOnlySpan items) => + new(items); + + /// + /// Creates a read-only array with the specified items. + /// + /// The type of items stored in the array. + /// The items to populate the array with. + /// + /// A read-only array that contains the specified items. + /// + public static ReadOnlyArray Create([InstantHandle] IEnumerable items) => + new(items.ToArray()); + + /// + /// Returns an empty read-only array. + /// + /// The type of elements stored in the array. + /// + /// An empty read-only array. + /// + public static ReadOnlyArray Empty() => + new(Array.Empty()); +} diff --git a/Ramstack.Structures/Collections/ReadOnlyArrayExtensions.Linq.cs b/Ramstack.Structures/Collections/ReadOnlyArrayExtensions.Linq.cs index 6c46a38..c8c8a66 100644 --- a/Ramstack.Structures/Collections/ReadOnlyArrayExtensions.Linq.cs +++ b/Ramstack.Structures/Collections/ReadOnlyArrayExtensions.Linq.cs @@ -1,471 +1,475 @@ -namespace Ramstack.Collections; - -public static partial class ReadOnlyArrayExtensions -{ - /// - [LinqTunnel] - public static T Aggregate(this ReadOnlyArray source, Func func) => - source.Inner!.Aggregate(func); - - /// - [LinqTunnel] - public static TAccumulate Aggregate(this ReadOnlyArray source, TAccumulate seed, Func func) => - source.Inner!.Aggregate(seed, func); - - /// - [LinqTunnel] - public static TResult Aggregate(this ReadOnlyArray source, TAccumulate seed, Func func, Func resultSelector) => - source.Inner!.Aggregate(seed, func, resultSelector); - - /// - [LinqTunnel] - public static IEnumerable Select(this ReadOnlyArray source, Func selector) => - source.Inner!.Select(selector); - - /// - [LinqTunnel] - public static IEnumerable Select(this ReadOnlyArray source, Func selector) => - source.Inner!.Select(selector); - - /// - [LinqTunnel] - public static IEnumerable SelectMany(this ReadOnlyArray source, Func> selector) => - source.Inner!.SelectMany(selector); - - /// - [LinqTunnel] - public static IEnumerable SelectMany(this ReadOnlyArray source, Func> selector) => - source.Inner!.SelectMany(selector); - - /// - [LinqTunnel] - public static IEnumerable SelectMany(this ReadOnlyArray source, Func> collectionSelector, Func resultSelector) => - source.Inner!.SelectMany(collectionSelector, resultSelector); - - /// - [LinqTunnel] - public static IEnumerable SelectMany(this ReadOnlyArray source, Func> collectionSelector, Func resultSelector) => - source.Inner!.SelectMany(collectionSelector, resultSelector); - - /// - /// Sorts the elements of a sequence in ascending order. - /// - /// The types of elements of . - /// A sequence of values to order. - /// - /// An whose elements are sorted. - /// - [LinqTunnel] - public static IEnumerable Order(this ReadOnlyArray source) - { - #if NET6_0 - return source.Inner!.OrderBy(SortHelper.Identity); - #else - return source.Inner!.Order(); - #endif - } - - /// - /// Sorts the elements of a sequence in ascending order. - /// - /// The types of elements of . - /// A sequence of values to order. - /// An to compare keys. - /// - /// An whose elements are sorted. - /// - [LinqTunnel] - public static IEnumerable Order(this ReadOnlyArray source, IComparer? comparer) - { - #if NET6_0 - return source.Inner!.OrderBy(SortHelper.Identity, comparer); - #else - return source.Inner!.Order(comparer); - #endif - } - - /// - /// Sorts the elements of a sequence in descending order. - /// - /// The types of elements of . - /// A sequence of values to order. - /// - /// An whose elements are sorted. - /// - [LinqTunnel] - public static IEnumerable OrderDescending(this ReadOnlyArray source) - { - #if NET6_0 - return source.Inner!.OrderByDescending(SortHelper.Identity); - #else - return source.Inner!.OrderDescending(); - #endif - } - - /// - /// Sorts the elements of a sequence in descending order. - /// - /// The types of elements of . - /// A sequence of values to order. - /// An to compare keys. - /// - /// An whose elements are sorted. - /// - [LinqTunnel] - public static IEnumerable OrderDescending(this ReadOnlyArray source, IComparer? comparer) - { - #if NET6_0 - return source.Inner!.OrderByDescending(SortHelper.Identity, comparer); - #else - return source.Inner!.OrderDescending(comparer); - #endif - } - - /// - [LinqTunnel] - public static IEnumerable OrderBy(this ReadOnlyArray source, Func keySelector) => - source.Inner!.OrderBy(keySelector); - - /// - [LinqTunnel] - public static IEnumerable OrderBy(this ReadOnlyArray source, Func keySelector, IComparer? comparer) => - source.Inner!.OrderBy(keySelector, comparer); - - /// - [LinqTunnel] - public static IEnumerable OrderByDescending(this ReadOnlyArray source, Func keySelector) => - source.Inner!.OrderByDescending(keySelector); - - /// - [LinqTunnel] - public static IEnumerable OrderByDescending(this ReadOnlyArray source, Func keySelector, IComparer? comparer) => - source.Inner!.OrderByDescending(keySelector, comparer); - - /// - [LinqTunnel] - public static IEnumerable Where(this ReadOnlyArray source, Func selector) => - source.Inner!.Where(selector); - - /// - [LinqTunnel] - public static IEnumerable Where(this ReadOnlyArray source, Func selector) => - source.Inner!.Where(selector); - - /// - [LinqTunnel] - public static IEnumerable Distinct(this ReadOnlyArray source) => - source.Inner!.Distinct(); - - /// - [LinqTunnel] - public static IEnumerable Distinct(this ReadOnlyArray source, IEqualityComparer? comparer) => - source.Inner!.Distinct(comparer); - - /// - public static IEnumerable DistinctBy(this ReadOnlyArray source, Func keySelector) => - source.Inner!.DistinctBy(keySelector); - - /// - [LinqTunnel] - public static IEnumerable DistinctBy(this ReadOnlyArray source, Func keySelector, IEqualityComparer? comparer) => - source.Inner!.DistinctBy(keySelector, comparer); - - /// - public static bool Any(this ReadOnlyArray source) => - source.Inner!.Length != 0; - - /// - public static bool Any(this ReadOnlyArray source, Func predicate) - { - foreach (var item in source.Inner!) - if (predicate(item)) - return true; - - return false; - } - - /// - public static bool All(this ReadOnlyArray source, Func predicate) - { - foreach (var item in source.Inner!) - if (!predicate(item)) - return false; - - return true; - } - - /// - public static int Count(this ReadOnlyArray source) => - source.Inner!.Length; - - /// - public static int Count(this ReadOnlyArray source, Func predicate) - { - var count = 0; - - foreach (var item in source.Inner!) - if (predicate(item)) - count++; - - return count; - } - - /// - [LinqTunnel] - public static IEnumerable Take(this ReadOnlyArray source, int count) => - source.Inner!.Take(count); - - /// - [LinqTunnel] - public static IEnumerable TakeLast(this ReadOnlyArray source, int count) => - source.Inner!.TakeLast(count); - - /// - [LinqTunnel] - public static IEnumerable TakeWhile(this ReadOnlyArray source, Func predicate) => - source.Inner!.TakeWhile(predicate); - - /// - [LinqTunnel] - public static IEnumerable TakeWhile(this ReadOnlyArray source, Func predicate) => - source.Inner!.TakeWhile(predicate); - - /// - [LinqTunnel] - public static IEnumerable Skip(this ReadOnlyArray source, int count) => - source.Inner!.Skip(count); - - /// - [LinqTunnel] - public static IEnumerable SkipLast(this ReadOnlyArray source, int count) => - source.Inner!.SkipLast(count); - - /// - [LinqTunnel] - public static IEnumerable SkipWhile(this ReadOnlyArray source, Func predicate) => - source.Inner!.SkipWhile(predicate); - - /// - [LinqTunnel] - public static IEnumerable SkipWhile(this ReadOnlyArray source, Func predicate) => - source.Inner!.SkipWhile(predicate); - - /// - public static T Single(this ReadOnlyArray source) => - source.Inner!.Single(); - - /// - public static T Single(this ReadOnlyArray source, Func predicate) => - source.Inner!.Single(predicate); - - /// - public static T? SingleOrDefault(this ReadOnlyArray source) => - source.Inner!.SingleOrDefault(); - - /// - public static T? SingleOrDefault(this ReadOnlyArray source, Func predicate) => - source.Inner!.SingleOrDefault(predicate); - - /// - public static T First(this ReadOnlyArray source) - { - if (source.Length != 0) - return source[0]; - - // throw the same exception as LINQ - return source.Inner!.First(); - } - - /// - public static T First(this ReadOnlyArray source, Func predicate) - { - foreach (var item in source.Inner!) - if (predicate(item)) - return item; - - // throw the same exception as LINQ - return source.Inner.First(predicate); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static T? FirstOrDefault(this ReadOnlyArray source) => - source.Length == 0 ? default : source[0]; - - /// - public static T? FirstOrDefault(this ReadOnlyArray source, Func predicate) - { - foreach (var item in source.Inner!) - if (predicate(item)) - return item; - - return default; - } - - /// - public static T Last(this ReadOnlyArray source) - { - if ((uint)source.Length - 1 < (uint)source.Length) - return source[^1]; - - // throw the same exception as LINQ - return source.Inner!.Last(); - } - - /// - public static T Last(this ReadOnlyArray source, Func predicate) - { - var index = source.Length; - - while (true) - { - if ((uint)--index >= (uint)source.Length) - break; - - if (predicate(source[index])) - return source[index]; - } - - // throw the same exception as LINQ - return source.Inner!.Last(predicate); - } - - /// - public static T? LastOrDefault(this ReadOnlyArray source) - { - if ((uint)source.Length - 1 < (uint)source.Length) - return source[^1]; - - return default; - } - - /// - public static T? LastOrDefault(this ReadOnlyArray source, Func predicate) - { - var index = source.Length; - - while (true) - { - if ((uint)--index >= (uint)source.Length) - break; - - if (predicate(source[index])) - return source[index]; - } - - return default; - } - - /// - public static IEnumerable> GroupBy(this ReadOnlyArray source, Func keySelector) => - source.Inner!.GroupBy(keySelector); - - /// - public static IEnumerable> GroupBy(this ReadOnlyArray source, Func keySelector, Func elementSelector) => - source.Inner!.GroupBy(keySelector, elementSelector); - - /// - public static IEnumerable> GroupBy(this ReadOnlyArray source, Func keySelector, IEqualityComparer? comparer) => - source.Inner!.GroupBy(keySelector, comparer); - - /// - public static IEnumerable> GroupBy(this ReadOnlyArray source, Func keySelector, Func elementSelector, IEqualityComparer? comparer) => - source.Inner!.GroupBy(keySelector, elementSelector, comparer); - - /// - [LinqTunnel] - public static IEnumerable AsEnumerable(this ReadOnlyArray source) => - source.Inner!; - - /// - [LinqTunnel] - public static IQueryable AsQueryable(this ReadOnlyArray source) => - source.Inner!.AsQueryable(); - - /// - public static T[] ToArray(this ReadOnlyArray source) - { - _ = source.Length; - return source.AsSpan().ToArray(); - } - - /// - public static List ToList(this ReadOnlyArray source) - { - #if NET9_0_OR_GREATER - var list = new List(); - - ListAccessor.GetArray(list) = source.ToArray(); - ListAccessor.GetCount(list) = source.Length; - - return list; - #elif NET8_0_OR_GREATER - var list = new List(source.Length); - - System.Runtime.InteropServices.CollectionsMarshal.SetCount(list, source.Length); - source.TryCopyTo(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(list)); - - return list; - #else - return [..source.Inner!]; - #endif - } - - /// - public static Dictionary ToDictionary(this ReadOnlyArray source, Func keySelector, Func elementSelector) where TKey : notnull => - source.Inner!.ToDictionary(keySelector, elementSelector); - - /// - public static Dictionary ToDictionary(this ReadOnlyArray source, Func keySelector) where TKey : notnull => - source.Inner!.ToDictionary(keySelector); - - /// - public static Dictionary ToDictionary(this ReadOnlyArray source, Func keySelector, Func elementSelector, IEqualityComparer? comparer) where TKey : notnull => - source.Inner!.ToDictionary(keySelector, elementSelector, comparer); - - /// - public static Dictionary ToDictionary(this ReadOnlyArray source, Func keySelector, IEqualityComparer? comparer) where TKey : notnull => - source.Inner!.ToDictionary(keySelector, comparer); - - /// - public static HashSet ToHashSet(this ReadOnlyArray source) => - new(source.Inner!, null); - - /// - public static HashSet ToHashSet(this ReadOnlyArray source, IEqualityComparer? comparer) => - new(source.Inner!, comparer); - - /// - /// Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type. - /// - /// The sequence to compare to second. - /// The sequence to compare to the first sequence. - /// - /// if the two sequences are of equal length and their corresponding elements are equal - /// according to the default equality comparer for their type; otherwise, . - /// - public static bool SequenceEqual(this ReadOnlyArray a, [InstantHandle] IEnumerable b) => - a.Inner!.SequenceEqual(b); - - /// - /// Determines whether two sequences are equal by comparing the elements by using the specified equality comparer for their type. - /// - /// The sequence to compare to second. - /// The sequence to compare to the first sequence. - /// The to use to compare elements. - /// - /// if the two sequences are of equal length and their corresponding elements are equal - /// according to the specified equality comparer for their type; otherwise, . - /// - public static bool SequenceEqual(this ReadOnlyArray a, [InstantHandle] IEnumerable b, IEqualityComparer? comparer) => - a.Inner!.SequenceEqual(b, comparer); - - #if NET6_0 - - private static class SortHelper - { - public static readonly Func Identity = e => e; - } - - #endif -} +namespace Ramstack.Collections; + +public static partial class ReadOnlyArrayExtensions +{ + /// + [LinqTunnel] + public static T Aggregate(this ReadOnlyArray source, Func func) => + source.Inner!.Aggregate(func); + + /// + [LinqTunnel] + public static TAccumulate Aggregate(this ReadOnlyArray source, TAccumulate seed, Func func) => + source.Inner!.Aggregate(seed, func); + + /// + [LinqTunnel] + public static TResult Aggregate(this ReadOnlyArray source, TAccumulate seed, Func func, Func resultSelector) => + source.Inner!.Aggregate(seed, func, resultSelector); + + /// + [LinqTunnel] + public static IEnumerable Select(this ReadOnlyArray source, Func selector) => + source.Inner!.Select(selector); + + /// + [LinqTunnel] + public static IEnumerable Select(this ReadOnlyArray source, Func selector) => + source.Inner!.Select(selector); + + /// + [LinqTunnel] + public static IEnumerable SelectMany(this ReadOnlyArray source, Func> selector) => + source.Inner!.SelectMany(selector); + + /// + [LinqTunnel] + public static IEnumerable SelectMany(this ReadOnlyArray source, Func> selector) => + source.Inner!.SelectMany(selector); + + /// + [LinqTunnel] + public static IEnumerable SelectMany(this ReadOnlyArray source, Func> collectionSelector, Func resultSelector) => + source.Inner!.SelectMany(collectionSelector, resultSelector); + + /// + [LinqTunnel] + public static IEnumerable SelectMany(this ReadOnlyArray source, Func> collectionSelector, Func resultSelector) => + source.Inner!.SelectMany(collectionSelector, resultSelector); + + /// + /// Sorts the elements of a sequence in ascending order. + /// + /// The types of elements of . + /// A sequence of values to order. + /// + /// An whose elements are sorted. + /// + [LinqTunnel] + public static IEnumerable Order(this ReadOnlyArray source) + { + #if NET6_0 + return source.Inner!.OrderBy(SortHelper.Identity); + #else + return source.Inner!.Order(); + #endif + } + + /// + /// Sorts the elements of a sequence in ascending order. + /// + /// The types of elements of . + /// A sequence of values to order. + /// An to compare keys. + /// + /// An whose elements are sorted. + /// + [LinqTunnel] + public static IEnumerable Order(this ReadOnlyArray source, IComparer? comparer) + { + #if NET6_0 + return source.Inner!.OrderBy(SortHelper.Identity, comparer); + #else + return source.Inner!.Order(comparer); + #endif + } + + /// + /// Sorts the elements of a sequence in descending order. + /// + /// The types of elements of . + /// A sequence of values to order. + /// + /// An whose elements are sorted. + /// + [LinqTunnel] + public static IEnumerable OrderDescending(this ReadOnlyArray source) + { + #if NET6_0 + return source.Inner!.OrderByDescending(SortHelper.Identity); + #else + return source.Inner!.OrderDescending(); + #endif + } + + /// + /// Sorts the elements of a sequence in descending order. + /// + /// The types of elements of . + /// A sequence of values to order. + /// An to compare keys. + /// + /// An whose elements are sorted. + /// + [LinqTunnel] + public static IEnumerable OrderDescending(this ReadOnlyArray source, IComparer? comparer) + { + #if NET6_0 + return source.Inner!.OrderByDescending(SortHelper.Identity, comparer); + #else + return source.Inner!.OrderDescending(comparer); + #endif + } + + /// + [LinqTunnel] + public static IEnumerable OrderBy(this ReadOnlyArray source, Func keySelector) => + source.Inner!.OrderBy(keySelector); + + /// + [LinqTunnel] + public static IEnumerable OrderBy(this ReadOnlyArray source, Func keySelector, IComparer? comparer) => + source.Inner!.OrderBy(keySelector, comparer); + + /// + [LinqTunnel] + public static IEnumerable OrderByDescending(this ReadOnlyArray source, Func keySelector) => + source.Inner!.OrderByDescending(keySelector); + + /// + [LinqTunnel] + public static IEnumerable OrderByDescending(this ReadOnlyArray source, Func keySelector, IComparer? comparer) => + source.Inner!.OrderByDescending(keySelector, comparer); + + /// + [LinqTunnel] + public static IEnumerable Where(this ReadOnlyArray source, Func selector) => + source.Inner!.Where(selector); + + /// + [LinqTunnel] + public static IEnumerable Where(this ReadOnlyArray source, Func selector) => + source.Inner!.Where(selector); + + /// + [LinqTunnel] + public static IEnumerable Distinct(this ReadOnlyArray source) => + source.Inner!.Distinct(); + + /// + [LinqTunnel] + public static IEnumerable Distinct(this ReadOnlyArray source, IEqualityComparer? comparer) => + source.Inner!.Distinct(comparer); + + /// + public static IEnumerable DistinctBy(this ReadOnlyArray source, Func keySelector) => + source.Inner!.DistinctBy(keySelector); + + /// + [LinqTunnel] + public static IEnumerable DistinctBy(this ReadOnlyArray source, Func keySelector, IEqualityComparer? comparer) => + source.Inner!.DistinctBy(keySelector, comparer); + + /// + public static bool Any(this ReadOnlyArray source) => + source.Inner!.Length != 0; + + /// + public static bool Any(this ReadOnlyArray source, Func predicate) + { + foreach (var item in source.Inner!) + if (predicate(item)) + return true; + + return false; + } + + /// + public static bool All(this ReadOnlyArray source, Func predicate) + { + foreach (var item in source.Inner!) + if (!predicate(item)) + return false; + + return true; + } + + /// + public static int Count(this ReadOnlyArray source) => + source.Inner!.Length; + + /// + public static int Count(this ReadOnlyArray source, Func predicate) + { + var count = 0; + + foreach (var item in source.Inner!) + if (predicate(item)) + count++; + + return count; + } + + /// + [LinqTunnel] + public static IEnumerable Take(this ReadOnlyArray source, int count) => + source.Inner!.Take(count); + + /// + [LinqTunnel] + public static IEnumerable TakeLast(this ReadOnlyArray source, int count) => + source.Inner!.TakeLast(count); + + /// + [LinqTunnel] + public static IEnumerable TakeWhile(this ReadOnlyArray source, Func predicate) => + source.Inner!.TakeWhile(predicate); + + /// + [LinqTunnel] + public static IEnumerable TakeWhile(this ReadOnlyArray source, Func predicate) => + source.Inner!.TakeWhile(predicate); + + /// + [LinqTunnel] + public static IEnumerable Skip(this ReadOnlyArray source, int count) => + source.Inner!.Skip(count); + + /// + [LinqTunnel] + public static IEnumerable SkipLast(this ReadOnlyArray source, int count) => + source.Inner!.SkipLast(count); + + /// + [LinqTunnel] + public static IEnumerable SkipWhile(this ReadOnlyArray source, Func predicate) => + source.Inner!.SkipWhile(predicate); + + /// + [LinqTunnel] + public static IEnumerable SkipWhile(this ReadOnlyArray source, Func predicate) => + source.Inner!.SkipWhile(predicate); + + /// + [SuppressMessage("Naming", "CA1720:Identifier contains type name", + Justification = "The method mirrors Enumerable.Single, and renaming it would break the public API.")] + public static T Single(this ReadOnlyArray source) => + source.Inner!.Single(); + + /// + [SuppressMessage("Naming", "CA1720:Identifier contains type name", + Justification = "The method mirrors Enumerable.Single, and renaming it would break the public API.")] + public static T Single(this ReadOnlyArray source, Func predicate) => + source.Inner!.Single(predicate); + + /// + public static T? SingleOrDefault(this ReadOnlyArray source) => + source.Inner!.SingleOrDefault(); + + /// + public static T? SingleOrDefault(this ReadOnlyArray source, Func predicate) => + source.Inner!.SingleOrDefault(predicate); + + /// + public static T First(this ReadOnlyArray source) + { + if (source.Length != 0) + return source[0]; + + // throw the same exception as LINQ + return source.Inner!.First(); + } + + /// + public static T First(this ReadOnlyArray source, Func predicate) + { + foreach (var item in source.Inner!) + if (predicate(item)) + return item; + + // throw the same exception as LINQ + return source.Inner.First(predicate); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T? FirstOrDefault(this ReadOnlyArray source) => + source.Length == 0 ? default : source[0]; + + /// + public static T? FirstOrDefault(this ReadOnlyArray source, Func predicate) + { + foreach (var item in source.Inner!) + if (predicate(item)) + return item; + + return default; + } + + /// + public static T Last(this ReadOnlyArray source) + { + if ((uint)source.Length - 1 < (uint)source.Length) + return source[^1]; + + // throw the same exception as LINQ + return source.Inner!.Last(); + } + + /// + public static T Last(this ReadOnlyArray source, Func predicate) + { + var index = source.Length; + + while (true) + { + if ((uint)--index >= (uint)source.Length) + break; + + if (predicate(source[index])) + return source[index]; + } + + // throw the same exception as LINQ + return source.Inner!.Last(predicate); + } + + /// + public static T? LastOrDefault(this ReadOnlyArray source) + { + if ((uint)source.Length - 1 < (uint)source.Length) + return source[^1]; + + return default; + } + + /// + public static T? LastOrDefault(this ReadOnlyArray source, Func predicate) + { + var index = source.Length; + + while (true) + { + if ((uint)--index >= (uint)source.Length) + break; + + if (predicate(source[index])) + return source[index]; + } + + return default; + } + + /// + public static IEnumerable> GroupBy(this ReadOnlyArray source, Func keySelector) => + source.Inner!.GroupBy(keySelector); + + /// + public static IEnumerable> GroupBy(this ReadOnlyArray source, Func keySelector, Func elementSelector) => + source.Inner!.GroupBy(keySelector, elementSelector); + + /// + public static IEnumerable> GroupBy(this ReadOnlyArray source, Func keySelector, IEqualityComparer? comparer) => + source.Inner!.GroupBy(keySelector, comparer); + + /// + public static IEnumerable> GroupBy(this ReadOnlyArray source, Func keySelector, Func elementSelector, IEqualityComparer? comparer) => + source.Inner!.GroupBy(keySelector, elementSelector, comparer); + + /// + [LinqTunnel] + public static IEnumerable AsEnumerable(this ReadOnlyArray source) => + source.Inner!; + + /// + [LinqTunnel] + public static IQueryable AsQueryable(this ReadOnlyArray source) => + source.Inner!.AsQueryable(); + + /// + public static T[] ToArray(this ReadOnlyArray source) + { + _ = source.Length; + return source.AsSpan().ToArray(); + } + + /// + public static List ToList(this ReadOnlyArray source) + { + #if NET9_0_OR_GREATER + var list = new List(); + + ListAccessor.GetArray(list) = source.ToArray(); + ListAccessor.GetCount(list) = source.Length; + + return list; + #elif NET8_0_OR_GREATER + var list = new List(source.Length); + + System.Runtime.InteropServices.CollectionsMarshal.SetCount(list, source.Length); + source.TryCopyTo(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(list)); + + return list; + #else + return [..source.Inner!]; + #endif + } + + /// + public static Dictionary ToDictionary(this ReadOnlyArray source, Func keySelector, Func elementSelector) where TKey : notnull => + source.Inner!.ToDictionary(keySelector, elementSelector); + + /// + public static Dictionary ToDictionary(this ReadOnlyArray source, Func keySelector) where TKey : notnull => + source.Inner!.ToDictionary(keySelector); + + /// + public static Dictionary ToDictionary(this ReadOnlyArray source, Func keySelector, Func elementSelector, IEqualityComparer? comparer) where TKey : notnull => + source.Inner!.ToDictionary(keySelector, elementSelector, comparer); + + /// + public static Dictionary ToDictionary(this ReadOnlyArray source, Func keySelector, IEqualityComparer? comparer) where TKey : notnull => + source.Inner!.ToDictionary(keySelector, comparer); + + /// + public static HashSet ToHashSet(this ReadOnlyArray source) => + new(source.Inner!, null); + + /// + public static HashSet ToHashSet(this ReadOnlyArray source, IEqualityComparer? comparer) => + new(source.Inner!, comparer); + + /// + /// Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type. + /// + /// The sequence to compare to second. + /// The sequence to compare to the first sequence. + /// + /// if the two sequences are of equal length and their corresponding elements are equal + /// according to the default equality comparer for their type; otherwise, . + /// + public static bool SequenceEqual(this ReadOnlyArray a, [InstantHandle] IEnumerable b) => + a.Inner!.SequenceEqual(b); + + /// + /// Determines whether two sequences are equal by comparing the elements by using the specified equality comparer for their type. + /// + /// The sequence to compare to second. + /// The sequence to compare to the first sequence. + /// The to use to compare elements. + /// + /// if the two sequences are of equal length and their corresponding elements are equal + /// according to the specified equality comparer for their type; otherwise, . + /// + public static bool SequenceEqual(this ReadOnlyArray a, [InstantHandle] IEnumerable b, IEqualityComparer? comparer) => + a.Inner!.SequenceEqual(b, comparer); + + #if NET6_0 + + private static class SortHelper + { + public static readonly Func Identity = e => e; + } + + #endif +} diff --git a/Ramstack.Structures/Collections/ReadOnlyArrayExtensions.cs b/Ramstack.Structures/Collections/ReadOnlyArrayExtensions.cs index 4057034..61b153a 100644 --- a/Ramstack.Structures/Collections/ReadOnlyArrayExtensions.cs +++ b/Ramstack.Structures/Collections/ReadOnlyArrayExtensions.cs @@ -1,90 +1,90 @@ -namespace Ramstack.Collections; - -/// -/// Provides extension methods for the class. -/// -public static partial class ReadOnlyArrayExtensions -{ - /// - /// Creates a read-only array from the specified read-only span. - /// - /// The type of element in the array. - /// The read-only span to create a read-only from. - /// - /// A read-only array containing the specified items. - /// - public static ReadOnlyArray ToReadOnlyArray(this Span items) => - new(items); - - /// - /// Creates a read-only array from the specified read-only span. - /// - /// The type of element in the array. - /// The read-only span to create a read-only from. - /// - /// A read-only array containing the specified items. - /// - public static ReadOnlyArray ToReadOnlyArray(this ReadOnlySpan items) => - new(items); - - /// - /// Enumerates a sequence exactly once and produces a read-only array of its contents. - /// - /// The type of element in the sequence. - /// The array to create a read-only from. - /// - /// A read-only array containing the specified items. - /// - public static ReadOnlyArray ToReadOnlyArray(this T[] items) => - ReadOnlyArray.Create(items); - - /// - /// Enumerates a sequence exactly once and produces a read-only array of its contents. - /// - /// The type of element in the array. - /// The sequence to create a read-only from. - /// - /// A read-only array containing the specified items. - /// - [SuppressMessage("ReSharper", "OperatorIsCanBeUsed")] - public static ReadOnlyArray ToReadOnlyArray([InstantHandle] this IEnumerable items) - { - if (items.GetType() == typeof(ReadOnlyArray)) - return (ReadOnlyArray)items; - - if (items.GetType() == typeof(ImmutableArray)) - return (ImmutableArray)items; - - if (items.GetType() == typeof(T[])) - return ReadOnlyArray.Create(Unsafe.As, T[]>(ref items)); - - return new ReadOnlyArray(items.ToArray()); - } - - /// - /// Searches for the specified object and returns the index of its first occurrence. - /// - /// The type of element in the array. - /// The instance. - /// The object to locate in array. - /// - /// The zero-based index of the first occurrence of - /// in the , if found; otherwise, -1. - /// - public static int IndexOf(this ReadOnlyArray array, T value) => - Array.IndexOf(array.Inner!, value); - - /// - /// Searches for the specified object and returns the index - /// of the last occurrence within the entire . - /// - /// The type of element in the array. - /// The instance. - /// The object to locate in array. - /// - /// The zero-based index of the last occurrence of - /// in the , if found; otherwise, -1. - /// - public static int LastIndexOf(this ReadOnlyArray array, T value) => - Array.LastIndexOf(array.Inner!, value); -} +namespace Ramstack.Collections; + +/// +/// Provides extension methods for the class. +/// +public static partial class ReadOnlyArrayExtensions +{ + /// + /// Creates a read-only array from the specified read-only span. + /// + /// The type of element in the array. + /// The read-only span to create a read-only from. + /// + /// A read-only array containing the specified items. + /// + public static ReadOnlyArray ToReadOnlyArray(this Span items) => + new(items); + + /// + /// Creates a read-only array from the specified read-only span. + /// + /// The type of element in the array. + /// The read-only span to create a read-only from. + /// + /// A read-only array containing the specified items. + /// + public static ReadOnlyArray ToReadOnlyArray(this ReadOnlySpan items) => + new(items); + + /// + /// Enumerates a sequence exactly once and produces a read-only array of its contents. + /// + /// The type of element in the sequence. + /// The array to create a read-only from. + /// + /// A read-only array containing the specified items. + /// + public static ReadOnlyArray ToReadOnlyArray(this T[] items) => + ReadOnlyArray.Create(items); + + /// + /// Enumerates a sequence exactly once and produces a read-only array of its contents. + /// + /// The type of element in the array. + /// The sequence to create a read-only from. + /// + /// A read-only array containing the specified items. + /// + [SuppressMessage("ReSharper", "OperatorIsCanBeUsed")] + public static ReadOnlyArray ToReadOnlyArray([InstantHandle] this IEnumerable items) + { + if (items.GetType() == typeof(ReadOnlyArray)) + return (ReadOnlyArray)items; + + if (items.GetType() == typeof(ImmutableArray)) + return (ImmutableArray)items; + + if (items.GetType() == typeof(T[])) + return ReadOnlyArray.Create(Unsafe.As, T[]>(ref items)); + + return new ReadOnlyArray(items.ToArray()); + } + + /// + /// Searches for the specified object and returns the index of its first occurrence. + /// + /// The type of element in the array. + /// The instance. + /// The object to locate in array. + /// + /// The zero-based index of the first occurrence of + /// in the , if found; otherwise, -1. + /// + public static int IndexOf(this ReadOnlyArray array, T value) => + Array.IndexOf(array.Inner!, value); + + /// + /// Searches for the specified object and returns the index + /// of the last occurrence within the entire . + /// + /// The type of element in the array. + /// The instance. + /// The object to locate in array. + /// + /// The zero-based index of the last occurrence of + /// in the , if found; otherwise, -1. + /// + public static int LastIndexOf(this ReadOnlyArray array, T value) => + Array.LastIndexOf(array.Inner!, value); +} diff --git a/Ramstack.Structures/Collections/ReadOnlyArray`1.cs b/Ramstack.Structures/Collections/ReadOnlyArray`1.cs index 4a6ffd4..04a2b2d 100644 --- a/Ramstack.Structures/Collections/ReadOnlyArray`1.cs +++ b/Ramstack.Structures/Collections/ReadOnlyArray`1.cs @@ -1,516 +1,518 @@ -namespace Ramstack.Collections; - -/// -/// Represents a read-only array wrapper. -/// -/// The type of element stored by the array. -[DebuggerDisplay("{ToStringDebugger(),nq}")] -[CollectionBuilder(typeof(ReadOnlyArray), nameof(ReadOnlyArray.Create))] -public readonly struct ReadOnlyArray : IReadOnlyList, IEquatable> -{ - [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - internal readonly T[]? Inner; - - /// - /// Gets an empty read-only array. - /// - public static ReadOnlyArray Empty => new(Array.Empty()); - - /// - /// Gets the number of elements contained in the . - /// - public int Length => Inner!.Length; - - /// - /// Gets a value indicating whether this was declared but not initialized. - /// - public bool IsDefault - { - [MemberNotNullWhen(false, nameof(Inner))] - get => Inner is null; - } - - /// - /// Gets a value indicating whether this is empty or is not initialized. - /// - public bool IsDefaultOrEmpty - { - [MemberNotNullWhen(false, nameof(Inner))] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => Inner is var inner && (inner is null || inner.Length == 0); - } - - /// - /// Gets an element at the specified index. - /// - /// The zero-based index of the element to get. - public ref readonly T this[int index] => ref Inner![index]; - - /// - /// Initializes a new instance of the structure. - /// - /// The underlying array. - internal ReadOnlyArray(T[] array) => - Inner = array; - - /// - /// Initializes a new instance of the structure with the specified object. - /// - /// The object to store in the array. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyArray(T item) => - Inner = [item]; - - /// - /// Initializes a new instance of the structure with the specified objects. - /// - /// The object to store in the array. - /// The object to store in the array. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyArray(T item1, T item2) => - Inner = [item1, item2]; - - /// - /// Initializes a new instance of the structure with the specified objects. - /// - /// The object to store in the array. - /// The object to store in the array. - /// The object to store in the array. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyArray(T item1, T item2, T item3) => - Inner = [item1, item2, item3]; - - /// - /// Initializes a new instance of the structure with the specified objects. - /// - /// The object to store in the array. - /// The object to store in the array. - /// The object to store in the array. - /// The object to store in the array. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyArray(T item1, T item2, T item3, T item4) => - Inner = [item1, item2, item3, item4]; - - /// - /// Initializes a new instance of the structure with the specified objects. - /// - /// The objects to populate the array with. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyArray(ReadOnlySpan items) - { - // - // Avoid address exposure in cases where the destination local - // does not actually end up escaping in any way. - // https://github.com/dotnet/runtime/pull/102808 - // - - // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression - if (items.Length != 0) - Inner = items.ToArray(); - else - Inner = []; - } - - /// - /// Returns an enumerator that iterates through the collection. - /// - /// - /// An enumerator that can be used to iterate through the collection. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Enumerator GetEnumerator() - { - var array = Inner; - _ = array!.Length; - - return new Enumerator(array); - } - - /// - /// Forms a slice out of the current array that begins at a specified index. - /// - /// The index at which to begin the slice. - /// - /// A readonly span that consists of all elements of the current array - /// from to the end. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyArray Slice(int start) - { - var array = Inner; - _ = array!.Length; - - return start != 0 - ? new ReadOnlyArray(array.AsSpan(start)) - : this; - } - - /// - /// Forms a slice out of the current array that begins at a specified index for a specified length. - /// - /// The index at which to begin the slice. - /// The desired length for the slice. - /// - /// A readonly span that consists of elements - /// from the current array starting at . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyArray Slice(int start, int length) - { - var array = Inner; - var count = array!.Length; - - if (start == 0 && length == count) - return this; - - return new ReadOnlyArray(array.AsSpan(start, length)); - } - - /// - public bool Equals(ReadOnlyArray other) => - ReferenceEquals(Inner, other.Inner); - - /// - public override bool Equals(object? obj) => - obj is ReadOnlyArray array && Equals(array); - - /// - public override int GetHashCode() => - Inner?.GetHashCode() ?? 0; - - /// - /// Creates a read-only span over the current array. - /// - /// - /// The read-only span representation of the array. - /// - public ReadOnlySpan AsSpan() => - new(Inner ?? []); - - /// - /// Creates a new read-only span over a portion of the current array - /// starting at a specified position to the end of the array. - /// - /// The index at which to begin the span. - /// - /// The read-only span representation of the array. - /// - public ReadOnlySpan AsSpan(int start) => - // ReSharper disable once ReplaceSliceWithRangeIndexer - AsSpan().Slice(start); - - /// - /// Creates a new read-only span over a portion of the current array - /// starting at a specified position for a specified length. - /// - /// The index at which to begin the span. - /// The number of items in the span. - /// - /// The read-only span representation of the array. - /// - public ReadOnlySpan AsSpan(int start, int length) => - AsSpan().Slice(start, length); - - /// - /// Creates an over the current array. - /// - /// - /// The read-only view of the array. - /// - public ArrayView AsView() => - new(Inner ?? []); - - /// - /// Creates an over the current array - /// starting at a specified position to the end of the array. - /// - /// The index at which to begin the array view. - /// - /// The read-only view of the array. - /// - public ArrayView AsView(int index) => - new(Inner ?? [], index); - - /// - /// Creates an over the current array - /// starting at a specified position for a specified length. - /// - /// The index at which to begin the array view. - /// The number of items in the array view. - /// - /// The read-only view of the array. - /// - public ArrayView AsView(int index, int count) => - new(Inner ?? [], index, count); - - /// - /// Creates a new read-only memory region over the read-only array. - /// - /// - /// The memory representation of the array. - /// - public ReadOnlyMemory AsMemory() => - this; - - /// - /// Returns a reference to the element of the at index zero. - /// - /// - /// A reference to the element of the at index zero, - /// or if is true. - /// - public ref readonly T GetPinnableReference() => - ref MemoryMarshal.GetArrayDataReference(Inner!); - - /// - /// Copies the contents of this into a destination . - /// - /// The span to copy items into. - public void CopyTo(Span destination) - { - var array = Inner; - _ = array!.Length; - - array.AsSpan().CopyTo(destination); - } - - /// - /// Attempts to copy the contents of this into a destination - /// and returns a value to indicate whether the operation succeeded. - /// - /// The span to copy items into. - /// - /// if the copy operation succeeded; otherwise, . - /// - public bool TryCopyTo(Span destination) - { - var array = Inner; - _ = array!.Length; - - return array.AsSpan().TryCopyTo(destination); - } - - /// - /// Returns a read-only array from the . - /// - /// The array of objects to get a read-only wrapper for. - /// - /// A read-only array. - /// - public static explicit operator ReadOnlyArray(T[]? array) => - new(array!); - - /// - /// Returns a read-only array from the . - /// - /// The array of objects to get a read-only wrapper for. - /// - /// A read-only array. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator ReadOnlyArray(ImmutableArray array) - { - #if NET8_0_OR_GREATER - return new ReadOnlyArray(ImmutableCollectionsMarshal.AsArray(array)!); - #else - // - // https://github.com/dotnet/runtime/issues/83141#issuecomment-1460324087 - // - return Unsafe.As, ReadOnlyArray>(ref array); - #endif - } - - /// - /// Returns a array from the . - /// - /// The array of objects to get a read-only wrapper for. - /// - /// A read-only array. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator ImmutableArray(ReadOnlyArray array) - { - #if NET8_0_OR_GREATER - return ImmutableCollectionsMarshal.AsImmutableArray(array.Inner); - #else - // - // https://github.com/dotnet/runtime/issues/83141#issuecomment-1460324087 - // - return Unsafe.As, ImmutableArray>(ref array); - #endif - } - - /// - /// Returns a from the . - /// - /// The . - /// - /// A . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator ReadOnlySpan(ReadOnlyArray array) => - new(array.Inner ?? []); - - /// - /// Returns a from the . - /// - /// The . - /// - /// A . - /// - public static implicit operator ReadOnlyMemory(ReadOnlyArray array) => - new(array.Inner ?? []); - - /// - /// Returns a value that indicates if two arrays are equal. - /// - /// The array to the left of the operator. - /// The array to the right of the operator. - /// - /// true if the arrays are equal; otherwise, false. - /// - public static bool operator ==(ReadOnlyArray left, ReadOnlyArray right) => - left.Inner == right.Inner; - - /// - /// Returns a value that indicates if two arrays are not equal. - /// - /// The array to the left of the operator. - /// The array to the right of the operator. - /// - /// true if the arrays are not equal; otherwise, false. - /// - public static bool operator !=(ReadOnlyArray left, ReadOnlyArray right) => - left.Inner != right.Inner; - - /// - /// Returns a value that indicates if two arrays are equal. - /// - /// The array to the left of the operator. - /// The array to the right of the operator. - /// - /// true if the arrays are equal; otherwise, false. - /// - public static bool operator ==(ReadOnlyArray? left, ReadOnlyArray? right) => - left.GetValueOrDefault() == right.GetValueOrDefault(); - - /// - /// Returns a value that indicates if two arrays are not equal. - /// - /// The array to the left of the operator. - /// The array to the right of the operator. - /// - /// true if the arrays are not equal; otherwise, false. - /// - public static bool operator !=(ReadOnlyArray? left, ReadOnlyArray? right) => - left.GetValueOrDefault() != right.GetValueOrDefault(); - - /// - /// Returns a string representation of the current instance's state, intended for debugging purposes. - /// - /// - /// A string containing information about the current instance. - /// - private string ToStringDebugger() => - Inner is { } array ? $"Length = {array.Length}" : "Uninitialized"; - - [MemberNotNull(nameof(Inner))] - private void EnsureInitialized() - { - if (Inner is null) - { - const string? message = - "This operation cannot be performed on a default instance of ReadOnlyArray. " + - "Consider initializing the array, or checking the ReadOnlyArray.IsDefault property."; - throw new InvalidOperationException(message); - } - } - - #region IEnumerable implementation - - IEnumerator IEnumerable.GetEnumerator() - { - EnsureInitialized(); - - return Inner.AsEnumerable().GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - EnsureInitialized(); - - return Inner.AsEnumerable().GetEnumerator(); - } - - #endregion - - #region IReadOnlyCollection implementation - - int IReadOnlyCollection.Count - { - get - { - EnsureInitialized(); - return Inner.Length; - } - } - - #endregion - - #region IReadOnlyList implementation - - T IReadOnlyList.this[int index] - { - get - { - EnsureInitialized(); - return Inner![index]; - } - } - - #endregion - - #region Inner type: Enumerator - - /// - /// Represents the enumerator. - /// - public struct Enumerator - { - private readonly T[] _array; - private int _index; - - /// - /// Gets the element in the collection at the current position of the enumerator. - /// - public readonly ref readonly T Current - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => ref _array[_index]; - } - - /// - /// Initializes a new instance of the structure. - /// - /// The array to iterate. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal Enumerator(T[] array) - { - _index = -1; - _array = array; - } - - /// - /// Advances the enumerator to the next element of the collection. - /// - /// - /// if the enumerator was successfully advanced to the next element; - /// otherwise, . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool MoveNext() => - ++_index < _array.Length; - } - - #endregion -} +namespace Ramstack.Collections; + +/// +/// Represents a read-only array wrapper. +/// +/// The type of element stored by the array. +[DebuggerDisplay("{ToStringDebugger(),nq}")] +[CollectionBuilder(typeof(ReadOnlyArray), nameof(ReadOnlyArray.Create))] +public readonly struct ReadOnlyArray : IReadOnlyList, IEquatable> +{ + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + internal readonly T[]? Inner; + + /// + /// Gets an empty read-only array. + /// + [SuppressMessage("Design", "CA1000:Do not declare static members on generic types", + Justification = "Like ImmutableArray.Empty, the empty instance belongs to the generic type, and removing it would break the public API.")] + public static ReadOnlyArray Empty => new(Array.Empty()); + + /// + /// Gets the number of elements contained in the . + /// + public int Length => Inner!.Length; + + /// + /// Gets a value indicating whether this was declared but not initialized. + /// + public bool IsDefault + { + [MemberNotNullWhen(false, nameof(Inner))] + get => Inner is null; + } + + /// + /// Gets a value indicating whether this is empty or is not initialized. + /// + public bool IsDefaultOrEmpty + { + [MemberNotNullWhen(false, nameof(Inner))] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Inner is var inner && (inner is null || inner.Length == 0); + } + + /// + /// Gets an element at the specified index. + /// + /// The zero-based index of the element to get. + public ref readonly T this[int index] => ref Inner![index]; + + /// + /// Initializes a new instance of the structure. + /// + /// The underlying array. + internal ReadOnlyArray(T[] array) => + Inner = array; + + /// + /// Initializes a new instance of the structure with the specified object. + /// + /// The object to store in the array. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyArray(T item) => + Inner = [item]; + + /// + /// Initializes a new instance of the structure with the specified objects. + /// + /// The object to store in the array. + /// The object to store in the array. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyArray(T item1, T item2) => + Inner = [item1, item2]; + + /// + /// Initializes a new instance of the structure with the specified objects. + /// + /// The object to store in the array. + /// The object to store in the array. + /// The object to store in the array. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyArray(T item1, T item2, T item3) => + Inner = [item1, item2, item3]; + + /// + /// Initializes a new instance of the structure with the specified objects. + /// + /// The object to store in the array. + /// The object to store in the array. + /// The object to store in the array. + /// The object to store in the array. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyArray(T item1, T item2, T item3, T item4) => + Inner = [item1, item2, item3, item4]; + + /// + /// Initializes a new instance of the structure with the specified objects. + /// + /// The objects to populate the array with. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyArray(ReadOnlySpan items) + { + // + // Avoid address exposure in cases where the destination local + // does not actually end up escaping in any way. + // https://github.com/dotnet/runtime/pull/102808 + // + + // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression + if (items.Length != 0) + Inner = items.ToArray(); + else + Inner = []; + } + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// An enumerator that can be used to iterate through the collection. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Enumerator GetEnumerator() + { + var array = Inner; + _ = array!.Length; + + return new Enumerator(array); + } + + /// + /// Forms a slice out of the current array that begins at a specified index. + /// + /// The index at which to begin the slice. + /// + /// A readonly span that consists of all elements of the current array + /// from to the end. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyArray Slice(int start) + { + var array = Inner; + _ = array!.Length; + + return start != 0 + ? new ReadOnlyArray(array.AsSpan(start)) + : this; + } + + /// + /// Forms a slice out of the current array that begins at a specified index for a specified length. + /// + /// The index at which to begin the slice. + /// The desired length for the slice. + /// + /// A readonly span that consists of elements + /// from the current array starting at . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyArray Slice(int start, int length) + { + var array = Inner; + var count = array!.Length; + + if (start == 0 && length == count) + return this; + + return new ReadOnlyArray(array.AsSpan(start, length)); + } + + /// + public bool Equals(ReadOnlyArray other) => + ReferenceEquals(Inner, other.Inner); + + /// + public override bool Equals(object? obj) => + obj is ReadOnlyArray array && Equals(array); + + /// + public override int GetHashCode() => + Inner?.GetHashCode() ?? 0; + + /// + /// Creates a read-only span over the current array. + /// + /// + /// The read-only span representation of the array. + /// + public ReadOnlySpan AsSpan() => + new(Inner ?? []); + + /// + /// Creates a new read-only span over a portion of the current array + /// starting at a specified position to the end of the array. + /// + /// The index at which to begin the span. + /// + /// The read-only span representation of the array. + /// + public ReadOnlySpan AsSpan(int start) => + // ReSharper disable once ReplaceSliceWithRangeIndexer + AsSpan().Slice(start); + + /// + /// Creates a new read-only span over a portion of the current array + /// starting at a specified position for a specified length. + /// + /// The index at which to begin the span. + /// The number of items in the span. + /// + /// The read-only span representation of the array. + /// + public ReadOnlySpan AsSpan(int start, int length) => + AsSpan().Slice(start, length); + + /// + /// Creates an over the current array. + /// + /// + /// The read-only view of the array. + /// + public ArrayView AsView() => + new(Inner ?? []); + + /// + /// Creates an over the current array + /// starting at a specified position to the end of the array. + /// + /// The index at which to begin the array view. + /// + /// The read-only view of the array. + /// + public ArrayView AsView(int index) => + new(Inner ?? [], index); + + /// + /// Creates an over the current array + /// starting at a specified position for a specified length. + /// + /// The index at which to begin the array view. + /// The number of items in the array view. + /// + /// The read-only view of the array. + /// + public ArrayView AsView(int index, int count) => + new(Inner ?? [], index, count); + + /// + /// Creates a new read-only memory region over the read-only array. + /// + /// + /// The memory representation of the array. + /// + public ReadOnlyMemory AsMemory() => + this; + + /// + /// Returns a reference to the element of the at index zero. + /// + /// + /// A reference to the element of the at index zero, + /// or if is true. + /// + public ref readonly T GetPinnableReference() => + ref MemoryMarshal.GetArrayDataReference(Inner!); + + /// + /// Copies the contents of this into a destination . + /// + /// The span to copy items into. + public void CopyTo(Span destination) + { + var array = Inner; + _ = array!.Length; + + array.AsSpan().CopyTo(destination); + } + + /// + /// Attempts to copy the contents of this into a destination + /// and returns a value to indicate whether the operation succeeded. + /// + /// The span to copy items into. + /// + /// if the copy operation succeeded; otherwise, . + /// + public bool TryCopyTo(Span destination) + { + var array = Inner; + _ = array!.Length; + + return array.AsSpan().TryCopyTo(destination); + } + + /// + /// Returns a read-only array from the . + /// + /// The array of objects to get a read-only wrapper for. + /// + /// A read-only array. + /// + public static explicit operator ReadOnlyArray(T[]? array) => + new(array!); + + /// + /// Returns a read-only array from the . + /// + /// The array of objects to get a read-only wrapper for. + /// + /// A read-only array. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlyArray(ImmutableArray array) + { + #if NET8_0_OR_GREATER + return new ReadOnlyArray(ImmutableCollectionsMarshal.AsArray(array)!); + #else + // + // https://github.com/dotnet/runtime/issues/83141#issuecomment-1460324087 + // + return Unsafe.As, ReadOnlyArray>(ref array); + #endif + } + + /// + /// Returns a array from the . + /// + /// The array of objects to get a read-only wrapper for. + /// + /// A read-only array. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ImmutableArray(ReadOnlyArray array) + { + #if NET8_0_OR_GREATER + return ImmutableCollectionsMarshal.AsImmutableArray(array.Inner); + #else + // + // https://github.com/dotnet/runtime/issues/83141#issuecomment-1460324087 + // + return Unsafe.As, ImmutableArray>(ref array); + #endif + } + + /// + /// Returns a from the . + /// + /// The . + /// + /// A . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlySpan(ReadOnlyArray array) => + new(array.Inner ?? []); + + /// + /// Returns a from the . + /// + /// The . + /// + /// A . + /// + public static implicit operator ReadOnlyMemory(ReadOnlyArray array) => + new(array.Inner ?? []); + + /// + /// Returns a value that indicates if two arrays are equal. + /// + /// The array to the left of the operator. + /// The array to the right of the operator. + /// + /// true if the arrays are equal; otherwise, false. + /// + public static bool operator ==(ReadOnlyArray left, ReadOnlyArray right) => + left.Inner == right.Inner; + + /// + /// Returns a value that indicates if two arrays are not equal. + /// + /// The array to the left of the operator. + /// The array to the right of the operator. + /// + /// true if the arrays are not equal; otherwise, false. + /// + public static bool operator !=(ReadOnlyArray left, ReadOnlyArray right) => + left.Inner != right.Inner; + + /// + /// Returns a value that indicates if two arrays are equal. + /// + /// The array to the left of the operator. + /// The array to the right of the operator. + /// + /// true if the arrays are equal; otherwise, false. + /// + public static bool operator ==(ReadOnlyArray? left, ReadOnlyArray? right) => + left.GetValueOrDefault() == right.GetValueOrDefault(); + + /// + /// Returns a value that indicates if two arrays are not equal. + /// + /// The array to the left of the operator. + /// The array to the right of the operator. + /// + /// true if the arrays are not equal; otherwise, false. + /// + public static bool operator !=(ReadOnlyArray? left, ReadOnlyArray? right) => + left.GetValueOrDefault() != right.GetValueOrDefault(); + + /// + /// Returns a string representation of the current instance's state, intended for debugging purposes. + /// + /// + /// A string containing information about the current instance. + /// + private string ToStringDebugger() => + Inner is { } array ? $"Length = {array.Length}" : "Uninitialized"; + + [MemberNotNull(nameof(Inner))] + private void EnsureInitialized() + { + if (Inner is null) + { + const string? message = + "This operation cannot be performed on a default instance of ReadOnlyArray. " + + "Consider initializing the array, or checking the ReadOnlyArray.IsDefault property."; + throw new InvalidOperationException(message); + } + } + + #region IEnumerable implementation + + IEnumerator IEnumerable.GetEnumerator() + { + EnsureInitialized(); + + return Inner.AsEnumerable().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + EnsureInitialized(); + + return Inner.AsEnumerable().GetEnumerator(); + } + + #endregion + + #region IReadOnlyCollection implementation + + int IReadOnlyCollection.Count + { + get + { + EnsureInitialized(); + return Inner.Length; + } + } + + #endregion + + #region IReadOnlyList implementation + + T IReadOnlyList.this[int index] + { + get + { + EnsureInitialized(); + return Inner![index]; + } + } + + #endregion + + #region Inner type: Enumerator + + /// + /// Represents the enumerator. + /// + public struct Enumerator + { + private readonly T[] _array; + private int _index; + + /// + /// Gets the element in the collection at the current position of the enumerator. + /// + public readonly ref readonly T Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ref _array[_index]; + } + + /// + /// Initializes a new instance of the structure. + /// + /// The array to iterate. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(T[] array) + { + _index = -1; + _array = array; + } + + /// + /// Advances the enumerator to the next element of the collection. + /// + /// + /// if the enumerator was successfully advanced to the next element; + /// otherwise, . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() => + ++_index < _array.Length; + } + + #endregion +} diff --git a/Ramstack.Structures/Internal/Jetbrains.Assertions.cs b/Ramstack.Structures/Internal/Jetbrains.Assertions.cs index 6b0b2b9..d4f3f7d 100644 --- a/Ramstack.Structures/Internal/Jetbrains.Assertions.cs +++ b/Ramstack.Structures/Internal/Jetbrains.Assertions.cs @@ -1,66 +1,66 @@ -// MIT License -// -// Copyright (c) 2016 JetBrains http://www.jetbrains.com -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -#nullable disable - -#pragma warning disable 1591 - -// ReSharper disable CheckNamespace -// ReSharper disable ConvertToPrimaryConstructor -// ReSharper disable InconsistentNaming -// ReSharper disable IntroduceOptionalParameters.Global -// ReSharper disable MemberCanBePrivate.Global -// ReSharper disable MemberCanBeProtected.Global -// ReSharper disable RedundantTypeDeclarationBody -// ReSharper disable UnusedAutoPropertyAccessor.Global -// ReSharper disable UnusedMember.Global -// ReSharper disable UnusedType.Global - -namespace JetBrains.Annotations; - -/// -/// Tells the code analysis engine if the parameter is completely handled when the invoked method is on stack. -/// If the parameter is a delegate, indicates that the delegate can only be invoked during method execution -/// (the delegate can be invoked zero or multiple times, but not stored to some field and invoked later, -/// when the containing method is no longer on the execution stack). -/// If the parameter is an enumerable, indicates that it is enumerated while the method is executed. -/// If is true, the attribute will only take effect if the method invocation is located under the 'await' expression. -/// -[AttributeUsage(AttributeTargets.Parameter)] -[Conditional("JETBRAINS_ANNOTATIONS")] -internal sealed class InstantHandleAttribute : Attribute -{ - /// - /// Require the method invocation to be used under the 'await' expression for this attribute to take effect on the code analysis engine. - /// Can be used for delegate/enumerable parameters of 'async' methods. - /// - public bool RequireAwait { get; set; } -} - -/// -/// Indicates that the method is a pure LINQ method, with postponed enumeration (like Enumerable.Select, -/// .Where). This annotation allows inference of [InstantHandle] annotation for parameters -/// of delegate type by analyzing LINQ method chains. -/// -[AttributeUsage(AttributeTargets.Method)] -[Conditional("JETBRAINS_ANNOTATIONS")] -internal sealed class LinqTunnelAttribute : Attribute { } +// MIT License +// +// Copyright (c) 2016 JetBrains http://www.jetbrains.com +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#nullable disable + +#pragma warning disable 1591 + +// ReSharper disable CheckNamespace +// ReSharper disable ConvertToPrimaryConstructor +// ReSharper disable InconsistentNaming +// ReSharper disable IntroduceOptionalParameters.Global +// ReSharper disable MemberCanBePrivate.Global +// ReSharper disable MemberCanBeProtected.Global +// ReSharper disable RedundantTypeDeclarationBody +// ReSharper disable UnusedAutoPropertyAccessor.Global +// ReSharper disable UnusedMember.Global +// ReSharper disable UnusedType.Global + +namespace JetBrains.Annotations; + +/// +/// Tells the code analysis engine if the parameter is completely handled when the invoked method is on stack. +/// If the parameter is a delegate, indicates that the delegate can only be invoked during method execution +/// (the delegate can be invoked zero or multiple times, but not stored to some field and invoked later, +/// when the containing method is no longer on the execution stack). +/// If the parameter is an enumerable, indicates that it is enumerated while the method is executed. +/// If is true, the attribute will only take effect if the method invocation is located under the 'await' expression. +/// +[AttributeUsage(AttributeTargets.Parameter)] +[Conditional("JETBRAINS_ANNOTATIONS")] +internal sealed class InstantHandleAttribute : Attribute +{ + /// + /// Require the method invocation to be used under the 'await' expression for this attribute to take effect on the code analysis engine. + /// Can be used for delegate/enumerable parameters of 'async' methods. + /// + public bool RequireAwait { get; set; } +} + +/// +/// Indicates that the method is a pure LINQ method, with postponed enumeration (like Enumerable.Select, +/// .Where). This annotation allows inference of [InstantHandle] annotation for parameters +/// of delegate type by analyzing LINQ method chains. +/// +[AttributeUsage(AttributeTargets.Method)] +[Conditional("JETBRAINS_ANNOTATIONS")] +internal sealed class LinqTunnelAttribute : Attribute { } diff --git a/Ramstack.Structures/Internal/JitHelpers.cs b/Ramstack.Structures/Internal/JitHelpers.cs index f664a93..cf36ef1 100644 --- a/Ramstack.Structures/Internal/JitHelpers.cs +++ b/Ramstack.Structures/Internal/JitHelpers.cs @@ -1,36 +1,36 @@ -namespace Ramstack.Internal; - -/// -/// Provides JIT helper methods. -/// -internal static class JitHelpers -{ - /// - /// Returns the reference to the first character of the specified string. - /// - /// The string instance. - /// The zero-based index of the element to get. - /// - /// The reference to the first character. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ref readonly char GetRawStringData(this string text, int index) => - ref Unsafe.Add(ref Unsafe.AsRef(in text.GetPinnableReference()), (nint)(uint)index); - - /// - /// Returns the reference to an element at the specified index. - /// - /// The type of array elements. - /// The array instance. - /// The zero-based index of the element to get. - /// - /// The reference to an element at the specified index. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ref T GetRawArrayData(this T[] array, int index) - { - // It's valid for a ref to point just past the end of an array, and it'll - // be properly GC-tracked. (Though dereferencing it may result in undefined behavior) - return ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)index); - } -} +namespace Ramstack.Internal; + +/// +/// Provides JIT helper methods. +/// +internal static class JitHelpers +{ + /// + /// Returns the reference to the first character of the specified string. + /// + /// The string instance. + /// The zero-based index of the element to get. + /// + /// The reference to the first character. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref readonly char GetRawStringData(this string text, int index) => + ref Unsafe.Add(ref Unsafe.AsRef(in text.GetPinnableReference()), (nint)(uint)index); + + /// + /// Returns the reference to an element at the specified index. + /// + /// The type of array elements. + /// The array instance. + /// The zero-based index of the element to get. + /// + /// The reference to an element at the specified index. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T GetRawArrayData(this T[] array, int index) + { + // It's valid for a ref to point just past the end of an array, and it'll + // be properly GC-tracked. (Though dereferencing it may result in undefined behavior) + return ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)index); + } +} diff --git a/Ramstack.Structures/Internal/ListAccessor.cs b/Ramstack.Structures/Internal/ListAccessor.cs index 15d4b89..9fb0e11 100644 --- a/Ramstack.Structures/Internal/ListAccessor.cs +++ b/Ramstack.Structures/Internal/ListAccessor.cs @@ -1,33 +1,33 @@ -#if NET9_0_OR_GREATER - -namespace Ramstack.Internal; - -/// -/// Provides low-level access to the internal array buffer of a . -/// -/// The type of the elements in the list. -internal static class ListAccessor -{ - /// - /// Returns a reference to the internal array buffer of the specified . - /// - /// The list whose internal buffer is to be accessed. - /// - /// A reference to the internal array used by the list. - /// - [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_items")] - public static extern ref T[] GetArray(List list); - - /// - /// Returns a reference to the internal "_size" field of the specified - /// representing the number of elements in the list. - /// - /// The list whose internal "_size" field is to be accessed. - /// - /// A reference to the internal "_size" field representing the number of elements in the list. - /// - [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_size")] - public static extern ref int GetCount(List list); -} - -#endif +#if NET9_0_OR_GREATER + +namespace Ramstack.Internal; + +/// +/// Provides low-level access to the internal array buffer of a . +/// +/// The type of the elements in the list. +internal static class ListAccessor +{ + /// + /// Returns a reference to the internal array buffer of the specified . + /// + /// The list whose internal buffer is to be accessed. + /// + /// A reference to the internal array used by the list. + /// + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_items")] + public static extern ref T[] GetArray(List list); + + /// + /// Returns a reference to the internal "_size" field of the specified + /// representing the number of elements in the list. + /// + /// The list whose internal "_size" field is to be accessed. + /// + /// A reference to the internal "_size" field representing the number of elements in the list. + /// + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_size")] + public static extern ref int GetCount(List list); +} + +#endif diff --git a/Ramstack.Structures/Internal/ThrowHelper.cs b/Ramstack.Structures/Internal/ThrowHelper.cs index b1ee41f..4a12824 100644 --- a/Ramstack.Structures/Internal/ThrowHelper.cs +++ b/Ramstack.Structures/Internal/ThrowHelper.cs @@ -1,21 +1,21 @@ -namespace Ramstack.Internal; - -/// -/// Provides helper methods for throwing exceptions. -/// -internal static class ThrowHelper -{ - /// - /// Throws an . - /// - [DoesNotReturn] - public static void ThrowArgumentOutOfRangeException() => - throw new ArgumentOutOfRangeException(); - - /// - /// Throws a . - /// - [DoesNotReturn] - public static void ThrowNotSupportedException() => - throw new NotSupportedException(); -} +namespace Ramstack.Internal; + +/// +/// Provides helper methods for throwing exceptions. +/// +internal static class ThrowHelper +{ + /// + /// Throws an . + /// + [DoesNotReturn] + public static void ThrowArgumentOutOfRangeException() => + throw new ArgumentOutOfRangeException(); + + /// + /// Throws a . + /// + [DoesNotReturn] + public static void ThrowNotSupportedException() => + throw new NotSupportedException(); +} diff --git a/Ramstack.Structures/InteropServices/MemoryMarshalExtensions.cs b/Ramstack.Structures/InteropServices/MemoryMarshalExtensions.cs index 19502b3..3a8c57d 100644 --- a/Ramstack.Structures/InteropServices/MemoryMarshalExtensions.cs +++ b/Ramstack.Structures/InteropServices/MemoryMarshalExtensions.cs @@ -1,168 +1,168 @@ -using Ramstack.Collections; -using Ramstack.Text; - -namespace Ramstack.InteropServices; - -/// -/// Provides extension methods for the class. -/// -public static class MemoryMarshalExtensions -{ - extension(MemoryMarshal) - { - /// - /// Creates a new over a portion of the specified string - /// starting at a specified position to the end of the string. - /// - /// The string to create a view over. - /// The zero-based starting position of the view in the string. - /// - /// A representing the specified portion of the string. - /// - /// - /// This method should be used with caution as it doesn't perform argument validation. - /// The caller is responsible for ensuring: - /// - /// is not null. - /// is within the bounds of the string. - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static StringView CreateStringView(string value, int index) - { - Debug.Assert(value is not null); - Debug.Assert(value.AsSpan(index).Length == value.Length - index); - - return new StringView(value, index, value.Length - index, unused: 0); - } - - /// - /// Creates a new over a portion of the specified string - /// starting at a specified position for a specified number of characters. - /// - /// The string to create a view over. - /// The zero-based starting position of the view in the string. - /// The number of characters to include in the view. - /// - /// A representing the specified portion of the string. - /// - /// - /// This method should be used with caution as it doesn't perform argument validation. - /// The caller is responsible for ensuring: - /// - /// is not null. - /// is within the bounds of the string. - /// is valid for the specified index. - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static StringView CreateStringView(string value, int index, int length) - { - Debug.Assert(value is not null); - Debug.Assert(value.AsSpan(index, length).Length == length); - - return new StringView(value, index, length, unused: 0); - } - - /// - /// Creates a new over a portion of the specified array, - /// starting at a specified position to the end of the array. - /// - /// The type of elements in the array. - /// The array to create a view over. - /// The zero-based starting position of the view in the array. - /// - /// An representing the specified portion of the array. - /// - /// - /// This method should be used with caution as it doesn't perform argument validation. - /// The caller is responsible for ensuring: - /// - /// is not null. - /// is within the bounds of the array. - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ArrayView CreateArrayView(T[] array, int index) - { - Debug.Assert(array is not null); - Debug.Assert(array.AsSpan(index).Length == array.Length - index); - - return new ArrayView(array, index, array.Length - index, unused: 0); - } - - /// - /// Creates a new over a portion of the specified array - /// starting at a specified position for a specified number of elements. - /// - /// The type of elements in the array. - /// The array to create a view over. - /// The zero-based starting position of the view in the array. - /// The number of elements to include in the view. - /// - /// An representing the specified portion of the array. - /// - /// - /// This method should be used with caution as it doesn't perform argument validation. - /// The caller is responsible for ensuring: - /// - /// is not null. - /// is within the bounds of the array. - /// is valid for the specified index. - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ArrayView CreateArrayView(T[] array, int index, int length) - { - Debug.Assert(array is not null); - Debug.Assert(array.AsSpan(index, length).Length == length); - - return new ArrayView(array, index, length, unused: 0); - } - - /// - /// Attempts to get a from the underlying memory buffer. - /// - /// Read-only memory containing a block of characters. - /// When this method returns, contains the - /// retrieved from the underlying read-only memory buffer. - /// - /// if the method successfully retrieves the underlying string; - /// otherwise, . - /// - public static bool TryGetStringView(ReadOnlyMemory memory, out StringView view) - { - if (MemoryMarshal.TryGetString(memory, out var value, out var start, out var length)) - { - view = new StringView(value, start, length, unused: 0); - return true; - } - - view = default; - return false; - } - - /// - /// Attempts to get a from the underlying memory buffer. - /// - /// The type of elements in the read-only memory buffer. - /// Read-only memory buffer. - /// When this method returns, contains the - /// retrieved from the underlying read-only memory buffer. - /// - /// if the underlying memory buffer represents an array segment; - /// otherwise, . - /// - public static bool TryGetArrayView(ReadOnlyMemory memory, out ArrayView view) - { - if (MemoryMarshal.TryGetArray(memory, out var segment)) - { - view = segment; - return true; - } - - view = default; - return false; - } - } -} +using Ramstack.Collections; +using Ramstack.Text; + +namespace Ramstack.InteropServices; + +/// +/// Provides extension methods for the class. +/// +public static class MemoryMarshalExtensions +{ + extension(MemoryMarshal) + { + /// + /// Creates a new over a portion of the specified string + /// starting at a specified position to the end of the string. + /// + /// The string to create a view over. + /// The zero-based starting position of the view in the string. + /// + /// A representing the specified portion of the string. + /// + /// + /// This method should be used with caution as it doesn't perform argument validation. + /// The caller is responsible for ensuring: + /// + /// is not null. + /// is within the bounds of the string. + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static StringView CreateStringView(string value, int index) + { + Debug.Assert(value is not null); + Debug.Assert(value.AsSpan(index).Length == value.Length - index); + + return new StringView(value, index, value.Length - index, unused: 0); + } + + /// + /// Creates a new over a portion of the specified string + /// starting at a specified position for a specified number of characters. + /// + /// The string to create a view over. + /// The zero-based starting position of the view in the string. + /// The number of characters to include in the view. + /// + /// A representing the specified portion of the string. + /// + /// + /// This method should be used with caution as it doesn't perform argument validation. + /// The caller is responsible for ensuring: + /// + /// is not null. + /// is within the bounds of the string. + /// is valid for the specified index. + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static StringView CreateStringView(string value, int index, int length) + { + Debug.Assert(value is not null); + Debug.Assert(value.AsSpan(index, length).Length == length); + + return new StringView(value, index, length, unused: 0); + } + + /// + /// Creates a new over a portion of the specified array, + /// starting at a specified position to the end of the array. + /// + /// The type of elements in the array. + /// The array to create a view over. + /// The zero-based starting position of the view in the array. + /// + /// An representing the specified portion of the array. + /// + /// + /// This method should be used with caution as it doesn't perform argument validation. + /// The caller is responsible for ensuring: + /// + /// is not null. + /// is within the bounds of the array. + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ArrayView CreateArrayView(T[] array, int index) + { + Debug.Assert(array is not null); + Debug.Assert(array.AsSpan(index).Length == array.Length - index); + + return new ArrayView(array, index, array.Length - index, unused: 0); + } + + /// + /// Creates a new over a portion of the specified array + /// starting at a specified position for a specified number of elements. + /// + /// The type of elements in the array. + /// The array to create a view over. + /// The zero-based starting position of the view in the array. + /// The number of elements to include in the view. + /// + /// An representing the specified portion of the array. + /// + /// + /// This method should be used with caution as it doesn't perform argument validation. + /// The caller is responsible for ensuring: + /// + /// is not null. + /// is within the bounds of the array. + /// is valid for the specified index. + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ArrayView CreateArrayView(T[] array, int index, int length) + { + Debug.Assert(array is not null); + Debug.Assert(array.AsSpan(index, length).Length == length); + + return new ArrayView(array, index, length, unused: 0); + } + + /// + /// Attempts to get a from the underlying memory buffer. + /// + /// Read-only memory containing a block of characters. + /// When this method returns, contains the + /// retrieved from the underlying read-only memory buffer. + /// + /// if the method successfully retrieves the underlying string; + /// otherwise, . + /// + public static bool TryGetStringView(ReadOnlyMemory memory, out StringView view) + { + if (MemoryMarshal.TryGetString(memory, out var value, out var start, out var length)) + { + view = new StringView(value, start, length, unused: 0); + return true; + } + + view = default; + return false; + } + + /// + /// Attempts to get a from the underlying memory buffer. + /// + /// The type of elements in the read-only memory buffer. + /// Read-only memory buffer. + /// When this method returns, contains the + /// retrieved from the underlying read-only memory buffer. + /// + /// if the underlying memory buffer represents an array segment; + /// otherwise, . + /// + public static bool TryGetArrayView(ReadOnlyMemory memory, out ArrayView view) + { + if (MemoryMarshal.TryGetArray(memory, out var segment)) + { + view = segment; + return true; + } + + view = default; + return false; + } + } +} diff --git a/Ramstack.Structures/Properties/AssemblyInfo.cs b/Ramstack.Structures/Properties/AssemblyInfo.cs index 63851e9..8fc4963 100644 --- a/Ramstack.Structures/Properties/AssemblyInfo.cs +++ b/Ramstack.Structures/Properties/AssemblyInfo.cs @@ -1,32 +1,32 @@ -// ReSharper disable UnusedMember.Global - -[module: System.Runtime.CompilerServices.SkipLocalsInit] - -#if !NET8_0_OR_GREATER - -// ReSharper disable once CheckNamespace -namespace System.Runtime.CompilerServices -{ - /// - /// The type of the builder to use to construct the collection. - /// The name of the method on the builder to use to construct the collection. - [AttributeUsage( - AttributeTargets.Class - | AttributeTargets.Struct - | AttributeTargets.Interface, - Inherited = false)] - internal sealed class CollectionBuilderAttribute(Type builderType, string methodName) : Attribute - { - /// - /// Gets the type of the builder to use to construct the collection. - /// - public Type BuilderType => builderType; - - /// - /// Gets the name of the method on the builder to use to construct the collection. - /// - public string MethodName => methodName; - } -} - -#endif +// ReSharper disable UnusedMember.Global + +[module: System.Runtime.CompilerServices.SkipLocalsInit] + +#if !NET8_0_OR_GREATER + +// ReSharper disable once CheckNamespace +namespace System.Runtime.CompilerServices +{ + /// + /// The type of the builder to use to construct the collection. + /// The name of the method on the builder to use to construct the collection. + [AttributeUsage( + AttributeTargets.Class + | AttributeTargets.Struct + | AttributeTargets.Interface, + Inherited = false)] + internal sealed class CollectionBuilderAttribute(Type builderType, string methodName) : Attribute + { + /// + /// Gets the type of the builder to use to construct the collection. + /// + public Type BuilderType => builderType; + + /// + /// Gets the name of the method on the builder to use to construct the collection. + /// + public string MethodName => methodName; + } +} + +#endif diff --git a/Ramstack.Structures/Ramstack.Structures.csproj b/Ramstack.Structures/Ramstack.Structures.csproj index b74071e..26ad850 100644 --- a/Ramstack.Structures/Ramstack.Structures.csproj +++ b/Ramstack.Structures/Ramstack.Structures.csproj @@ -1,74 +1,69 @@ - - - net6.0;net8.0;net9.0 - Provides various data structures and utilities. - -Includes three primary types: -Ramstack.Text.StringView -Ramstack.Collections.ArrayView<T> -Ramstack.Collections.ReadOnlyArray<T> - enable - enable - preview - true - true - Ramstack - - - - 649;1591 - CS8600;CS8601;CS8602;CS8603;CS8604;CS8610;CS8613;CS8614;CS8618;CS8619;CS8620;CS8625;CS8643;CS8653;CS8714 - - - - https://github.com/rameel/ramstack.structures - Rameel - collections;arrayview;stringview;readonlyarray;immutablearray - https://github.com/rameel/ramstack.structures#readme - README.md - MIT - true - snupkg - true - true - true - true - - - - true - - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - True - \ - - - - + + + net6.0;net8.0;net9.0 + Provides various data structures and utilities. + +Includes three primary types: +Ramstack.Text.StringView +Ramstack.Collections.ArrayView<T> +Ramstack.Collections.ReadOnlyArray<T> + enable + enable + preview + true + true + Ramstack + + + + https://github.com/rameel/ramstack.structures + Rameel + collections;arrayview;stringview;readonlyarray;immutablearray + https://github.com/rameel/ramstack.structures#readme + README.md + MIT + true + snupkg + true + true + true + true + + + + true + + + + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + True + \ + + + + diff --git a/Ramstack.Structures/Text/StringView.cs b/Ramstack.Structures/Text/StringView.cs index 7b15aa5..a98514b 100644 --- a/Ramstack.Structures/Text/StringView.cs +++ b/Ramstack.Structures/Text/StringView.cs @@ -1,1313 +1,1315 @@ -namespace Ramstack.Text; - -/// -/// Represents a read-only view of a string, providing safe and efficient access to a subset of its characters. -/// -[DebuggerDisplay("{ToStringDebugger(),nq}")] -public readonly struct StringView : IReadOnlyList, IComparable, IComparable, IEquatable, IEquatable -{ - private readonly string? _value; - private readonly int _index; - private readonly int _length; - - /// - /// Gets the empty string view. - /// - public static StringView Empty => default; - - /// - /// Gets the number of characters in the current object. - /// - public int Length => _length; - - /// - /// Gets a value indicating whether the was declared but not initialized. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public bool IsDefault => _value is null; - - /// - public char this[int index] - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - if ((uint)index >= (uint)_length) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - return _value!.GetRawStringData(_index + index); - } - } - - /// - /// Initializes a new instance of the structure that creates a view - /// for the all characters in the specified string. - /// - /// The string to wrap. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public StringView(string value) - { - _length = value.Length; - _value = value; - } - - /// - /// Initializes a new instance of the structure that creates - /// a view for the specified range of the characters in the specified string. - /// - /// The string to wrap. - /// The zero-based starting position of the view in the string. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public StringView(string value, int index) - { - if ((uint)index > (uint)value.Length) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - _index = index; - _length = value.Length - index; - _value = value; - } - - /// - /// Initializes a new instance of the structure that creates - /// a view for the specified range of the characters in the specified string. - /// - /// The string to wrap. - /// The zero-based starting position of the view in the string. - /// The number of characters to include in the view. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public StringView(string value, int index, int length) - { - if ((uint)index > (uint)value.Length || (uint)length > (uint)(value.Length - index)) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - _index = index; - _length = length; - _value = value; - } - - /// - /// Initializes a new instance of the structure that creates - /// a view for the specified range of the characters in the specified string. - /// - /// - /// This constructor is intentionally minimal and skips all argument validations, - /// as the caller is responsible for ensuring correctness (e.g., - /// is non-null, and - /// are within bounds). - /// - /// The string to wrap. - /// The zero-based starting position of the view in the string. - /// The number of characters to include in the view. - /// Unused parameter used only to differentiate between overloads. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal StringView(string value, int index, int length, int unused) - { - _index = index; - _length = length; - _value = value; - _ = unused; - } - - /// - public Enumerator GetEnumerator() => - new(this); - - /// - /// Returns a substring from the current string view starting at the specified index. - /// - /// - /// This method is a synonym for the method. - /// - /// The index at which to begin the substring. - /// - /// A string view that consists of all characters of the current string view - /// from to the end of the string view. - /// - public StringView Substring(int start) => - Slice(start); - - /// - /// Returns a substring of the specified length out of the current string view - /// starting at the specified index. - /// - /// - /// This method is a synonym for the method. - /// - /// The index at which to begin the substring. - /// The length of the substring. - /// - /// A string view of characters starting at . - /// - public StringView Substring(int start, int length) => - Slice(start, length); - - /// - /// Forms a slice out of the current string view starting at the specified index. - /// - /// The index at which to begin the slice. - /// - /// A string view that consists of all characters of the current string view - /// from to the end of the string view. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public StringView Slice(int start) - { - if ((uint)start > (uint)_length) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - return new StringView(_value!, _index + start, _length - start, unused: 0); - } - - /// - /// Forms a slice of the specified length out of the current string view - /// starting at the specified index. - /// - /// The index at which to begin the slice. - /// The length of the slice. - /// - /// A string view of characters starting at . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public StringView Slice(int start, int length) - { - if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) - ThrowHelper.ThrowArgumentOutOfRangeException(); - - return new StringView(_value!, _index + start, length, unused: 0); - } - - /// - /// Determines whether this instance starts with the specified character. - /// - /// The character to compare. - /// - /// if parameter matches - /// the beginning of this instance; otherwise, . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool StartsWith(char value) => - _length != 0 && _value!.GetRawStringData(_index) == value; - - /// - /// Determines whether the end of this instance matches the specified character. - /// - /// The character to compare. - /// - /// if matches - /// the end of this instance; otherwise, . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool EndsWith(char value) => - _length != 0 && _value!.GetRawStringData(_index + _length - 1) == value; - - /// - /// Determines whether the beginning of this instance matches the specified value - /// when compared using the specified comparison option. - /// - /// The value to compare. - /// One of the enumeration values that determines - /// how this instance and are compared. - /// The default value is . - /// - /// if this instance begins with parameter; - /// otherwise, . - /// - public bool StartsWith(ReadOnlySpan value, StringComparison comparisonType = StringComparison.CurrentCulture) => - AsSpan().StartsWith(value, comparisonType); - - /// - /// Determines whether the end of this instance matches the specified value - /// when compared using the specified comparison option. - /// - /// The value to compare. - /// One of the enumeration values that determines - /// how this instance and are compared. - /// The default value is . - /// - /// if parameter matches - /// the end of this instance; otherwise, . - /// - public bool EndsWith(ReadOnlySpan value, StringComparison comparisonType = StringComparison.CurrentCulture) => - AsSpan().EndsWith(value, comparisonType); - - /// - /// Removes all leading whitespace characters from the current instance. - /// - /// - /// The trimmed . - /// - public StringView TrimStart() - { - var start = _index; - var final = _index + _length; - var value = _value; - - if (value is not null) - for (; start < final; start++) - if (!char.IsWhiteSpace(value.GetRawStringData(start))) - break; - - return new StringView(value!, start, final - start, unused: 0); - } - - /// - /// Removes all leading occurrences of a specified character from the current instance. - /// - /// The specified character to look for and remove. - /// - /// The trimmed . - /// - public StringView TrimStart(char trimChar) - { - var start = _index; - var final = _index + _length; - var value = _value; - - if (value is not null) - for (; start < final; start++) - if (value.GetRawStringData(start) != trimChar) - break; - - return new StringView(value!, start, final - start, unused: 0); - } - - /// - /// Removes all leading occurrences of a set of characters specified - /// in an array from the current instance. - /// - /// - /// If is or an empty array, - /// whitespace characters are removed instead. - /// - /// An array which contains a set of characters to remove. - /// - /// The trimmed . - /// - public StringView TrimStart(params char[]? trimChars) => - TrimStart(trimChars.AsSpan()); - - /// - /// Removes all leading occurrences of a set of characters specified - /// in a read-only span from the current instance. - /// - /// - /// If is empty, whitespace characters are removed instead. - /// - /// A read-only span which contains a set of characters to remove. - /// - /// The trimmed . - /// - public StringView TrimStart(params ReadOnlySpan trimChars) - { - if (trimChars.Length == 0) - return TrimStart(); - - var start = _index; - var final = _index + _length; - var value = _value; - - if (value is not null) - { - for (; start < final; start++) - { - var ch = value.GetRawStringData(start); - - foreach (var trimChar in trimChars) - if (ch == trimChar) - goto MATCHED; - - break; - MATCHED: ; - } - } - - return new StringView(value!, start, final - start, unused: 0); - } - - /// - /// Removes all trailing whitespace characters from the current instance. - /// - /// - /// The trimmed . - /// - public StringView TrimEnd() - { - var start = _index; - var final = _index + _length - 1; - var value = _value; - - if (value is not null) - for (; final >= start; final--) - if (!char.IsWhiteSpace(value.GetRawStringData(final))) - break; - - return new StringView(value!, start, final + 1 - start, unused: 0); - } - - /// - /// Removes all trailing occurrences of a specified character from the current instance. - /// - /// The specified character to look for and remove. - /// - /// The trimmed . - /// - public StringView TrimEnd(char trimChar) - { - var start = _index; - var final = _index + _length - 1; - var value = _value; - - if (value is not null) - for (; final >= start; final--) - if (value.GetRawStringData(final) != trimChar) - break; - - return new StringView(value!, start, final + 1 - start, unused: 0); - } - - /// - /// Removes all trailing occurrences of a set of characters specified - /// in an array from the current instance. - /// - /// - /// If is or an empty array, - /// whitespace characters are removed instead. - /// - /// An array which contains a set of characters to remove. - /// - /// The trimmed . - /// - public StringView TrimEnd(params char[]? trimChars) => - TrimEnd(trimChars.AsSpan()); - - /// - /// Removes all leading occurrences of a set of characters specified - /// in a read-only span from the current instance. - /// - /// - /// If is empty, whitespace characters are removed instead. - /// - /// A read-only span which contains a set of characters to remove. - /// - /// The trimmed . - /// - public StringView TrimEnd(params ReadOnlySpan trimChars) - { - if (trimChars.Length == 0) - return TrimEnd(); - - var start = _index; - var final = _index + _length - 1; - var value = _value; - - if (value is not null) - { - for (; final >= start; final--) - { - var ch = value.GetRawStringData(final); - - foreach (var trimChar in trimChars) - if (ch == trimChar) - goto MATCHED; - - break; - MATCHED: ; - } - } - - return new StringView(value!, start, final + 1 - start, unused: 0); - } - - /// - /// Removes all leading and trailing whitespace characters from the current instance. - /// - /// - /// The trimmed . - /// - public StringView Trim() - { - var start = _index; - var final = _index + _length - 1; - var value = _value; - - if (value is not null) - { - for (; start <= final; start++) - if (!char.IsWhiteSpace(value.GetRawStringData(start))) - break; - - for (; final > start; final--) - if (!char.IsWhiteSpace(value.GetRawStringData(final))) - break; - } - - return new StringView(value!, start, final + 1 - start, unused: 0); - } - - /// - /// Removes all leading and trailing occurrences of a specified character from the current instance. - /// - /// The specified character to look for and remove. - /// - /// The trimmed . - /// - public StringView Trim(char trimChar) - { - var start = _index; - var final = _index + _length - 1; - var value = _value; - - if (value is not null) - { - for (; start <= final; start++) - if (value.GetRawStringData(start) != trimChar) - break; - - for (; final > start; final--) - if (value.GetRawStringData(final) != trimChar) - break; - } - - return new StringView(value!, start, final + 1 - start, unused: 0); - } - - /// - /// Removes all leading and trailing occurrences of a set of characters - /// specified in an array from the current instance. - /// - /// - /// If is or an empty array, - /// whitespace characters are removed instead. - /// - /// An array which contains a set of characters to remove. - /// - /// The trimmed . - /// - public StringView Trim(params char[]? trimChars) => - Trim(trimChars.AsSpan()); - - /// - /// Removes all leading and trailing occurrences of a set of characters specified - /// in a read-only span from the current instance. - /// - /// - /// If is empty, whitespace characters are removed instead. - /// - /// A read-only span which contains a set of characters to remove. - /// - /// The trimmed . - /// - public StringView Trim(params ReadOnlySpan trimChars) - { - if (trimChars.Length == 0) - return Trim(); - - var start = _index; - var final = _index + _length - 1; - var value = _value; - - if (value is not null) - { - for (; start <= final; start++) - { - var ch = value.GetRawStringData(start); - - foreach (var trimChar in trimChars) - if (ch == trimChar) - goto MATCHED; - - break; - MATCHED: ; - } - - for (; final > start; final--) - { - var ch = value.GetRawStringData(final); - - foreach (var trimChar in trimChars) - if (ch == trimChar) - goto MATCHED; - - break; - MATCHED: ; - } - } - - return new StringView(value!, start, final + 1 - start, unused: 0); - } - - /// - /// Reports the zero-based index of the first occurrence of the specified Unicode character in this instance. - /// - /// A Unicode character to seek. - /// - /// The zero-based index position of if that character is found, - /// or -1 if it is not. - /// - public int IndexOf(char value) => - AsSpan().IndexOf(value); - - /// - /// Reports the zero-based index of the first occurrence of the specified character sequence - /// in this instance. - /// - /// The sequence of characters to search. - /// - /// The zero-based index position of if that sequence is found, - /// or -1 if it is not. - /// - public int IndexOf(ReadOnlySpan value) => - AsSpan().IndexOf(value); - - /// - /// Reports the zero-based index of the last occurrence of the specified character sequence - /// in this instance. A parameter specifies the type of search - /// to use for the specified character sequence. - /// - /// The sequence of characters to search. - /// An enumeration value that specifies the rules for the search. - /// - /// The zero-based index position of if that sequence is found, - /// or -1 if it is not. - /// - public int IndexOf(ReadOnlySpan value, StringComparison comparisonType) => - AsSpan().IndexOf(value, comparisonType); - - /// - /// Reports the zero-based index of the last occurrence of the specified Unicode character - /// in this instance. - /// - /// A Unicode character to seek. - /// - /// The zero-based index position of if that character is found, - /// or -1 if it is not. - /// - public int LastIndexOf(char value) => - AsSpan().LastIndexOf(value); - - /// - /// Reports the zero-based index of the last occurrence of the specified character sequence - /// in this instance. - /// - /// The sequence of characters to search. - /// - /// The zero-based index position of if that sequence is found, - /// or -1 if it is not. - /// - public int LastIndexOf(ReadOnlySpan value) => - AsSpan().LastIndexOf(value); - - /// - /// Reports the zero-based index of the last occurrence of the specified character sequence - /// in this instance. A parameter specifies the type of search to use - /// for the specified character sequence. - /// - /// The sequence of characters to search. - /// An enumeration value that specifies the rules for the search. - /// - /// The zero-based index position of if that sequence is found, - /// or -1 if it is not. - /// - public int LastIndexOf(ReadOnlySpan value, StringComparison comparisonType) => - AsSpan().LastIndexOf(value, comparisonType); - - /// - /// Returns a value indicating whether a specified character occurs within this instance. - /// - /// A Unicode character to seek. - /// - /// if the parameter occurs within this instance; - /// otherwise, . - /// - public bool Contains(char value) => - AsSpan().Contains(value); - - /// - /// Returns a value indicating whether a specified character sequence occurs within this instance. - /// - /// The sequence of characters to seek. - /// - /// if the parameter occurs within this instance; - /// otherwise, . - /// - public bool Contains(ReadOnlySpan value) => - AsSpan().IndexOf(value) >= 0; - - /// - /// Reports the zero-based index of the first occurrence of the specified character sequence - /// in this instance, using the specified comparison rules. - /// - /// The sequence of characters to search. - /// An enumeration value that specifies the rules for the search. - /// - /// if the parameter occurs within this instance; - /// otherwise, . - /// - public bool Contains(ReadOnlySpan value, StringComparison comparisonType) => - AsSpan().Contains(value, comparisonType); - - /// - public int CompareTo(StringView other) => - Compare(this, other, StringComparison.CurrentCulture); - - /// - /// Compares one view with a readonly span, and returns an integer - /// that indicates their relative position in the sort order. - /// - /// An object to compare with this instance. - /// - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, this instance precedes than . - /// - If 0, this instance equals . - /// - If greater than 0, this instance follows . - /// - public int CompareTo(ReadOnlySpan other) => - Compare(this, other, StringComparison.CurrentCulture); - - /// - public int CompareTo(string? other) => - Compare(this, other, StringComparison.CurrentCulture); - - /// - /// Compares one view with another using a specified string comparison, - /// and returns an integer that indicates their relative position in the sort order. - /// - /// The view to compare with the current instance. - /// An enumeration value that determines - /// how current view and other are compared. - /// - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, this instance precedes than . - /// - If 0, this instance equals . - /// - If greater than 0, this instance follows . - /// - public int CompareTo(StringView other, StringComparison comparisonType) => - Compare(this, other, comparisonType); - - /// - /// Compares one view with a readonly span using a specified string comparison, - /// and returns an integer that indicates their relative position in the sort order. - /// - /// The view to compare with the current instance. - /// An enumeration value that determines - /// how current view and other are compared. - /// - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, this instance precedes than . - /// - If 0, this instance equals . - /// - If greater than 0, this instance follows . - /// - public int CompareTo(ReadOnlySpan other, StringComparison comparisonType) => - Compare(this, other, comparisonType); - - /// - /// Compares one view with a string using a specified string comparison, - /// and returns an integer that indicates their relative position in the sort order. - /// - /// The view to compare with the current instance. - /// An enumeration value that determines - /// how current view and other are compared. - /// - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, this instance precedes than . - /// - If 0, this instance equals . - /// - If greater than 0, this instance follows . - /// - public int CompareTo(string? other, StringComparison comparisonType) => - Compare(this, other, comparisonType); - - /// - public override bool Equals([NotNullWhen(true)] object? obj) - { - if (obj is null) - return _length == 0; - - if (obj is StringView view) - return Equals(this, view); - - return obj is string s && Equals(s); - } - - /// - public bool Equals(StringView other) => - Equals(this, other); - - /// - /// Indicates whether the current object is equal to a specified readonly span. - /// - /// An object to compare with this object. - /// - /// if the current object is equal to the parameter; - /// otherwise, . - /// - public bool Equals(ReadOnlySpan other) => - Equals(this, other); - - /// - public bool Equals(string? other) => - Equals(this, other); - - /// - /// Determines whether this view and the specified other view have the same characters - /// when compared using the specified option. - /// - /// The value to compare with the current instance. - /// An enumeration value that determines - /// how current instance and are compared. - /// - /// true if equal, false otherwise. - /// - public bool Equals(StringView other, StringComparison comparisonType) => - Equals(this, other, comparisonType); - - /// - /// Determines whether this view and the specified readonly span have the same characters - /// when compared using the specified option. - /// - /// The value to compare with the current instance. - /// An enumeration value that determines - /// how current instance and are compared. - /// - /// true if equal, false otherwise. - /// - public bool Equals(ReadOnlySpan other, StringComparison comparisonType) => - Equals(this, other, comparisonType); - - /// - /// Determines whether this view and the specified other view have the same characters - /// when compared using the specified option. - /// - /// The value to compare with the current instance. - /// An enumeration value that determines - /// how current instance and are compared. - /// - /// true if equal, false otherwise. - /// - public bool Equals(string? other, StringComparison comparisonType) => - Equals(this, other, comparisonType); - - /// - public override int GetHashCode() => - string.GetHashCode(AsSpan()); - - /// - /// Returns the hash code for this instance using the specified rules. - /// - /// One of the enumeration values - /// that specifies the rules to use in the comparison. - /// - /// A 32-bit signed integer hash code. - /// - public int GetHashCode(StringComparison comparisonType) => - string.GetHashCode(AsSpan(), comparisonType); - - /// - /// Copies the contents of this string view into a new string. - /// - /// - /// A string containing the data in the current string view. - /// - public override string ToString() - { - var value = _value ?? ""; - if (_length == value.Length && _index == 0) - return value; - - return new string( - MemoryMarshal.CreateReadOnlySpan( - ref Unsafe.AsRef(in value.GetRawStringData(_index)), - _length)); - } - - /// - /// Copies the contents of this string view into a new array. - /// - /// - /// An array containing the data in the current string view. - /// - public char[] ToArray() => - ((ReadOnlySpan)this).ToArray(); - - /// - /// Returns a read-only span over the current string view. - /// - /// - /// The read-only span representation of the string view. - /// - public ReadOnlySpan AsSpan() => - this; - - /// - /// Returns a read-only memory region over the current string view. - /// - /// - /// The read-only memory region over the string view. - /// - public ReadOnlyMemory AsMemory() => - this; - - /// - /// Returns a reference to the element of the at index zero. - /// - /// - /// A reference to the element of the at index zero, - /// or if is true. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ref readonly char GetPinnableReference() - { - // - // Normalize the returned reference. - // We must not return a reference to an element outside the bounds of our view - // when the view is empty (_count = 0), even if it points to a valid element - // in the underlying string. In this case, we return a null reference. - // - // Examples: - // - // Full string (_value): - // [0][1][2][3][4][5][6][7][8][9] - // |--------------------------| - // - // Case 1: Non-empty view (_index = 3, _count = 4) - // [3][4][5][6] - // ^ ^ - // |--------| <- valid range for this view - // - // Case 2: Empty view (_index = 3, _count = 0) - // [3][4][5][6] - // ^ - // | <- no valid reference for this view - // - - ref readonly var p = ref Unsafe.NullRef(); - - if (_length != 0) - p = ref _value!.GetRawStringData(_index); - - return ref p; - } - - /// - /// Copies the contents of this into a destination . - /// - /// The span to copy items into. - public void CopyTo(Span destination) => - AsSpan().CopyTo(destination); - - /// - /// Attempts to copy the contents of this into a destination - /// and returns a value to indicate whether the operation succeeded. - /// - /// The span to copy items into. - /// - /// if the copy operation succeeded; otherwise, . - /// - public bool TryCopyTo(Span destination) => - AsSpan().TryCopyTo(destination); - - /// - /// Determines whether two specified objects have the same value. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// if the value of is the same as the value - /// of ; otherwise, . - /// - public static bool Equals(StringView a, StringView b) => - a.AsSpan().SequenceEqual(b); - - /// - /// Determines whether two specified objects have the same value. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// if the value of is the same as the value - /// of ; otherwise, . - /// - public static bool Equals(StringView a, ReadOnlySpan b) => - a.AsSpan().SequenceEqual(b); - - /// - /// Determines whether two specified objects have the same value. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// if the value of is the same as the value - /// of ; otherwise, . - /// - public static bool Equals(StringView a, string? b) => - a.AsSpan().SequenceEqual(b); - - /// - /// Determines whether two specified objects have the same value - /// with the specified comparison rules. - /// - /// The first value to compare. - /// The second value to compare. - /// An enumeration value that determines how values are compared. - /// - /// if the value of the parameter - /// is equal to the value of parameter; - /// otherwise, . - /// - public static bool Equals(StringView a, StringView b, StringComparison comparison) => - a.AsSpan().Equals(b, comparison); - - /// - /// Determines whether two specified objects have the same value - /// with the specified comparison rules. - /// - /// The first value to compare. - /// The second value to compare. - /// An enumeration value that determines how values are compared. - /// - /// if the value of the parameter - /// is equal to the value of parameter; - /// otherwise, . - /// - public static bool Equals(StringView a, ReadOnlySpan b, StringComparison comparison) => - a.AsSpan().Equals(b, comparison); - - /// - /// Determines whether two specified objects have the same value - /// with the specified comparison rules. - /// - /// The first value to compare. - /// The second value to compare. - /// An enumeration value that determines how values are compared. - /// - /// if the value of the parameter - /// is equal to the value of parameter; - /// otherwise, . - /// - public static bool Equals(StringView a, string? b, StringComparison comparison) => - a.AsSpan().Equals(b, comparison); - - /// - /// Compares two specified objects and returns an integer - /// that indicates their relative position in the sort order. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, > precedes in the sort order. - /// - If 0, > equals . - /// - If greater than 0, > follows in the sort order. - /// - public static int CompareOrdinal(StringView a, StringView b) => - a.AsSpan().SequenceCompareTo(b); - - /// - /// Compares two specified objects and returns an integer - /// that indicates their relative position in the sort order. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, > precedes in the sort order. - /// - If 0, > equals . - /// - If greater than 0, > follows in the sort order. - /// - public static int CompareOrdinal(StringView a, ReadOnlySpan b) => - a.AsSpan().SequenceCompareTo(b); - - /// - /// Compares two specified objects and returns an integer - /// that indicates their relative position in the sort order. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, > precedes in the sort order. - /// - If 0, > equals . - /// - If greater than 0, > follows in the sort order. - /// - public static int CompareOrdinal(StringView a, string? b) => - a.AsSpan().SequenceCompareTo(b); - - /// - /// Compares two specified objects and returns an integer - /// that indicates their relative position in the sort order. - /// - /// The first value to compare. - /// The second value to compare. - /// One of the enumeration values - /// that specifies the rules to use in the comparison. - /// - /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, > precedes in the sort order. - /// - If 0, > equals . - /// - If greater than 0, > follows in the sort order. - /// - public static int Compare(StringView a, StringView b, StringComparison comparison) => - a.AsSpan().CompareTo(b, comparison); - - /// - /// Compares two specified objects and returns an integer - /// that indicates their relative position in the sort order. - /// - /// The first value to compare. - /// The second value to compare. - /// One of the enumeration values - /// that specifies the rules to use in the comparison. - /// - /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, > precedes in the sort order. - /// - If 0, > equals . - /// - If greater than 0, > follows in the sort order. - /// - public static int Compare(StringView a, ReadOnlySpan b, StringComparison comparison) => - a.AsSpan().CompareTo(b, comparison); - - /// - /// Compares two specified objects and returns an integer - /// that indicates their relative position in the sort order. - /// - /// The first value to compare. - /// The second value to compare. - /// One of the enumeration values - /// that specifies the rules to use in the comparison. - /// - /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. - /// A signed integer that indicates the relative order of view and other: - /// - If less than 0, > precedes in the sort order. - /// - If 0, > equals . - /// - If greater than 0, > follows in the sort order. - /// - public static int Compare(StringView a, string? b, StringComparison comparison) => - a.AsSpan().CompareTo(b, comparison); - - /// - /// Determines whether two instances are equal. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// if the two instances are equal; - /// otherwise, . - /// - public static bool operator ==(StringView a, StringView b) => - Equals(a, b); - - /// - /// Determines whether two instances are not equal. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// if the two instances are not equal; - /// otherwise, . - /// - public static bool operator !=(StringView a, StringView b) => - !Equals(a, b); - - /// - /// Determines whether two instances are equal. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// if the two instances are equal; - /// otherwise, . - /// - public static bool operator ==(StringView a, string? b) => - Equals(a, b); - - /// - /// Determines whether two instances are not equal. - /// - /// The first value to compare. - /// The second value to compare. - /// - /// if the two instances are not equal; - /// otherwise, . - /// - public static bool operator !=(StringView a, string? b) => - !Equals(a, b); - - /// - /// Defines an implicit conversion of a string view. - /// - /// The string to convert. - /// - /// A string view representation of the string. - /// - public static implicit operator StringView(string? value) => - new(value ?? ""); - - /// - /// Defines an implicit conversion of the to the . - /// - /// The to convert. - /// - /// A representation of the . - /// - public static implicit operator ReadOnlyMemory(StringView view) => - view._value.AsMemory(view._index, view._length); - - /// - /// Defines an implicit conversion of a string view to the . - /// - /// The string view to convert. - /// - /// A representation of the string view. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator ReadOnlySpan(StringView view) - { - var value = view._value ?? ""; - - return MemoryMarshal.CreateReadOnlySpan( - ref Unsafe.AsRef(in value.GetRawStringData(view._index)), - view._length); - } - - /// - /// Returns a string representation of the current instance's state, intended for debugging purposes. - /// - /// - /// A string containing information about the current instance. - /// - private string ToStringDebugger() => - _value is null ? "Uninitialized" : ToString(); - - #region IEnumerable implementation - - IEnumerator IEnumerable.GetEnumerator() => - new StringViewEnumerator(this); - - IEnumerator IEnumerable.GetEnumerator() => - new StringViewEnumerator(this); - - #endregion - - #region IReadOnlyCollection implementation - - int IReadOnlyCollection.Count => _length; - - #endregion - - #region IReadOnlyList implementation - - char IReadOnlyList.this[int index] => this[index]; - - #endregion - - #region Inner type: Enumerator - - /// - /// Provides the ability to iterate through the characters of the . - /// - public struct Enumerator - { - private readonly string? _value; - private int _index; - private readonly int _final; - private char _ch; - - /// - public readonly char Current => _ch; - - /// - /// Initializes a new instance of the structure. - /// - /// The to iterate through its characters. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal Enumerator(StringView view) - { - _index = view._index - 1; - _final = view._index + view._length; - _value = view._value; - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool MoveNext() - { - #if NET9_0_OR_GREATER - // - // The "_value is not null" condition is hoisted and checked only once - // - if (_value is not null && (uint)++_index < (uint)_final) - { - _ch = _value!.GetRawStringData(_index); - return true; - } - #else - if ((uint)++_index < (uint)_final) - { - _ch = _value!.GetRawStringData(_index); - return true; - } - #endif - - return false; - } - } - - #endregion - - #region Inner type: StringViewEnumerator - - /// - /// Provides the ability to iterate through the characters of the . - /// - private sealed class StringViewEnumerator : IEnumerator - { - private readonly string? _value; - private int _index; - private readonly int _final; - private char _ch; - - /// - public char Current => _ch; - - /// - /// Initializes a new instance of the class. - /// - /// The to iterate through its characters. - public StringViewEnumerator(StringView view) - { - _index = view._index - 1; - _final = view._index + view._length; - _value = view._value; - } - - /// - public bool MoveNext() - { - if ((uint)++_index < (uint)_final) - { - _ch = _value!.GetRawStringData(_index); - return true; - } - - return false; - } - - /// - public void Dispose() - { } - - /// - object IEnumerator.Current => Current; - - /// - void IEnumerator.Reset() => - ThrowHelper.ThrowNotSupportedException(); - } - - #endregion -} +namespace Ramstack.Text; + +/// +/// Represents a read-only view of a string, providing safe and efficient access to a subset of its characters. +/// +[DebuggerDisplay("{ToStringDebugger(),nq}")] +[SuppressMessage("Design", "CA1036:Override methods on comparable types", + Justification = "Like string, StringView provides ordering through the CompareTo and Compare methods instead of comparison operators.")] +public readonly struct StringView : IReadOnlyList, IComparable, IComparable, IEquatable, IEquatable +{ + private readonly string? _value; + private readonly int _index; + private readonly int _length; + + /// + /// Gets the empty string view. + /// + public static StringView Empty => default; + + /// + /// Gets the number of characters in the current object. + /// + public int Length => _length; + + /// + /// Gets a value indicating whether the was declared but not initialized. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public bool IsDefault => _value is null; + + /// + public char this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if ((uint)index >= (uint)_length) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return _value!.GetRawStringData(_index + index); + } + } + + /// + /// Initializes a new instance of the structure that creates a view + /// for the all characters in the specified string. + /// + /// The string to wrap. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public StringView(string value) + { + _length = value.Length; + _value = value; + } + + /// + /// Initializes a new instance of the structure that creates + /// a view for the specified range of the characters in the specified string. + /// + /// The string to wrap. + /// The zero-based starting position of the view in the string. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public StringView(string value, int index) + { + if ((uint)index > (uint)value.Length) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + _index = index; + _length = value.Length - index; + _value = value; + } + + /// + /// Initializes a new instance of the structure that creates + /// a view for the specified range of the characters in the specified string. + /// + /// The string to wrap. + /// The zero-based starting position of the view in the string. + /// The number of characters to include in the view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public StringView(string value, int index, int length) + { + if ((uint)index > (uint)value.Length || (uint)length > (uint)(value.Length - index)) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + _index = index; + _length = length; + _value = value; + } + + /// + /// Initializes a new instance of the structure that creates + /// a view for the specified range of the characters in the specified string. + /// + /// + /// This constructor is intentionally minimal and skips all argument validations, + /// as the caller is responsible for ensuring correctness (e.g., + /// is non-null, and + /// are within bounds). + /// + /// The string to wrap. + /// The zero-based starting position of the view in the string. + /// The number of characters to include in the view. + /// Unused parameter used only to differentiate between overloads. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal StringView(string value, int index, int length, int unused) + { + _index = index; + _length = length; + _value = value; + _ = unused; + } + + /// + public Enumerator GetEnumerator() => + new(this); + + /// + /// Returns a substring from the current string view starting at the specified index. + /// + /// + /// This method is a synonym for the method. + /// + /// The index at which to begin the substring. + /// + /// A string view that consists of all characters of the current string view + /// from to the end of the string view. + /// + public StringView Substring(int start) => + Slice(start); + + /// + /// Returns a substring of the specified length out of the current string view + /// starting at the specified index. + /// + /// + /// This method is a synonym for the method. + /// + /// The index at which to begin the substring. + /// The length of the substring. + /// + /// A string view of characters starting at . + /// + public StringView Substring(int start, int length) => + Slice(start, length); + + /// + /// Forms a slice out of the current string view starting at the specified index. + /// + /// The index at which to begin the slice. + /// + /// A string view that consists of all characters of the current string view + /// from to the end of the string view. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public StringView Slice(int start) + { + if ((uint)start > (uint)_length) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return new StringView(_value!, _index + start, _length - start, unused: 0); + } + + /// + /// Forms a slice of the specified length out of the current string view + /// starting at the specified index. + /// + /// The index at which to begin the slice. + /// The length of the slice. + /// + /// A string view of characters starting at . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public StringView Slice(int start, int length) + { + if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return new StringView(_value!, _index + start, length, unused: 0); + } + + /// + /// Determines whether this instance starts with the specified character. + /// + /// The character to compare. + /// + /// if parameter matches + /// the beginning of this instance; otherwise, . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool StartsWith(char value) => + _length != 0 && _value!.GetRawStringData(_index) == value; + + /// + /// Determines whether the end of this instance matches the specified character. + /// + /// The character to compare. + /// + /// if matches + /// the end of this instance; otherwise, . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool EndsWith(char value) => + _length != 0 && _value!.GetRawStringData(_index + _length - 1) == value; + + /// + /// Determines whether the beginning of this instance matches the specified value + /// when compared using the specified comparison option. + /// + /// The value to compare. + /// One of the enumeration values that determines + /// how this instance and are compared. + /// The default value is . + /// + /// if this instance begins with parameter; + /// otherwise, . + /// + public bool StartsWith(ReadOnlySpan value, StringComparison comparisonType = StringComparison.CurrentCulture) => + AsSpan().StartsWith(value, comparisonType); + + /// + /// Determines whether the end of this instance matches the specified value + /// when compared using the specified comparison option. + /// + /// The value to compare. + /// One of the enumeration values that determines + /// how this instance and are compared. + /// The default value is . + /// + /// if parameter matches + /// the end of this instance; otherwise, . + /// + public bool EndsWith(ReadOnlySpan value, StringComparison comparisonType = StringComparison.CurrentCulture) => + AsSpan().EndsWith(value, comparisonType); + + /// + /// Removes all leading whitespace characters from the current instance. + /// + /// + /// The trimmed . + /// + public StringView TrimStart() + { + var start = _index; + var final = _index + _length; + var value = _value; + + if (value is not null) + for (; start < final; start++) + if (!char.IsWhiteSpace(value.GetRawStringData(start))) + break; + + return new StringView(value!, start, final - start, unused: 0); + } + + /// + /// Removes all leading occurrences of a specified character from the current instance. + /// + /// The specified character to look for and remove. + /// + /// The trimmed . + /// + public StringView TrimStart(char trimChar) + { + var start = _index; + var final = _index + _length; + var value = _value; + + if (value is not null) + for (; start < final; start++) + if (value.GetRawStringData(start) != trimChar) + break; + + return new StringView(value!, start, final - start, unused: 0); + } + + /// + /// Removes all leading occurrences of a set of characters specified + /// in an array from the current instance. + /// + /// + /// If is or an empty array, + /// whitespace characters are removed instead. + /// + /// An array which contains a set of characters to remove. + /// + /// The trimmed . + /// + public StringView TrimStart(params char[]? trimChars) => + TrimStart(trimChars.AsSpan()); + + /// + /// Removes all leading occurrences of a set of characters specified + /// in a read-only span from the current instance. + /// + /// + /// If is empty, whitespace characters are removed instead. + /// + /// A read-only span which contains a set of characters to remove. + /// + /// The trimmed . + /// + public StringView TrimStart(params ReadOnlySpan trimChars) + { + if (trimChars.Length == 0) + return TrimStart(); + + var start = _index; + var final = _index + _length; + var value = _value; + + if (value is not null) + { + for (; start < final; start++) + { + var ch = value.GetRawStringData(start); + + foreach (var trimChar in trimChars) + if (ch == trimChar) + goto MATCHED; + + break; + MATCHED: ; + } + } + + return new StringView(value!, start, final - start, unused: 0); + } + + /// + /// Removes all trailing whitespace characters from the current instance. + /// + /// + /// The trimmed . + /// + public StringView TrimEnd() + { + var start = _index; + var final = _index + _length - 1; + var value = _value; + + if (value is not null) + for (; final >= start; final--) + if (!char.IsWhiteSpace(value.GetRawStringData(final))) + break; + + return new StringView(value!, start, final + 1 - start, unused: 0); + } + + /// + /// Removes all trailing occurrences of a specified character from the current instance. + /// + /// The specified character to look for and remove. + /// + /// The trimmed . + /// + public StringView TrimEnd(char trimChar) + { + var start = _index; + var final = _index + _length - 1; + var value = _value; + + if (value is not null) + for (; final >= start; final--) + if (value.GetRawStringData(final) != trimChar) + break; + + return new StringView(value!, start, final + 1 - start, unused: 0); + } + + /// + /// Removes all trailing occurrences of a set of characters specified + /// in an array from the current instance. + /// + /// + /// If is or an empty array, + /// whitespace characters are removed instead. + /// + /// An array which contains a set of characters to remove. + /// + /// The trimmed . + /// + public StringView TrimEnd(params char[]? trimChars) => + TrimEnd(trimChars.AsSpan()); + + /// + /// Removes all leading occurrences of a set of characters specified + /// in a read-only span from the current instance. + /// + /// + /// If is empty, whitespace characters are removed instead. + /// + /// A read-only span which contains a set of characters to remove. + /// + /// The trimmed . + /// + public StringView TrimEnd(params ReadOnlySpan trimChars) + { + if (trimChars.Length == 0) + return TrimEnd(); + + var start = _index; + var final = _index + _length - 1; + var value = _value; + + if (value is not null) + { + for (; final >= start; final--) + { + var ch = value.GetRawStringData(final); + + foreach (var trimChar in trimChars) + if (ch == trimChar) + goto MATCHED; + + break; + MATCHED: ; + } + } + + return new StringView(value!, start, final + 1 - start, unused: 0); + } + + /// + /// Removes all leading and trailing whitespace characters from the current instance. + /// + /// + /// The trimmed . + /// + public StringView Trim() + { + var start = _index; + var final = _index + _length - 1; + var value = _value; + + if (value is not null) + { + for (; start <= final; start++) + if (!char.IsWhiteSpace(value.GetRawStringData(start))) + break; + + for (; final > start; final--) + if (!char.IsWhiteSpace(value.GetRawStringData(final))) + break; + } + + return new StringView(value!, start, final + 1 - start, unused: 0); + } + + /// + /// Removes all leading and trailing occurrences of a specified character from the current instance. + /// + /// The specified character to look for and remove. + /// + /// The trimmed . + /// + public StringView Trim(char trimChar) + { + var start = _index; + var final = _index + _length - 1; + var value = _value; + + if (value is not null) + { + for (; start <= final; start++) + if (value.GetRawStringData(start) != trimChar) + break; + + for (; final > start; final--) + if (value.GetRawStringData(final) != trimChar) + break; + } + + return new StringView(value!, start, final + 1 - start, unused: 0); + } + + /// + /// Removes all leading and trailing occurrences of a set of characters + /// specified in an array from the current instance. + /// + /// + /// If is or an empty array, + /// whitespace characters are removed instead. + /// + /// An array which contains a set of characters to remove. + /// + /// The trimmed . + /// + public StringView Trim(params char[]? trimChars) => + Trim(trimChars.AsSpan()); + + /// + /// Removes all leading and trailing occurrences of a set of characters specified + /// in a read-only span from the current instance. + /// + /// + /// If is empty, whitespace characters are removed instead. + /// + /// A read-only span which contains a set of characters to remove. + /// + /// The trimmed . + /// + public StringView Trim(params ReadOnlySpan trimChars) + { + if (trimChars.Length == 0) + return Trim(); + + var start = _index; + var final = _index + _length - 1; + var value = _value; + + if (value is not null) + { + for (; start <= final; start++) + { + var ch = value.GetRawStringData(start); + + foreach (var trimChar in trimChars) + if (ch == trimChar) + goto MATCHED; + + break; + MATCHED: ; + } + + for (; final > start; final--) + { + var ch = value.GetRawStringData(final); + + foreach (var trimChar in trimChars) + if (ch == trimChar) + goto MATCHED; + + break; + MATCHED: ; + } + } + + return new StringView(value!, start, final + 1 - start, unused: 0); + } + + /// + /// Reports the zero-based index of the first occurrence of the specified Unicode character in this instance. + /// + /// A Unicode character to seek. + /// + /// The zero-based index position of if that character is found, + /// or -1 if it is not. + /// + public int IndexOf(char value) => + AsSpan().IndexOf(value); + + /// + /// Reports the zero-based index of the first occurrence of the specified character sequence + /// in this instance. + /// + /// The sequence of characters to search. + /// + /// The zero-based index position of if that sequence is found, + /// or -1 if it is not. + /// + public int IndexOf(ReadOnlySpan value) => + AsSpan().IndexOf(value); + + /// + /// Reports the zero-based index of the last occurrence of the specified character sequence + /// in this instance. A parameter specifies the type of search + /// to use for the specified character sequence. + /// + /// The sequence of characters to search. + /// An enumeration value that specifies the rules for the search. + /// + /// The zero-based index position of if that sequence is found, + /// or -1 if it is not. + /// + public int IndexOf(ReadOnlySpan value, StringComparison comparisonType) => + AsSpan().IndexOf(value, comparisonType); + + /// + /// Reports the zero-based index of the last occurrence of the specified Unicode character + /// in this instance. + /// + /// A Unicode character to seek. + /// + /// The zero-based index position of if that character is found, + /// or -1 if it is not. + /// + public int LastIndexOf(char value) => + AsSpan().LastIndexOf(value); + + /// + /// Reports the zero-based index of the last occurrence of the specified character sequence + /// in this instance. + /// + /// The sequence of characters to search. + /// + /// The zero-based index position of if that sequence is found, + /// or -1 if it is not. + /// + public int LastIndexOf(ReadOnlySpan value) => + AsSpan().LastIndexOf(value); + + /// + /// Reports the zero-based index of the last occurrence of the specified character sequence + /// in this instance. A parameter specifies the type of search to use + /// for the specified character sequence. + /// + /// The sequence of characters to search. + /// An enumeration value that specifies the rules for the search. + /// + /// The zero-based index position of if that sequence is found, + /// or -1 if it is not. + /// + public int LastIndexOf(ReadOnlySpan value, StringComparison comparisonType) => + AsSpan().LastIndexOf(value, comparisonType); + + /// + /// Returns a value indicating whether a specified character occurs within this instance. + /// + /// A Unicode character to seek. + /// + /// if the parameter occurs within this instance; + /// otherwise, . + /// + public bool Contains(char value) => + AsSpan().Contains(value); + + /// + /// Returns a value indicating whether a specified character sequence occurs within this instance. + /// + /// The sequence of characters to seek. + /// + /// if the parameter occurs within this instance; + /// otherwise, . + /// + public bool Contains(ReadOnlySpan value) => + AsSpan().IndexOf(value) >= 0; + + /// + /// Reports the zero-based index of the first occurrence of the specified character sequence + /// in this instance, using the specified comparison rules. + /// + /// The sequence of characters to search. + /// An enumeration value that specifies the rules for the search. + /// + /// if the parameter occurs within this instance; + /// otherwise, . + /// + public bool Contains(ReadOnlySpan value, StringComparison comparisonType) => + AsSpan().Contains(value, comparisonType); + + /// + public int CompareTo(StringView other) => + Compare(this, other, StringComparison.CurrentCulture); + + /// + /// Compares one view with a readonly span, and returns an integer + /// that indicates their relative position in the sort order. + /// + /// An object to compare with this instance. + /// + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, this instance precedes than . + /// - If 0, this instance equals . + /// - If greater than 0, this instance follows . + /// + public int CompareTo(ReadOnlySpan other) => + Compare(this, other, StringComparison.CurrentCulture); + + /// + public int CompareTo(string? other) => + Compare(this, other, StringComparison.CurrentCulture); + + /// + /// Compares one view with another using a specified string comparison, + /// and returns an integer that indicates their relative position in the sort order. + /// + /// The view to compare with the current instance. + /// An enumeration value that determines + /// how current view and other are compared. + /// + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, this instance precedes than . + /// - If 0, this instance equals . + /// - If greater than 0, this instance follows . + /// + public int CompareTo(StringView other, StringComparison comparisonType) => + Compare(this, other, comparisonType); + + /// + /// Compares one view with a readonly span using a specified string comparison, + /// and returns an integer that indicates their relative position in the sort order. + /// + /// The view to compare with the current instance. + /// An enumeration value that determines + /// how current view and other are compared. + /// + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, this instance precedes than . + /// - If 0, this instance equals . + /// - If greater than 0, this instance follows . + /// + public int CompareTo(ReadOnlySpan other, StringComparison comparisonType) => + Compare(this, other, comparisonType); + + /// + /// Compares one view with a string using a specified string comparison, + /// and returns an integer that indicates their relative position in the sort order. + /// + /// The view to compare with the current instance. + /// An enumeration value that determines + /// how current view and other are compared. + /// + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, this instance precedes than . + /// - If 0, this instance equals . + /// - If greater than 0, this instance follows . + /// + public int CompareTo(string? other, StringComparison comparisonType) => + Compare(this, other, comparisonType); + + /// + public override bool Equals([NotNullWhen(true)] object? obj) + { + if (obj is null) + return _length == 0; + + if (obj is StringView view) + return Equals(this, view); + + return obj is string s && Equals(s); + } + + /// + public bool Equals(StringView other) => + Equals(this, other); + + /// + /// Indicates whether the current object is equal to a specified readonly span. + /// + /// An object to compare with this object. + /// + /// if the current object is equal to the parameter; + /// otherwise, . + /// + public bool Equals(ReadOnlySpan other) => + Equals(this, other); + + /// + public bool Equals(string? other) => + Equals(this, other); + + /// + /// Determines whether this view and the specified other view have the same characters + /// when compared using the specified option. + /// + /// The value to compare with the current instance. + /// An enumeration value that determines + /// how current instance and are compared. + /// + /// true if equal, false otherwise. + /// + public bool Equals(StringView other, StringComparison comparisonType) => + Equals(this, other, comparisonType); + + /// + /// Determines whether this view and the specified readonly span have the same characters + /// when compared using the specified option. + /// + /// The value to compare with the current instance. + /// An enumeration value that determines + /// how current instance and are compared. + /// + /// true if equal, false otherwise. + /// + public bool Equals(ReadOnlySpan other, StringComparison comparisonType) => + Equals(this, other, comparisonType); + + /// + /// Determines whether this view and the specified other view have the same characters + /// when compared using the specified option. + /// + /// The value to compare with the current instance. + /// An enumeration value that determines + /// how current instance and are compared. + /// + /// true if equal, false otherwise. + /// + public bool Equals(string? other, StringComparison comparisonType) => + Equals(this, other, comparisonType); + + /// + public override int GetHashCode() => + string.GetHashCode(AsSpan()); + + /// + /// Returns the hash code for this instance using the specified rules. + /// + /// One of the enumeration values + /// that specifies the rules to use in the comparison. + /// + /// A 32-bit signed integer hash code. + /// + public int GetHashCode(StringComparison comparisonType) => + string.GetHashCode(AsSpan(), comparisonType); + + /// + /// Copies the contents of this string view into a new string. + /// + /// + /// A string containing the data in the current string view. + /// + public override string ToString() + { + var value = _value ?? ""; + if (_length == value.Length && _index == 0) + return value; + + return new string( + MemoryMarshal.CreateReadOnlySpan( + ref Unsafe.AsRef(in value.GetRawStringData(_index)), + _length)); + } + + /// + /// Copies the contents of this string view into a new array. + /// + /// + /// An array containing the data in the current string view. + /// + public char[] ToArray() => + ((ReadOnlySpan)this).ToArray(); + + /// + /// Returns a read-only span over the current string view. + /// + /// + /// The read-only span representation of the string view. + /// + public ReadOnlySpan AsSpan() => + this; + + /// + /// Returns a read-only memory region over the current string view. + /// + /// + /// The read-only memory region over the string view. + /// + public ReadOnlyMemory AsMemory() => + this; + + /// + /// Returns a reference to the element of the at index zero. + /// + /// + /// A reference to the element of the at index zero, + /// or if is true. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ref readonly char GetPinnableReference() + { + // + // Normalize the returned reference. + // We must not return a reference to an element outside the bounds of our view + // when the view is empty (_count = 0), even if it points to a valid element + // in the underlying string. In this case, we return a null reference. + // + // Examples: + // + // Full string (_value): + // [0][1][2][3][4][5][6][7][8][9] + // |--------------------------| + // + // Case 1: Non-empty view (_index = 3, _count = 4) + // [3][4][5][6] + // ^ ^ + // |--------| <- valid range for this view + // + // Case 2: Empty view (_index = 3, _count = 0) + // [3][4][5][6] + // ^ + // | <- no valid reference for this view + // + + ref readonly var p = ref Unsafe.NullRef(); + + if (_length != 0) + p = ref _value!.GetRawStringData(_index); + + return ref p; + } + + /// + /// Copies the contents of this into a destination . + /// + /// The span to copy items into. + public void CopyTo(Span destination) => + AsSpan().CopyTo(destination); + + /// + /// Attempts to copy the contents of this into a destination + /// and returns a value to indicate whether the operation succeeded. + /// + /// The span to copy items into. + /// + /// if the copy operation succeeded; otherwise, . + /// + public bool TryCopyTo(Span destination) => + AsSpan().TryCopyTo(destination); + + /// + /// Determines whether two specified objects have the same value. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// if the value of is the same as the value + /// of ; otherwise, . + /// + public static bool Equals(StringView a, StringView b) => + a.AsSpan().SequenceEqual(b); + + /// + /// Determines whether two specified objects have the same value. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// if the value of is the same as the value + /// of ; otherwise, . + /// + public static bool Equals(StringView a, ReadOnlySpan b) => + a.AsSpan().SequenceEqual(b); + + /// + /// Determines whether two specified objects have the same value. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// if the value of is the same as the value + /// of ; otherwise, . + /// + public static bool Equals(StringView a, string? b) => + a.AsSpan().SequenceEqual(b); + + /// + /// Determines whether two specified objects have the same value + /// with the specified comparison rules. + /// + /// The first value to compare. + /// The second value to compare. + /// An enumeration value that determines how values are compared. + /// + /// if the value of the parameter + /// is equal to the value of parameter; + /// otherwise, . + /// + public static bool Equals(StringView a, StringView b, StringComparison comparison) => + a.AsSpan().Equals(b, comparison); + + /// + /// Determines whether two specified objects have the same value + /// with the specified comparison rules. + /// + /// The first value to compare. + /// The second value to compare. + /// An enumeration value that determines how values are compared. + /// + /// if the value of the parameter + /// is equal to the value of parameter; + /// otherwise, . + /// + public static bool Equals(StringView a, ReadOnlySpan b, StringComparison comparison) => + a.AsSpan().Equals(b, comparison); + + /// + /// Determines whether two specified objects have the same value + /// with the specified comparison rules. + /// + /// The first value to compare. + /// The second value to compare. + /// An enumeration value that determines how values are compared. + /// + /// if the value of the parameter + /// is equal to the value of parameter; + /// otherwise, . + /// + public static bool Equals(StringView a, string? b, StringComparison comparison) => + a.AsSpan().Equals(b, comparison); + + /// + /// Compares two specified objects and returns an integer + /// that indicates their relative position in the sort order. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, > precedes in the sort order. + /// - If 0, > equals . + /// - If greater than 0, > follows in the sort order. + /// + public static int CompareOrdinal(StringView a, StringView b) => + a.AsSpan().SequenceCompareTo(b); + + /// + /// Compares two specified objects and returns an integer + /// that indicates their relative position in the sort order. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, > precedes in the sort order. + /// - If 0, > equals . + /// - If greater than 0, > follows in the sort order. + /// + public static int CompareOrdinal(StringView a, ReadOnlySpan b) => + a.AsSpan().SequenceCompareTo(b); + + /// + /// Compares two specified objects and returns an integer + /// that indicates their relative position in the sort order. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, > precedes in the sort order. + /// - If 0, > equals . + /// - If greater than 0, > follows in the sort order. + /// + public static int CompareOrdinal(StringView a, string? b) => + a.AsSpan().SequenceCompareTo(b); + + /// + /// Compares two specified objects and returns an integer + /// that indicates their relative position in the sort order. + /// + /// The first value to compare. + /// The second value to compare. + /// One of the enumeration values + /// that specifies the rules to use in the comparison. + /// + /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, > precedes in the sort order. + /// - If 0, > equals . + /// - If greater than 0, > follows in the sort order. + /// + public static int Compare(StringView a, StringView b, StringComparison comparison) => + a.AsSpan().CompareTo(b, comparison); + + /// + /// Compares two specified objects and returns an integer + /// that indicates their relative position in the sort order. + /// + /// The first value to compare. + /// The second value to compare. + /// One of the enumeration values + /// that specifies the rules to use in the comparison. + /// + /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, > precedes in the sort order. + /// - If 0, > equals . + /// - If greater than 0, > follows in the sort order. + /// + public static int Compare(StringView a, ReadOnlySpan b, StringComparison comparison) => + a.AsSpan().CompareTo(b, comparison); + + /// + /// Compares two specified objects and returns an integer + /// that indicates their relative position in the sort order. + /// + /// The first value to compare. + /// The second value to compare. + /// One of the enumeration values + /// that specifies the rules to use in the comparison. + /// + /// A 32-bit signed integer that indicates the lexical relationship between the two comparands. + /// A signed integer that indicates the relative order of view and other: + /// - If less than 0, > precedes in the sort order. + /// - If 0, > equals . + /// - If greater than 0, > follows in the sort order. + /// + public static int Compare(StringView a, string? b, StringComparison comparison) => + a.AsSpan().CompareTo(b, comparison); + + /// + /// Determines whether two instances are equal. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// if the two instances are equal; + /// otherwise, . + /// + public static bool operator ==(StringView a, StringView b) => + Equals(a, b); + + /// + /// Determines whether two instances are not equal. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// if the two instances are not equal; + /// otherwise, . + /// + public static bool operator !=(StringView a, StringView b) => + !Equals(a, b); + + /// + /// Determines whether two instances are equal. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// if the two instances are equal; + /// otherwise, . + /// + public static bool operator ==(StringView a, string? b) => + Equals(a, b); + + /// + /// Determines whether two instances are not equal. + /// + /// The first value to compare. + /// The second value to compare. + /// + /// if the two instances are not equal; + /// otherwise, . + /// + public static bool operator !=(StringView a, string? b) => + !Equals(a, b); + + /// + /// Defines an implicit conversion of a string view. + /// + /// The string to convert. + /// + /// A string view representation of the string. + /// + public static implicit operator StringView(string? value) => + new(value ?? ""); + + /// + /// Defines an implicit conversion of the to the . + /// + /// The to convert. + /// + /// A representation of the . + /// + public static implicit operator ReadOnlyMemory(StringView view) => + view._value.AsMemory(view._index, view._length); + + /// + /// Defines an implicit conversion of a string view to the . + /// + /// The string view to convert. + /// + /// A representation of the string view. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ReadOnlySpan(StringView view) + { + var value = view._value ?? ""; + + return MemoryMarshal.CreateReadOnlySpan( + ref Unsafe.AsRef(in value.GetRawStringData(view._index)), + view._length); + } + + /// + /// Returns a string representation of the current instance's state, intended for debugging purposes. + /// + /// + /// A string containing information about the current instance. + /// + private string ToStringDebugger() => + _value is null ? "Uninitialized" : ToString(); + + #region IEnumerable implementation + + IEnumerator IEnumerable.GetEnumerator() => + new StringViewEnumerator(this); + + IEnumerator IEnumerable.GetEnumerator() => + new StringViewEnumerator(this); + + #endregion + + #region IReadOnlyCollection implementation + + int IReadOnlyCollection.Count => _length; + + #endregion + + #region IReadOnlyList implementation + + char IReadOnlyList.this[int index] => this[index]; + + #endregion + + #region Inner type: Enumerator + + /// + /// Provides the ability to iterate through the characters of the . + /// + public struct Enumerator + { + private readonly string? _value; + private int _index; + private readonly int _final; + private char _ch; + + /// + public readonly char Current => _ch; + + /// + /// Initializes a new instance of the structure. + /// + /// The to iterate through its characters. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Enumerator(StringView view) + { + _index = view._index - 1; + _final = view._index + view._length; + _value = view._value; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + #if NET9_0_OR_GREATER + // + // The "_value is not null" condition is hoisted and checked only once + // + if (_value is not null && (uint)++_index < (uint)_final) + { + _ch = _value!.GetRawStringData(_index); + return true; + } + #else + if ((uint)++_index < (uint)_final) + { + _ch = _value!.GetRawStringData(_index); + return true; + } + #endif + + return false; + } + } + + #endregion + + #region Inner type: StringViewEnumerator + + /// + /// Provides the ability to iterate through the characters of the . + /// + private sealed class StringViewEnumerator : IEnumerator + { + private readonly string? _value; + private int _index; + private readonly int _final; + private char _ch; + + /// + public char Current => _ch; + + /// + /// Initializes a new instance of the class. + /// + /// The to iterate through its characters. + public StringViewEnumerator(StringView view) + { + _index = view._index - 1; + _final = view._index + view._length; + _value = view._value; + } + + /// + public bool MoveNext() + { + if ((uint)++_index < (uint)_final) + { + _ch = _value!.GetRawStringData(_index); + return true; + } + + return false; + } + + /// + public void Dispose() + { } + + /// + object IEnumerator.Current => Current; + + /// + void IEnumerator.Reset() => + ThrowHelper.ThrowNotSupportedException(); + } + + #endregion +} diff --git a/Ramstack.Structures/Text/StringViewComparer.cs b/Ramstack.Structures/Text/StringViewComparer.cs index d6d9d31..6b5ead2 100644 --- a/Ramstack.Structures/Text/StringViewComparer.cs +++ b/Ramstack.Structures/Text/StringViewComparer.cs @@ -1,260 +1,260 @@ -namespace Ramstack.Text; - -/// -/// Represents a comparison operation -/// that uses specific case and culture-based or ordinal comparison rules. -/// -public abstract class StringViewComparer : IEqualityComparer, IComparer -{ - /// - /// Gets a object that performs a case-sensitive ordinal string comparison. - /// - public static StringViewComparer Ordinal => OrdinalComparer.Instance; - - /// - /// Gets a object that performs a case-insensitive ordinal string comparison. - /// - public static StringViewComparer OrdinalIgnoreCase => OrdinalIgnoreCaseComparer.Instance; - - /// - /// Gets a object that performs case-insensitive string comparisons - /// using the word comparison rules of the current culture. - /// - public static StringViewComparer CurrentCulture => new CultureAwareComparer( - CultureInfo.CurrentCulture.CompareInfo, CompareOptions.None); - - /// - /// Gets a object that performs case-insensitive string comparisons - /// using the word comparison rules of the current culture. - /// - public static StringViewComparer CurrentCultureIgnoreCase => new CultureAwareComparer( - CultureInfo.CurrentCulture.CompareInfo, CompareOptions.IgnoreCase); - - /// - /// Gets a object that performs a case-sensitive string comparison - /// using the word comparison rules of the invariant culture. - /// - public static StringViewComparer InvariantCulture => CultureAwareComparer.InvariantInstance; - - /// - /// Gets a object that performs a case-insensitive string comparison - /// using the word comparison rules of the invariant culture. - /// - public static StringViewComparer InvariantCultureIgnoreCase => CultureAwareComparer.InvariantIgnoreCaseInstance; - - /// - /// Initializes a new instance of the class. - /// - private protected StringViewComparer() - { - } - - /// - public abstract bool Equals(StringView x, StringView y); - - /// - public abstract int Compare(StringView x, StringView y); - - /// - public abstract int GetHashCode(StringView obj); - - /// - /// Creates a that compares - /// based on the rules of a specified culture. - /// - /// The culture whose linguistic rules are used for the string comparison. - /// for case-insensitive comparison; - /// for case-sensitive comparison. - /// - /// A new object that compares strings according - /// to the rules of the specified culture and case sensitivity. - /// - public static StringViewComparer Create(CultureInfo culture, bool ignoreCase) => - Create(culture, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); - - /// - /// Creates a object that compares - /// based on the rules of a specified culture and comparison options. - /// - /// The culture whose linguistic rules are used for the string comparison. - /// A combination of values - /// that specify the comparison options. - /// - /// A new object that compares strings - /// according to the rules of the specified culture and options. - /// - public static StringViewComparer Create(CultureInfo culture, CompareOptions options) => - new CultureAwareComparer(culture.CompareInfo, options); - - /// - /// Creates a instance from the specified value. - /// - /// The instance to convert. - /// - /// A instance that represents - /// the equivalent value of the specified instance. - /// - public static StringViewComparer FromComparison(StringComparison comparisonType) - { - return comparisonType switch - { - StringComparison.CurrentCulture => CurrentCulture, - StringComparison.CurrentCultureIgnoreCase => CurrentCultureIgnoreCase, - StringComparison.InvariantCulture => InvariantCulture, - StringComparison.InvariantCultureIgnoreCase => InvariantCultureIgnoreCase, - StringComparison.Ordinal => Ordinal, - StringComparison.OrdinalIgnoreCase => OrdinalIgnoreCase, - _ => Error(comparisonType) - }; - - static StringViewComparer Error(StringComparison comparisonType) => - throw new ArgumentOutOfRangeException(nameof(comparisonType), comparisonType, "The specified string comparison is not supported"); - } - - #region Inner type: CultureAwareComparer - - /// - /// Represents a comparer that performs culture-sensitive string comparisons. - /// - /// An instance of that provides - /// culture-specific comparison information. - /// A bitwise combination of values - /// that specify how the comparison should be performed. - private sealed class CultureAwareComparer(CompareInfo info, CompareOptions options) : StringViewComparer - #if NET9_0_OR_GREATER - , IAlternateEqualityComparer, StringView> - #endif - { - /// - /// A singleton instance of the class - /// for invariant case-sensitive comparison. - /// - public static readonly CultureAwareComparer InvariantInstance = - new(CultureInfo.InvariantCulture.CompareInfo, CompareOptions.None); - - /// - /// A singleton instance of the class - /// for invariant case-insensitive comparison. - /// - public static readonly CultureAwareComparer InvariantIgnoreCaseInstance = - new(CultureInfo.InvariantCulture.CompareInfo, CompareOptions.IgnoreCase); - - /// - public override bool Equals(StringView x, StringView y) => - info.IndexOf(x, y, options) == 0; - - /// - public override int GetHashCode(StringView obj) => - info.GetHashCode(obj, options); - - /// - public override int Compare(StringView x, StringView y) => - info.IndexOf(x, y, options); - - #if NET9_0_OR_GREATER - /// - bool IAlternateEqualityComparer, StringView>.Equals(ReadOnlySpan alternate, StringView other) => - info.IndexOf(alternate, other, options) == 0; - - /// - int IAlternateEqualityComparer, StringView>.GetHashCode(ReadOnlySpan alternate) => - info.GetHashCode(alternate, options); - - /// - StringView IAlternateEqualityComparer, StringView>.Create(ReadOnlySpan alternate) => - alternate.ToString(); - #endif - } - - #endregion - - #region Inner type: OrdinalComparer - - /// - /// Represents a comparison operation - /// that performs a case-sensitive ordinal string comparison. - /// - private sealed class OrdinalComparer : StringViewComparer - #if NET9_0_OR_GREATER - , IAlternateEqualityComparer, StringView> - #endif - { - /// - /// A singleton instance of the class. - /// - public static readonly OrdinalComparer Instance = new(); - - /// - public override bool Equals(StringView x, StringView y) => - StringView.Equals(x, y); - - /// - public override int Compare(StringView x, StringView y) => - StringView.CompareOrdinal(x, y); - - /// - public override int GetHashCode(StringView obj) => - obj.GetHashCode(); - - #if NET9_0_OR_GREATER - /// - bool IAlternateEqualityComparer, StringView>.Equals(ReadOnlySpan alternate, StringView other) => - alternate.SequenceEqual(other); - - /// - int IAlternateEqualityComparer, StringView>.GetHashCode(ReadOnlySpan alternate) => - string.GetHashCode(alternate); - - /// - StringView IAlternateEqualityComparer, StringView>.Create(ReadOnlySpan alternate) => - alternate.ToString(); - #endif - } - - #endregion - - #region Inner type: OrdinalIgnoreCaseComparer - - /// - /// Represents a comparison operation - /// that performs a case-insensitive ordinal string comparison. - /// - private sealed class OrdinalIgnoreCaseComparer : StringViewComparer - #if NET9_0_OR_GREATER - , IAlternateEqualityComparer, StringView> - #endif - { - /// - /// A singleton instance of the class. - /// - public static readonly OrdinalIgnoreCaseComparer Instance = new(); - - /// - public override bool Equals(StringView x, StringView y) => - StringView.Equals(x, y, StringComparison.OrdinalIgnoreCase); - - /// - public override int Compare(StringView x, StringView y) => - StringView.Compare(x, y, StringComparison.OrdinalIgnoreCase); - - /// - public override int GetHashCode(StringView obj) => - obj.GetHashCode(StringComparison.OrdinalIgnoreCase); - - #if NET9_0_OR_GREATER - /// - bool IAlternateEqualityComparer, StringView>.Equals(ReadOnlySpan alternate, StringView other) => - alternate.Equals(other, StringComparison.OrdinalIgnoreCase); - - /// - int IAlternateEqualityComparer, StringView>.GetHashCode(ReadOnlySpan alternate) => - string.GetHashCode(alternate, StringComparison.OrdinalIgnoreCase); - - /// - StringView IAlternateEqualityComparer, StringView>.Create(ReadOnlySpan alternate) => - alternate.ToString(); - #endif - } - - #endregion -} +namespace Ramstack.Text; + +/// +/// Represents a comparison operation +/// that uses specific case and culture-based or ordinal comparison rules. +/// +public abstract class StringViewComparer : IEqualityComparer, IComparer +{ + /// + /// Gets a object that performs a case-sensitive ordinal string comparison. + /// + public static StringViewComparer Ordinal => OrdinalComparer.Instance; + + /// + /// Gets a object that performs a case-insensitive ordinal string comparison. + /// + public static StringViewComparer OrdinalIgnoreCase => OrdinalIgnoreCaseComparer.Instance; + + /// + /// Gets a object that performs case-insensitive string comparisons + /// using the word comparison rules of the current culture. + /// + public static StringViewComparer CurrentCulture => new CultureAwareComparer( + CultureInfo.CurrentCulture.CompareInfo, CompareOptions.None); + + /// + /// Gets a object that performs case-insensitive string comparisons + /// using the word comparison rules of the current culture. + /// + public static StringViewComparer CurrentCultureIgnoreCase => new CultureAwareComparer( + CultureInfo.CurrentCulture.CompareInfo, CompareOptions.IgnoreCase); + + /// + /// Gets a object that performs a case-sensitive string comparison + /// using the word comparison rules of the invariant culture. + /// + public static StringViewComparer InvariantCulture => CultureAwareComparer.InvariantInstance; + + /// + /// Gets a object that performs a case-insensitive string comparison + /// using the word comparison rules of the invariant culture. + /// + public static StringViewComparer InvariantCultureIgnoreCase => CultureAwareComparer.InvariantIgnoreCaseInstance; + + /// + /// Initializes a new instance of the class. + /// + private protected StringViewComparer() + { + } + + /// + public abstract bool Equals(StringView x, StringView y); + + /// + public abstract int Compare(StringView x, StringView y); + + /// + public abstract int GetHashCode(StringView obj); + + /// + /// Creates a that compares + /// based on the rules of a specified culture. + /// + /// The culture whose linguistic rules are used for the string comparison. + /// for case-insensitive comparison; + /// for case-sensitive comparison. + /// + /// A new object that compares strings according + /// to the rules of the specified culture and case sensitivity. + /// + public static StringViewComparer Create(CultureInfo culture, bool ignoreCase) => + Create(culture, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); + + /// + /// Creates a object that compares + /// based on the rules of a specified culture and comparison options. + /// + /// The culture whose linguistic rules are used for the string comparison. + /// A combination of values + /// that specify the comparison options. + /// + /// A new object that compares strings + /// according to the rules of the specified culture and options. + /// + public static StringViewComparer Create(CultureInfo culture, CompareOptions options) => + new CultureAwareComparer(culture.CompareInfo, options); + + /// + /// Creates a instance from the specified value. + /// + /// The instance to convert. + /// + /// A instance that represents + /// the equivalent value of the specified instance. + /// + public static StringViewComparer FromComparison(StringComparison comparisonType) + { + return comparisonType switch + { + StringComparison.CurrentCulture => CurrentCulture, + StringComparison.CurrentCultureIgnoreCase => CurrentCultureIgnoreCase, + StringComparison.InvariantCulture => InvariantCulture, + StringComparison.InvariantCultureIgnoreCase => InvariantCultureIgnoreCase, + StringComparison.Ordinal => Ordinal, + StringComparison.OrdinalIgnoreCase => OrdinalIgnoreCase, + _ => Error(comparisonType) + }; + + static StringViewComparer Error(StringComparison comparisonType) => + throw new ArgumentOutOfRangeException(nameof(comparisonType), comparisonType, "The specified string comparison is not supported"); + } + + #region Inner type: CultureAwareComparer + + /// + /// Represents a comparer that performs culture-sensitive string comparisons. + /// + /// An instance of that provides + /// culture-specific comparison information. + /// A bitwise combination of values + /// that specify how the comparison should be performed. + private sealed class CultureAwareComparer(CompareInfo info, CompareOptions options) : StringViewComparer + #if NET9_0_OR_GREATER + , IAlternateEqualityComparer, StringView> + #endif + { + /// + /// A singleton instance of the class + /// for invariant case-sensitive comparison. + /// + public static readonly CultureAwareComparer InvariantInstance = + new(CultureInfo.InvariantCulture.CompareInfo, CompareOptions.None); + + /// + /// A singleton instance of the class + /// for invariant case-insensitive comparison. + /// + public static readonly CultureAwareComparer InvariantIgnoreCaseInstance = + new(CultureInfo.InvariantCulture.CompareInfo, CompareOptions.IgnoreCase); + + /// + public override bool Equals(StringView x, StringView y) => + info.IndexOf(x, y, options) == 0; + + /// + public override int GetHashCode(StringView obj) => + info.GetHashCode(obj, options); + + /// + public override int Compare(StringView x, StringView y) => + info.IndexOf(x, y, options); + + #if NET9_0_OR_GREATER + /// + bool IAlternateEqualityComparer, StringView>.Equals(ReadOnlySpan alternate, StringView other) => + info.IndexOf(alternate, other, options) == 0; + + /// + int IAlternateEqualityComparer, StringView>.GetHashCode(ReadOnlySpan alternate) => + info.GetHashCode(alternate, options); + + /// + StringView IAlternateEqualityComparer, StringView>.Create(ReadOnlySpan alternate) => + alternate.ToString(); + #endif + } + + #endregion + + #region Inner type: OrdinalComparer + + /// + /// Represents a comparison operation + /// that performs a case-sensitive ordinal string comparison. + /// + private sealed class OrdinalComparer : StringViewComparer + #if NET9_0_OR_GREATER + , IAlternateEqualityComparer, StringView> + #endif + { + /// + /// A singleton instance of the class. + /// + public static readonly OrdinalComparer Instance = new(); + + /// + public override bool Equals(StringView x, StringView y) => + StringView.Equals(x, y); + + /// + public override int Compare(StringView x, StringView y) => + StringView.CompareOrdinal(x, y); + + /// + public override int GetHashCode(StringView obj) => + obj.GetHashCode(); + + #if NET9_0_OR_GREATER + /// + bool IAlternateEqualityComparer, StringView>.Equals(ReadOnlySpan alternate, StringView other) => + alternate.SequenceEqual(other); + + /// + int IAlternateEqualityComparer, StringView>.GetHashCode(ReadOnlySpan alternate) => + string.GetHashCode(alternate); + + /// + StringView IAlternateEqualityComparer, StringView>.Create(ReadOnlySpan alternate) => + alternate.ToString(); + #endif + } + + #endregion + + #region Inner type: OrdinalIgnoreCaseComparer + + /// + /// Represents a comparison operation + /// that performs a case-insensitive ordinal string comparison. + /// + private sealed class OrdinalIgnoreCaseComparer : StringViewComparer + #if NET9_0_OR_GREATER + , IAlternateEqualityComparer, StringView> + #endif + { + /// + /// A singleton instance of the class. + /// + public static readonly OrdinalIgnoreCaseComparer Instance = new(); + + /// + public override bool Equals(StringView x, StringView y) => + StringView.Equals(x, y, StringComparison.OrdinalIgnoreCase); + + /// + public override int Compare(StringView x, StringView y) => + StringView.Compare(x, y, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode(StringView obj) => + obj.GetHashCode(StringComparison.OrdinalIgnoreCase); + + #if NET9_0_OR_GREATER + /// + bool IAlternateEqualityComparer, StringView>.Equals(ReadOnlySpan alternate, StringView other) => + alternate.Equals(other, StringComparison.OrdinalIgnoreCase); + + /// + int IAlternateEqualityComparer, StringView>.GetHashCode(ReadOnlySpan alternate) => + string.GetHashCode(alternate, StringComparison.OrdinalIgnoreCase); + + /// + StringView IAlternateEqualityComparer, StringView>.Create(ReadOnlySpan alternate) => + alternate.ToString(); + #endif + } + + #endregion +} diff --git a/Ramstack.Structures/Text/StringViewExtensions.cs b/Ramstack.Structures/Text/StringViewExtensions.cs index 799c9db..b77cde3 100644 --- a/Ramstack.Structures/Text/StringViewExtensions.cs +++ b/Ramstack.Structures/Text/StringViewExtensions.cs @@ -1,42 +1,42 @@ -namespace Ramstack.Text; - -/// -/// Provides extension methods for the structure. -/// -public static class StringViewExtensions -{ - /// - /// Creates a new over a string. - /// - /// The string to create a view over. - /// - /// A representing the specified string. - /// - public static StringView AsView(this string? value) => - new(value ?? ""); - - /// - /// Creates a new over a portion of the specified string - /// starting at a specified position to the end of the string. - /// - /// The string to create a view over. - /// The zero-based starting position of the view in the string. - /// - /// A representing the specified portion of the string. - /// - public static StringView AsView(this string? value, int index) => - new(value ?? "", index); - - /// - /// Creates a new over a portion of the specified string - /// starting at a specified position for a specified number of characters. - /// - /// The string to create a view over. - /// The zero-based starting position of the view in the string. - /// The number of characters to include in the view. - /// - /// A representing the specified portion of the string. - /// - public static StringView AsView(this string? value, int index, int length) => - new(value ?? "", index, length); -} +namespace Ramstack.Text; + +/// +/// Provides extension methods for the structure. +/// +public static class StringViewExtensions +{ + /// + /// Creates a new over a string. + /// + /// The string to create a view over. + /// + /// A representing the specified string. + /// + public static StringView AsView(this string? value) => + new(value ?? ""); + + /// + /// Creates a new over a portion of the specified string + /// starting at a specified position to the end of the string. + /// + /// The string to create a view over. + /// The zero-based starting position of the view in the string. + /// + /// A representing the specified portion of the string. + /// + public static StringView AsView(this string? value, int index) => + new(value ?? "", index); + + /// + /// Creates a new over a portion of the specified string + /// starting at a specified position for a specified number of characters. + /// + /// The string to create a view over. + /// The zero-based starting position of the view in the string. + /// The number of characters to include in the view. + /// + /// A representing the specified portion of the string. + /// + public static StringView AsView(this string? value, int index, int length) => + new(value ?? "", index, length); +}