O(1) bit shift operation for UInt128#1085
Open
pacowong wants to merge 5 commits into
Open
Conversation
Signed-off-by: pacowong <paco@goodnotesapp.com>
Signed-off-by: pacowong <paco@goodnotesapp.com>
Update UInt128.swift
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
pacowong
commented
Jun 10, 2026
Comment on lines
17
to
+36
| @@ -31,9 +31,9 @@ struct UInt128: Equatable, ExpressibleByIntegerLiteral { | |||
| init(_ raw: Array<UInt8>) { | |||
| precondition(raw.count >= 16, "UInt128 requires at least 16 bytes") | |||
| let a = UInt64(raw[0]) << 56 | UInt64(raw[1]) << 48 | UInt64(raw[2]) << 40 | UInt64(raw[3]) << 32 | | |||
| UInt64(raw[4]) << 24 | UInt64(raw[5]) << 16 | UInt64(raw[6]) << 8 | UInt64(raw[7]) | |||
| UInt64(raw[4]) << 24 | UInt64(raw[5]) << 16 | UInt64(raw[6]) << 8 | UInt64(raw[7]) | |||
| let b = UInt64(raw[8]) << 56 | UInt64(raw[9]) << 48 | UInt64(raw[10]) << 40 | UInt64(raw[11]) << 32 | | |||
| UInt64(raw[12]) << 24 | UInt64(raw[13]) << 16 | UInt64(raw[14]) << 8 | UInt64(raw[15]) | |||
| UInt64(raw[12]) << 24 | UInt64(raw[13]) << 16 | UInt64(raw[14]) << 8 | UInt64(raw[15]) | |||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #
Checklist:
Changes proposed in this pull request:
>>right-shift operator onUInt128with an O(1) direct bit-manipulation implementation. The previous code shifted one bit at a time in a loop (for _ in 0..<by), degrading linearly with the shift amount. The new implementation handles all cases in constant time: early exits for shift ≤ 0, shift ≥ 128, and shift ≥ 64, with a single-expression bit combine for the general case ((value.i.b >> by) | (value.i.a << (64 - by))).