├── .gitignore
├── LICENSE
├── README.md
└── src
├── Contrib.Bcl.Ranges
├── Contrib.Bcl.Ranges.csproj
├── ForwardedTypes.cs
├── Index.cs
├── Range.cs
├── RuntimeHelpers.cs
└── StringBuilderCache.cs
├── Directory.Build.props
├── global.json
└── refs
└── Contrib.Bcl.Ranges.Ref
└── Contrib.Bcl.Ranges.Ref.csproj
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/rider,visualstudio,visualstudiocode
3 | # Edit at https://www.gitignore.io/?templates=rider,visualstudio,visualstudiocode
4 |
5 | ### Rider ###
6 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
7 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
8 |
9 | # User-specific stuff
10 | .idea/**/workspace.xml
11 | .idea/**/tasks.xml
12 | .idea/**/usage.statistics.xml
13 | .idea/**/dictionaries
14 | .idea/**/shelf
15 |
16 | # Generated files
17 | .idea/**/contentModel.xml
18 |
19 | # Sensitive or high-churn files
20 | .idea/**/dataSources/
21 | .idea/**/dataSources.ids
22 | .idea/**/dataSources.local.xml
23 | .idea/**/sqlDataSources.xml
24 | .idea/**/dynamic.xml
25 | .idea/**/uiDesigner.xml
26 | .idea/**/dbnavigator.xml
27 |
28 | # Gradle
29 | .idea/**/gradle.xml
30 | .idea/**/libraries
31 |
32 | # Gradle and Maven with auto-import
33 | # When using Gradle or Maven with auto-import, you should exclude module files,
34 | # since they will be recreated, and may cause churn. Uncomment if using
35 | # auto-import.
36 | # .idea/modules.xml
37 | # .idea/*.iml
38 | # .idea/modules
39 | # *.iml
40 | # *.ipr
41 |
42 | # CMake
43 | cmake-build-*/
44 |
45 | # Mongo Explorer plugin
46 | .idea/**/mongoSettings.xml
47 |
48 | # File-based project format
49 | *.iws
50 |
51 | # IntelliJ
52 | out/
53 |
54 | # mpeltonen/sbt-idea plugin
55 | .idea_modules/
56 |
57 | # JIRA plugin
58 | atlassian-ide-plugin.xml
59 |
60 | # Cursive Clojure plugin
61 | .idea/replstate.xml
62 |
63 | # Crashlytics plugin (for Android Studio and IntelliJ)
64 | com_crashlytics_export_strings.xml
65 | crashlytics.properties
66 | crashlytics-build.properties
67 | fabric.properties
68 |
69 | # Editor-based Rest Client
70 | .idea/httpRequests
71 |
72 | # Android studio 3.1+ serialized cache file
73 | .idea/caches/build_file_checksums.ser
74 |
75 | ### VisualStudioCode ###
76 | .vscode/*
77 | !.vscode/settings.json
78 | !.vscode/tasks.json
79 | !.vscode/launch.json
80 | !.vscode/extensions.json
81 |
82 | ### VisualStudioCode Patch ###
83 | # Ignore all local history of files
84 | .history
85 |
86 | ### VisualStudio ###
87 | ## Ignore Visual Studio temporary files, build results, and
88 | ## files generated by popular Visual Studio add-ons.
89 | ##
90 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
91 |
92 | # User-specific files
93 | *.rsuser
94 | *.suo
95 | *.user
96 | *.userosscache
97 | *.sln.docstates
98 |
99 | # User-specific files (MonoDevelop/Xamarin Studio)
100 | *.userprefs
101 |
102 | # Mono auto generated files
103 | mono_crash.*
104 |
105 | # Build results
106 | [Dd]ebug/
107 | [Dd]ebugPublic/
108 | [Rr]elease/
109 | [Rr]eleases/
110 | x64/
111 | x86/
112 | [Aa][Rr][Mm]/
113 | [Aa][Rr][Mm]64/
114 | bld/
115 | [Bb]in/
116 | [Oo]bj/
117 | [Ll]og/
118 |
119 | # Visual Studio 2015/2017 cache/options directory
120 | .vs/
121 | # Uncomment if you have tasks that create the project's static files in wwwroot
122 | #wwwroot/
123 |
124 | # Visual Studio 2017 auto generated files
125 | Generated\ Files/
126 |
127 | # MSTest test Results
128 | [Tt]est[Rr]esult*/
129 | [Bb]uild[Ll]og.*
130 |
131 | # NUnit
132 | *.VisualState.xml
133 | TestResult.xml
134 | nunit-*.xml
135 |
136 | # Build Results of an ATL Project
137 | [Dd]ebugPS/
138 | [Rr]eleasePS/
139 | dlldata.c
140 |
141 | # Benchmark Results
142 | BenchmarkDotNet.Artifacts/
143 |
144 | # .NET Core
145 | project.lock.json
146 | project.fragment.lock.json
147 | artifacts/
148 |
149 | # StyleCop
150 | StyleCopReport.xml
151 |
152 | # Files built by Visual Studio
153 | *_i.c
154 | *_p.c
155 | *_h.h
156 | *.ilk
157 | *.meta
158 | *.obj
159 | *.iobj
160 | *.pch
161 | *.pdb
162 | *.ipdb
163 | *.pgc
164 | *.pgd
165 | *.rsp
166 | *.sbr
167 | *.tlb
168 | *.tli
169 | *.tlh
170 | *.tmp
171 | *.tmp_proj
172 | *_wpftmp.csproj
173 | *.log
174 | *.vspscc
175 | *.vssscc
176 | .builds
177 | *.pidb
178 | *.svclog
179 | *.scc
180 |
181 | # Chutzpah Test files
182 | _Chutzpah*
183 |
184 | # Visual C++ cache files
185 | ipch/
186 | *.aps
187 | *.ncb
188 | *.opendb
189 | *.opensdf
190 | *.sdf
191 | *.cachefile
192 | *.VC.db
193 | *.VC.VC.opendb
194 |
195 | # Visual Studio profiler
196 | *.psess
197 | *.vsp
198 | *.vspx
199 | *.sap
200 |
201 | # Visual Studio Trace Files
202 | *.e2e
203 |
204 | # TFS 2012 Local Workspace
205 | $tf/
206 |
207 | # Guidance Automation Toolkit
208 | *.gpState
209 |
210 | # ReSharper is a .NET coding add-in
211 | _ReSharper*/
212 | *.[Rr]e[Ss]harper
213 | *.DotSettings.user
214 |
215 | # JustCode is a .NET coding add-in
216 | .JustCode
217 |
218 | # TeamCity is a build add-in
219 | _TeamCity*
220 |
221 | # DotCover is a Code Coverage Tool
222 | *.dotCover
223 |
224 | # AxoCover is a Code Coverage Tool
225 | .axoCover/*
226 | !.axoCover/settings.json
227 |
228 | # Visual Studio code coverage results
229 | *.coverage
230 | *.coveragexml
231 |
232 | # NCrunch
233 | _NCrunch_*
234 | .*crunch*.local.xml
235 | nCrunchTemp_*
236 |
237 | # MightyMoose
238 | *.mm.*
239 | AutoTest.Net/
240 |
241 | # Web workbench (sass)
242 | .sass-cache/
243 |
244 | # Installshield output folder
245 | [Ee]xpress/
246 |
247 | # DocProject is a documentation generator add-in
248 | DocProject/buildhelp/
249 | DocProject/Help/*.HxT
250 | DocProject/Help/*.HxC
251 | DocProject/Help/*.hhc
252 | DocProject/Help/*.hhk
253 | DocProject/Help/*.hhp
254 | DocProject/Help/Html2
255 | DocProject/Help/html
256 |
257 | # Click-Once directory
258 | publish/
259 |
260 | # Publish Web Output
261 | *.[Pp]ublish.xml
262 | *.azurePubxml
263 | # Note: Comment the next line if you want to checkin your web deploy settings,
264 | # but database connection strings (with potential passwords) will be unencrypted
265 | *.pubxml
266 | *.publishproj
267 |
268 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
269 | # checkin your Azure Web App publish settings, but sensitive information contained
270 | # in these scripts will be unencrypted
271 | PublishScripts/
272 |
273 | # NuGet Packages
274 | *.nupkg
275 | # NuGet Symbol Packages
276 | *.snupkg
277 | # The packages folder can be ignored because of Package Restore
278 | **/[Pp]ackages/*
279 | # except build/, which is used as an MSBuild target.
280 | !**/[Pp]ackages/build/
281 | # Uncomment if necessary however generally it will be regenerated when needed
282 | #!**/[Pp]ackages/repositories.config
283 | # NuGet v3's project.json files produces more ignorable files
284 | *.nuget.props
285 | *.nuget.targets
286 |
287 | # Microsoft Azure Build Output
288 | csx/
289 | *.build.csdef
290 |
291 | # Microsoft Azure Emulator
292 | ecf/
293 | rcf/
294 |
295 | # Windows Store app package directories and files
296 | AppPackages/
297 | BundleArtifacts/
298 | Package.StoreAssociation.xml
299 | _pkginfo.txt
300 | *.appx
301 | *.appxbundle
302 | *.appxupload
303 |
304 | # Visual Studio cache files
305 | # files ending in .cache can be ignored
306 | *.[Cc]ache
307 | # but keep track of directories ending in .cache
308 | !?*.[Cc]ache/
309 |
310 | # Others
311 | ClientBin/
312 | ~$*
313 | *~
314 | *.dbmdl
315 | *.dbproj.schemaview
316 | *.jfm
317 | *.pfx
318 | *.publishsettings
319 | orleans.codegen.cs
320 |
321 | # Including strong name files can present a security risk
322 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
323 | #*.snk
324 |
325 | # Since there are multiple workflows, uncomment next line to ignore bower_components
326 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
327 | #bower_components/
328 |
329 | # RIA/Silverlight projects
330 | Generated_Code/
331 |
332 | # Backup & report files from converting an old project file
333 | # to a newer Visual Studio version. Backup files are not needed,
334 | # because we have git ;-)
335 | _UpgradeReport_Files/
336 | Backup*/
337 | UpgradeLog*.XML
338 | UpgradeLog*.htm
339 | ServiceFabricBackup/
340 | *.rptproj.bak
341 |
342 | # SQL Server files
343 | *.mdf
344 | *.ldf
345 | *.ndf
346 |
347 | # Business Intelligence projects
348 | *.rdl.data
349 | *.bim.layout
350 | *.bim_*.settings
351 | *.rptproj.rsuser
352 | *- [Bb]ackup.rdl
353 | *- [Bb]ackup ([0-9]).rdl
354 | *- [Bb]ackup ([0-9][0-9]).rdl
355 |
356 | # Microsoft Fakes
357 | FakesAssemblies/
358 |
359 | # GhostDoc plugin setting file
360 | *.GhostDoc.xml
361 |
362 | # Node.js Tools for Visual Studio
363 | .ntvs_analysis.dat
364 | node_modules/
365 |
366 | # Visual Studio 6 build log
367 | *.plg
368 |
369 | # Visual Studio 6 workspace options file
370 | *.opt
371 |
372 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
373 | *.vbw
374 |
375 | # Visual Studio LightSwitch build output
376 | **/*.HTMLClient/GeneratedArtifacts
377 | **/*.DesktopClient/GeneratedArtifacts
378 | **/*.DesktopClient/ModelManifest.xml
379 | **/*.Server/GeneratedArtifacts
380 | **/*.Server/ModelManifest.xml
381 | _Pvt_Extensions
382 |
383 | # Paket dependency manager
384 | .paket/paket.exe
385 | paket-files/
386 |
387 | # FAKE - F# Make
388 | .fake/
389 |
390 | # CodeRush personal settings
391 | .cr/personal
392 |
393 | # Python Tools for Visual Studio (PTVS)
394 | __pycache__/
395 | *.pyc
396 |
397 | # Cake - Uncomment if you are using it
398 | # tools/**
399 | # !tools/packages.config
400 |
401 | # Tabs Studio
402 | *.tss
403 |
404 | # Telerik's JustMock configuration file
405 | *.jmconfig
406 |
407 | # BizTalk build output
408 | *.btp.cs
409 | *.btm.cs
410 | *.odx.cs
411 | *.xsd.cs
412 |
413 | # OpenCover UI analysis results
414 | OpenCover/
415 |
416 | # Azure Stream Analytics local run output
417 | ASALocalRun/
418 |
419 | # MSBuild Binary and Structured Log
420 | *.binlog
421 |
422 | # NVidia Nsight GPU debugger configuration file
423 | *.nvuser
424 |
425 | # MFractors (Xamarin productivity tool) working folder
426 | .mfractor/
427 |
428 | # Local History for Visual Studio
429 | .localhistory/
430 |
431 | # BeatPulse healthcheck temp database
432 | healthchecksdb
433 |
434 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
435 | MigrationBackup/
436 |
437 | # End of https://www.gitignore.io/api/rider,visualstudio,visualstudiocode
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Stuart Lang
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Contrib.Bcl.Ranges
2 |
3 | This package polyfills the types required for the C# 8.0 feature [Ranges](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges) on targets lower than `netcoreapp3.0` and `netstandard2.1`. This includes:
4 | - .NET Framework - starting from `net461`
5 | - .NET Standard 2.0 Compatible Runtimes - this includes .NET Core 2.x
6 |
7 | ## Usage
8 |
9 | Add this to your `csproj` file:
10 | ```xml
11 |
12 | ```
13 | and add this to the `PropertyGroup`:
14 | ```xml
15 | 8.0
16 | ```
17 |
18 | Now we can start using this handy new language feature 😀
19 | ```csharp
20 | Console.WriteLine("Hello world!"[6..^1]); // world
21 | ```
22 |
--------------------------------------------------------------------------------
/src/Contrib.Bcl.Ranges/Contrib.Bcl.Ranges.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net461;net47;netstandard2.0;netstandard2.1
5 |
6 |
7 | $(DefineConstants),NO_RANGES_SUPPORT
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/src/Contrib.Bcl.Ranges/ForwardedTypes.cs:
--------------------------------------------------------------------------------
1 | #if (REFERENCE_ASSEMBLY && !NO_RANGES_SUPPORT)
2 | using System.Runtime.CompilerServices;
3 |
4 | [assembly: TypeForwardedTo(typeof(System.Range))]
5 | [assembly: TypeForwardedTo(typeof(System.Index))]
6 |
7 | #endif
--------------------------------------------------------------------------------
/src/Contrib.Bcl.Ranges/Index.cs:
--------------------------------------------------------------------------------
1 | // Licensed to the .NET Foundation under one or more agreements.
2 | // The .NET Foundation licenses this file to you under the MIT license.
3 | // See the LICENSE file in the project root for more information.
4 |
5 | #if NO_RANGES_SUPPORT
6 | using System.Runtime.CompilerServices;
7 |
8 | namespace System
9 | {
10 | /// Represent a type can be used to index a collection either from the start or the end.
11 | ///
12 | /// Index is used by the C# compiler to support the new index syntax
13 | ///
14 | /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ;
15 | /// int lastElement = someArray[^1]; // lastElement = 5
16 | ///
17 | ///
18 | public readonly struct Index : IEquatable
19 | {
20 | private readonly int _value;
21 |
22 | /// Construct an Index using a value and indicating if the index is from the start or from the end.
23 | /// The index value. it has to be zero or positive number.
24 | /// Indicating if the index is from the start or from the end.
25 | ///
26 | /// If the Index constructed from the end, index value 1 means pointing at the last element and index value 0 means pointing at beyond last element.
27 | ///
28 | [MethodImpl(MethodImplOptions.AggressiveInlining)]
29 | public Index(int value, bool fromEnd = false)
30 | {
31 | if (value < 0)
32 | {
33 | throw new ArgumentOutOfRangeException(nameof(value));
34 | }
35 |
36 | if (fromEnd)
37 | _value = ~value;
38 | else
39 | _value = value;
40 | }
41 |
42 | // The following private constructors mainly created for perf reason to avoid the checks
43 | private Index(int value)
44 | {
45 | _value = value;
46 | }
47 |
48 | /// Create an Index pointing at first element.
49 | public static Index Start => new Index(0);
50 |
51 | /// Create an Index pointing at beyond last element.
52 | public static Index End => new Index(~0);
53 |
54 | /// Create an Index from the start at the position indicated by the value.
55 | /// The index value from the start.
56 | [MethodImpl(MethodImplOptions.AggressiveInlining)]
57 | public static Index FromStart(int value)
58 | {
59 | if (value < 0)
60 | {
61 | throw new ArgumentOutOfRangeException(nameof(value));
62 | }
63 |
64 | return new Index(value);
65 | }
66 |
67 | /// Create an Index from the end at the position indicated by the value.
68 | /// The index value from the end.
69 | [MethodImpl(MethodImplOptions.AggressiveInlining)]
70 | public static Index FromEnd(int value)
71 | {
72 | if (value < 0)
73 | {
74 | throw new ArgumentOutOfRangeException(nameof(value));
75 | }
76 |
77 | return new Index(~value);
78 | }
79 |
80 | /// Returns the index value.
81 | public int Value
82 | {
83 | get
84 | {
85 | if (_value < 0)
86 | return ~_value;
87 | else
88 | return _value;
89 | }
90 | }
91 |
92 | /// Indicates whether the index is from the start or the end.
93 | public bool IsFromEnd => _value < 0;
94 |
95 | /// Calculate the offset from the start using the giving collection length.
96 | /// The length of the collection that the Index will be used with. length has to be a positive value
97 | ///
98 | /// For performance reason, we don't validate the input length parameter and the returned offset value against negative values.
99 | /// we don't validate either the returned offset is greater than the input length.
100 | /// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and
101 | /// then used to index a collection will get out of range exception which will be same affect as the validation.
102 | ///
103 | [MethodImpl(MethodImplOptions.AggressiveInlining)]
104 | public int GetOffset(int length)
105 | {
106 | int offset = _value;
107 | if (IsFromEnd)
108 | {
109 | // offset = length - (~value)
110 | // offset = length + (~(~value) + 1)
111 | // offset = length + value + 1
112 |
113 | offset += length + 1;
114 | }
115 | return offset;
116 | }
117 |
118 | /// Indicates whether the current Index object is equal to another object of the same type.
119 | /// An object to compare with this object
120 | public override bool Equals(object value) => value is Index && _value == ((Index)value)._value;
121 |
122 | /// Indicates whether the current Index object is equal to another Index object.
123 | /// An object to compare with this object
124 | public bool Equals(Index other) => _value == other._value;
125 |
126 | /// Returns the hash code for this instance.
127 | public override int GetHashCode() => _value;
128 |
129 | /// Converts integer number to an Index.
130 | public static implicit operator Index(int value) => FromStart(value);
131 |
132 | /// Converts the value of the current Index object to its equivalent string representation.
133 | public override string ToString()
134 | {
135 | if (IsFromEnd)
136 | return ToStringFromEnd();
137 |
138 | return ((uint)Value).ToString();
139 | }
140 |
141 | private string ToStringFromEnd()
142 | {
143 | var sb = StringBuilderCache.Acquire(11); // 1 for ^ and 10 for longest possible uint value
144 |
145 | sb.Append((uint) Value);
146 | sb.Append('^');
147 |
148 | return StringBuilderCache.GetStringAndRelease(sb);
149 | }
150 | }
151 | }
152 | #endif
--------------------------------------------------------------------------------
/src/Contrib.Bcl.Ranges/Range.cs:
--------------------------------------------------------------------------------
1 | // Licensed to the .NET Foundation under one or more agreements.
2 | // The .NET Foundation licenses this file to you under the MIT license.
3 | // See the LICENSE file in the project root for more information.
4 |
5 | #if NO_RANGES_SUPPORT
6 | using System.Runtime.CompilerServices;
7 |
8 | namespace System
9 | {
10 | /// Represent a range has start and end indexes.
11 | ///
12 | /// Range is used by the C# compiler to support the range syntax.
13 | ///
14 | /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 };
15 | /// int[] subArray1 = someArray[0..2]; // { 1, 2 }
16 | /// int[] subArray2 = someArray[1..^0]; // { 2, 3, 4, 5 }
17 | ///
18 | ///
19 | public readonly struct Range : IEquatable
20 | {
21 | /// Represent the inclusive start index of the Range.
22 | public Index Start { get; }
23 |
24 | /// Represent the exclusive end index of the Range.
25 | public Index End { get; }
26 |
27 | /// Construct a Range object using the start and end indexes.
28 | /// Represent the inclusive start index of the range.
29 | /// Represent the exclusive end index of the range.
30 | public Range(Index start, Index end)
31 | {
32 | Start = start;
33 | End = end;
34 | }
35 |
36 | /// Indicates whether the current Range object is equal to another object of the same type.
37 | /// An object to compare with this object
38 | public override bool Equals(object value) =>
39 | value is Range r &&
40 | r.Start.Equals(Start) &&
41 | r.End.Equals(End);
42 |
43 | /// Indicates whether the current Range object is equal to another Range object.
44 | /// An object to compare with this object
45 | public bool Equals(Range other) => other.Start.Equals(Start) && other.End.Equals(End);
46 |
47 | /// Returns the hash code for this instance.
48 | public override int GetHashCode()
49 | {
50 | return Combine(Start.GetHashCode(), End.GetHashCode());
51 | }
52 |
53 | /// Converts the value of the current Range object to its equivalent string representation.
54 | public override string ToString()
55 | {
56 | var sb = StringBuilderCache.Acquire(2 + (2 * 11)); // 2 for "..", then for each index 1 for '^' and 10 for longest possible uint
57 |
58 | if (Start.IsFromEnd)
59 | {
60 | sb.Append('^');
61 | }
62 |
63 | sb.Append((uint)Start.Value);
64 | sb.Append("..");
65 |
66 | if (End.IsFromEnd)
67 | {
68 | sb.Append('^');
69 | }
70 |
71 | sb.Append((uint) End.Value);
72 |
73 | return StringBuilderCache.GetStringAndRelease(sb);
74 | }
75 |
76 | /// Create a Range object starting from start index to the end of the collection.
77 | public static Range StartAt(Index start) => new Range(start, Index.End);
78 |
79 | /// Create a Range object starting from first element in the collection to the end Index.
80 | public static Range EndAt(Index end) => new Range(Index.Start, end);
81 |
82 | /// Create a Range object starting from first element to the end.
83 | public static Range All => new Range(Index.Start, Index.End);
84 |
85 | /// Calculate the start offset and length of range object using a collection length.
86 | /// The length of the collection that the range will be used with. length has to be a positive value.
87 | ///
88 | /// For performance reason, we don't validate the input length parameter against negative values.
89 | /// It is expected Range will be used with collections which always have non negative length/count.
90 | /// We validate the range is inside the length scope though.
91 | ///
92 | [MethodImpl(MethodImplOptions.AggressiveInlining)]
93 | public (int Offset, int Length) GetOffsetAndLength(int length)
94 | {
95 | int start;
96 | Index startIndex = Start;
97 | if (startIndex.IsFromEnd)
98 | start = length - startIndex.Value;
99 | else
100 | start = startIndex.Value;
101 |
102 | int end;
103 | Index endIndex = End;
104 | if (endIndex.IsFromEnd)
105 | end = length - endIndex.Value;
106 | else
107 | end = endIndex.Value;
108 |
109 | if ((uint)end > (uint)length || (uint)start > (uint)end)
110 | {
111 | throw new ArgumentOutOfRangeException();
112 | }
113 |
114 | return (start, end - start);
115 | }
116 |
117 | static int Combine(T1 value1, T2 value2)
118 | {
119 | return HashCode.Combine(value1?.GetHashCode() ?? 0, value2?.GetHashCode() ?? 0);
120 | }
121 | }
122 | }
123 | #endif
--------------------------------------------------------------------------------
/src/Contrib.Bcl.Ranges/RuntimeHelpers.cs:
--------------------------------------------------------------------------------
1 | // Licensed to the .NET Foundation under one or more agreements.
2 | // The .NET Foundation licenses this file to you under the MIT license.
3 | // See the LICENSE file in the project root for more information.
4 |
5 | #if NO_RANGES_SUPPORT
6 | using System;
7 |
8 | namespace System.Runtime.CompilerServices
9 | {
10 | public static partial class RuntimeHelpers
11 | {
12 | public static int get_IndexerExtension(this int[] array, Index index) =>
13 | index.IsFromEnd ? array[array.Length - index.Value] : array[index.Value];
14 |
15 | public static int get_IndexerExtension(this Span span, Index index) =>
16 | index.IsFromEnd ? span[span.Length - index.Value] : span[index.Value];
17 |
18 | public static char get_IndexerExtension(this string s, Index index) =>
19 | index.IsFromEnd ? s[s.Length - index.Value] : s[index.Value];
20 |
21 | public static Span get_IndexerExtension(this int[] array, Range range) =>
22 | array.Slice(range);
23 |
24 | public static Span get_IndexerExtension(this Span span, Range range) =>
25 | span.Slice(range);
26 |
27 | public static string get_IndexerExtension(this string s, Range range) =>
28 | s.Substring(range);
29 |
30 | public static Span Slice(this T[] array, Range range)
31 | => array.AsSpan().Slice(range);
32 |
33 | public static Span Slice(this Span span, Range range)
34 | {
35 | var (start, length) = GetStartAndLength(range, span.Length);
36 | return span.Slice(start, length);
37 | }
38 |
39 | public static string Substring(this string s, Range range)
40 | {
41 | var (start, length) = GetStartAndLength(range, s.Length);
42 | return s.Substring(start, length);
43 | }
44 |
45 | private static (int start, int length) GetStartAndLength(Range range, int entityLength)
46 | {
47 | var start = range.Start.IsFromEnd ? entityLength - range.Start.Value : range.Start.Value;
48 | var end = range.End.IsFromEnd ? entityLength - range.End.Value : range.End.Value;
49 | var length = end - start;
50 |
51 | return (start, length);
52 | }
53 |
54 | ///
55 | /// Slices the specified array using the specified range.
56 | ///
57 | public static T[] GetSubArray(T[] array, Range range)
58 | {
59 | if (array == null)
60 | {
61 | throw new ArgumentNullException(nameof(array));
62 | }
63 |
64 | (int offset, int length) = range.GetOffsetAndLength(array.Length);
65 |
66 | if (default(T) != null || typeof(T[]) == array.GetType())
67 | {
68 | // We know the type of the array to be exactly T[].
69 |
70 | if (length == 0)
71 | {
72 | return Array.Empty();
73 | }
74 |
75 | var dest = new T[length];
76 | Array.Copy(array, offset, dest, 0, length);
77 | return dest;
78 | }
79 | else
80 | {
81 | // The array is actually a U[] where U:T.
82 | T[] dest = (T[])Array.CreateInstance(array.GetType().GetElementType(), length);
83 | Array.Copy(array, offset, dest, 0, length);
84 | return dest;
85 | }
86 | }
87 | }
88 | }
89 | #endif
--------------------------------------------------------------------------------
/src/Contrib.Bcl.Ranges/StringBuilderCache.cs:
--------------------------------------------------------------------------------
1 | // Licensed to the .NET Foundation under one or more agreements.
2 | // The .NET Foundation licenses this file to you under the MIT license.
3 | // See the LICENSE file in the project root for more information.
4 |
5 | #if NO_RANGES_SUPPORT
6 | using System.Text;
7 |
8 | namespace System
9 | {
10 | /// Provide a cached reusable instance of stringbuilder per thread.
11 | internal static class StringBuilderCache
12 | {
13 | // The value 360 was chosen in discussion with performance experts as a compromise between using
14 | // as litle memory per thread as possible and still covering a large part of short-lived
15 | // StringBuilder creations on the startup path of VS designers.
16 | private const int MaxBuilderSize = 360;
17 | private const int DefaultCapacity = 16; // == StringBuilder.DefaultCapacity
18 |
19 | // WARNING: We allow diagnostic tools to directly inspect this member (t_cachedInstance).
20 | // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
21 | // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
22 | // Get in touch with the diagnostics team if you have questions.
23 | [ThreadStatic]
24 | private static StringBuilder t_cachedInstance;
25 |
26 | /// Get a StringBuilder for the specified capacity.
27 | /// If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.
28 | public static StringBuilder Acquire(int capacity = DefaultCapacity)
29 | {
30 | if (capacity <= MaxBuilderSize)
31 | {
32 | StringBuilder sb = t_cachedInstance;
33 | if (sb != null)
34 | {
35 | // Avoid stringbuilder block fragmentation by getting a new StringBuilder
36 | // when the requested size is larger than the current capacity
37 | if (capacity <= sb.Capacity)
38 | {
39 | t_cachedInstance = null;
40 | sb.Clear();
41 | return sb;
42 | }
43 | }
44 | }
45 |
46 | return new StringBuilder(capacity);
47 | }
48 |
49 | /// Place the specified builder in the cache if it is not too big.
50 | public static void Release(StringBuilder sb)
51 | {
52 | if (sb.Capacity <= MaxBuilderSize)
53 | {
54 | t_cachedInstance = sb;
55 | }
56 | }
57 |
58 | /// ToString() the stringbuilder, Release it to the cache, and return the resulting string.
59 | public static string GetStringAndRelease(StringBuilder sb)
60 | {
61 | string result = sb.ToString();
62 | Release(sb);
63 | return result;
64 | }
65 | }
66 | }
67 | #endif
--------------------------------------------------------------------------------
/src/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | 1.0.0
4 |
5 |
--------------------------------------------------------------------------------
/src/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "3.0.100"
4 | },
5 | "msbuild-sdks": {
6 | "MSBuild.Sdk.Extras": "2.0.41"
7 | }
8 | }
--------------------------------------------------------------------------------
/src/refs/Contrib.Bcl.Ranges.Ref/Contrib.Bcl.Ranges.Ref.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net461;net47;netstandard2.0;netstandard2.1
5 |
6 |
7 | $(DefineConstants),NO_RANGES_SUPPORT
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------