Skip to content

O(1) bit shift operation for UInt128#1085

Open
pacowong wants to merge 5 commits into
krzyzanowskim:mainfrom
pacowong:main
Open

O(1) bit shift operation for UInt128#1085
pacowong wants to merge 5 commits into
krzyzanowskim:mainfrom
pacowong:main

Conversation

@pacowong

@pacowong pacowong commented Jun 10, 2026

Copy link
Copy Markdown

Fixes #

Checklist:

  • Correct file headers (see CONTRIBUTING.md).
  • Formatted with SwiftFormat.
  • Tests added.

Changes proposed in this pull request:

  • Replace the O(n) loop-based >> right-shift operator on UInt128 with 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))).

pacowong added 3 commits June 10, 2026 10:02
Signed-off-by: pacowong <paco@goodnotesapp.com>
Signed-off-by: pacowong <paco@goodnotesapp.com>
@pacowong pacowong requested a review from krzyzanowskim as a code owner June 10, 2026 08:47
pacowong and others added 2 commits June 10, 2026 16:57
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
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])

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

modified by swiftformat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant