| | | 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.Collections; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | |
| | | 7 | | namespace System.Text |
| | | 8 | | { |
| | | 9 | | // An enumerator for retrieving System.Text.Rune instances from a System.String. |
| | | 10 | | public struct StringRuneEnumerator : IEnumerable<Rune>, IEnumerator<Rune> |
| | | 11 | | { |
| | | 12 | | private readonly string _string; |
| | | 13 | | private Rune _current; |
| | | 14 | | private int _nextIndex; |
| | | 15 | | |
| | | 16 | | internal StringRuneEnumerator(string value) |
| | | 17 | | { |
| | 0 | 18 | | _string = value; |
| | 0 | 19 | | _current = default; |
| | 0 | 20 | | _nextIndex = 0; |
| | 0 | 21 | | } |
| | | 22 | | |
| | 0 | 23 | | public Rune Current => _current; |
| | | 24 | | |
| | 0 | 25 | | public StringRuneEnumerator GetEnumerator() => this; |
| | | 26 | | |
| | | 27 | | public bool MoveNext() |
| | | 28 | | { |
| | 0 | 29 | | if ((uint)_nextIndex >= _string.Length) |
| | | 30 | | { |
| | | 31 | | // reached the end of the string |
| | 0 | 32 | | _current = default; |
| | 0 | 33 | | return false; |
| | | 34 | | } |
| | | 35 | | |
| | 0 | 36 | | if (!Rune.TryGetRuneAt(_string, _nextIndex, out _current)) |
| | | 37 | | { |
| | | 38 | | // replace invalid sequences with U+FFFD |
| | 0 | 39 | | _current = Rune.ReplacementChar; |
| | | 40 | | } |
| | | 41 | | |
| | | 42 | | // In UTF-16 specifically, invalid sequences always have length 1, which is the same |
| | | 43 | | // length as the replacement character U+FFFD. This means that we can always bump the |
| | | 44 | | // next index by the current scalar's UTF-16 sequence length. This optimization is not |
| | | 45 | | // generally applicable; for example, enumerating scalars from UTF-8 cannot utilize |
| | | 46 | | // this same trick. |
| | | 47 | | |
| | 0 | 48 | | _nextIndex += _current.Utf16SequenceLength; |
| | 0 | 49 | | return true; |
| | | 50 | | } |
| | | 51 | | |
| | 0 | 52 | | object? IEnumerator.Current => _current; |
| | | 53 | | |
| | | 54 | | void IDisposable.Dispose() |
| | | 55 | | { |
| | | 56 | | // no-op |
| | 0 | 57 | | } |
| | | 58 | | |
| | 0 | 59 | | IEnumerator IEnumerable.GetEnumerator() => this; |
| | | 60 | | |
| | 0 | 61 | | IEnumerator<Rune> IEnumerable<Rune>.GetEnumerator() => this; |
| | | 62 | | |
| | | 63 | | void IEnumerator.Reset() |
| | | 64 | | { |
| | 0 | 65 | | _current = default; |
| | 0 | 66 | | _nextIndex = 0; |
| | 0 | 67 | | } |
| | | 68 | | } |
| | | 69 | | } |
| | | 70 | | |