| | | 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 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Collections; |
| | | 6 | | using System.Collections.Generic; |
| | | 7 | | |
| | | 8 | | namespace System.Text |
| | | 9 | | { |
| | | 10 | | // An enumerator for retrieving System.Text.Rune instances from a ROS<char>. |
| | | 11 | | // Methods are pattern-matched by compiler to allow using foreach pattern. |
| | | 12 | | public ref struct SpanRuneEnumerator : IEnumerator<Rune> |
| | | 13 | | { |
| | | 14 | | private ReadOnlySpan<char> _remaining; |
| | | 15 | | private Rune _current; |
| | | 16 | | |
| | | 17 | | internal SpanRuneEnumerator(ReadOnlySpan<char> buffer) |
| | | 18 | | { |
| | 0 | 19 | | _remaining = buffer; |
| | 0 | 20 | | _current = default; |
| | 0 | 21 | | } |
| | | 22 | | |
| | 0 | 23 | | public Rune Current => _current; |
| | | 24 | | |
| | 0 | 25 | | public SpanRuneEnumerator GetEnumerator() => this; |
| | | 26 | | |
| | | 27 | | public bool MoveNext() |
| | | 28 | | { |
| | 0 | 29 | | if (_remaining.IsEmpty) |
| | | 30 | | { |
| | | 31 | | // reached the end of the buffer |
| | 0 | 32 | | _current = default; |
| | 0 | 33 | | return false; |
| | | 34 | | } |
| | | 35 | | |
| | 0 | 36 | | int scalarValue = Rune.ReadFirstRuneFromUtf16Buffer(_remaining); |
| | 0 | 37 | | if (scalarValue < 0) |
| | | 38 | | { |
| | | 39 | | // replace invalid sequences with U+FFFD |
| | 0 | 40 | | scalarValue = Rune.ReplacementChar.Value; |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | // In UTF-16 specifically, invalid sequences always have length 1, which is the same |
| | | 44 | | // length as the replacement character U+FFFD. This means that we can always bump the |
| | | 45 | | // next index by the current scalar's UTF-16 sequence length. This optimization is not |
| | | 46 | | // generally applicable; for example, enumerating scalars from UTF-8 cannot utilize |
| | | 47 | | // this same trick. |
| | | 48 | | |
| | 0 | 49 | | _current = Rune.UnsafeCreate((uint)scalarValue); |
| | 0 | 50 | | _remaining = _remaining.Slice(_current.Utf16SequenceLength); |
| | 0 | 51 | | return true; |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | /// <inheritdoc /> |
| | 0 | 55 | | object IEnumerator.Current => Current; |
| | | 56 | | |
| | | 57 | | /// <inheritdoc /> |
| | 0 | 58 | | void IEnumerator.Reset() => throw new NotSupportedException(); |
| | | 59 | | |
| | | 60 | | /// <inheritdoc /> |
| | 0 | 61 | | void IDisposable.Dispose() { } |
| | | 62 | | } |
| | | 63 | | } |
| | | 64 | | |