From f4aa686374a9e34ee8fa33a8e02ef09b45f0dc3b Mon Sep 17 00:00:00 2001 From: tamcy Date: Mon, 25 Mar 2024 11:17:25 +0800 Subject: [PATCH] Add an optional offset argument to StringScanner.peekCodePoint to align with StringScanner.peekChar --- CHANGELOG.md | 4 +++- lib/src/string_scanner.dart | 12 ++++++++---- pubspec.yaml | 2 +- test/string_scanner_test.dart | 6 ++++++ 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa7af43..dacbfe0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,8 @@ -## 1.2.1-wip +## 1.3.0-wip * Require Dart 3.0.0 +* `StringScanner.peekCodePoint()` now accepts an optional `offset` argument like + `StringScanner.peekChar()`. ## 1.2.0 diff --git a/lib/src/string_scanner.dart b/lib/src/string_scanner.dart index 1466944..490727a 100644 --- a/lib/src/string_scanner.dart +++ b/lib/src/string_scanner.dart @@ -158,19 +158,23 @@ class StringScanner { return decodeSurrogatePair(first, next); } - /// Returns the Unicode code point immediately after [position]. + /// Returns the Unicode code point [offset] away from [position]. /// /// This works like [peekChar], except that it automatically handles UTF-16 /// surrogate pairs. Specifically, if the next two code units form a surrogate /// pair, returns the corresponding Unicode code point. /// + /// [offset] defaults to zero, and may be negative to inspect already-consumed + /// characters. + /// /// If next two characters are not a surrogate pair, the next code unit is /// returned as-is, even if it's an unpaired surrogate. - int? peekCodePoint() { - final first = peekChar(); + int? peekCodePoint([int? offset]) { + offset ??= 0; + final first = peekChar(offset); if (first == null || !isHighSurrogate(first)) return first; - final next = peekChar(1); + final next = peekChar(offset + 1); if (next == null || !isLowSurrogate(next)) return first; return decodeSurrogatePair(first, next); diff --git a/pubspec.yaml b/pubspec.yaml index 7ceb7d9..92a44cb 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: string_scanner -version: 1.2.1-wip +version: 1.3.0-wip description: A class for parsing strings using a sequence of patterns. repository: https://github.com/dart-lang/string_scanner diff --git a/test/string_scanner_test.dart b/test/string_scanner_test.dart index 36a737e..29f1199 100644 --- a/test/string_scanner_test.dart +++ b/test/string_scanner_test.dart @@ -154,6 +154,12 @@ void main() { expect(scanner.position, equals(0)); }); + test('peekCodePoint with an argument returns the nth character', () { + expect(scanner.peekCodePoint(4), equals(0x62)); + expect(scanner.lastMatch, isNull); + expect(scanner.position, equals(0)); + }); + test('a matching scanChar returns true moves forward', () { expect(scanner.scanChar($f), isTrue); expect(scanner.lastMatch, isNull);