Skip to content

Commit d4470aa

Browse files
[stdlib] Refactor UTF16 decode to use UInt16 locals
1 parent 2cce7db commit d4470aa

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

stdlib/public/core/Unicode.swift

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,7 @@ public struct UTF16 : UnicodeCodec {
440440
public init() {}
441441

442442
/// A lookahead buffer for one UTF-16 code unit.
443-
internal var _decodeLookahead: UInt32?
443+
internal var _decodeLookahead: UInt16?
444444

445445
/// Starts or continues decoding a UTF-16 sequence.
446446
///
@@ -490,10 +490,10 @@ public struct UTF16 : UnicodeCodec {
490490
// length 1. Length 0 does not make sense. Neither does length 2 -- in
491491
// that case the sequence is valid.
492492

493-
let unit0: UInt32
493+
let unit0: UInt16
494494
if _fastPath(_decodeLookahead == nil) {
495495
guard let next = input.next() else { return .emptyInput }
496-
unit0 = UInt32(next)
496+
unit0 = next
497497
} else { // Consume lookahead first.
498498
unit0 = _decodeLookahead!
499499
_decodeLookahead = nil
@@ -505,15 +505,14 @@ public struct UTF16 : UnicodeCodec {
505505

506506
// Common case first, non-surrogate -- just a sequence of 1 code unit.
507507
if _fastPath((unit0 >> 11) != 0b1101_1) {
508-
return .scalarValue(UnicodeScalar(_unchecked: unit0))
508+
return .scalarValue(UnicodeScalar(_unchecked: UInt32(unit0)))
509509
}
510510

511511
// Ensure `unit0` is a high-surrogate.
512512
guard _fastPath((unit0 >> 10) == 0b1101_10) else { return .error }
513513

514514
// We already have a high-surrogate, so there should be a next code unit.
515-
guard let next = input.next() else { return .error }
516-
let unit1 = UInt32(next)
515+
guard let unit1 = input.next() else { return .error }
517516

518517
// `unit0` is a high-surrogate, so `unit1` should be a low-surrogate.
519518
guard _fastPath((unit1 >> 10) == 0b1101_11) else {
@@ -523,7 +522,7 @@ public struct UTF16 : UnicodeCodec {
523522
}
524523

525524
// We have a well-formed surrogate pair, decode it.
526-
let result = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff))
525+
let result = 0x10000 + ((UInt32(unit0 & 0x03ff) << 10) | UInt32(unit1 & 0x03ff))
527526
return .scalarValue(UnicodeScalar(_unchecked: result))
528527
}
529528

0 commit comments

Comments
 (0)