Skip to content

Add checked arithmetic functions to addresses, pages, and frames - #616

Open
mkroening wants to merge 4 commits into
rust-osdev:masterfrom
mkroening:checked-ops
Open

mkroening wants to merge 4 commits into
rust-osdev:masterfrom
mkroening:checked-ops

Conversation

@mkroening

@mkroening mkroening commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

This adds checked_add and checked_sub const functions corresponding to the current Add and Sub implementations for:

  • VirtAddr
  • PhysAddr
  • Page
  • PhysFrame
  • MappedPage (not public)
  • MappedPageItem (not public)

Note that this changes the panic behavior for Page and PhysFrame, since rhs * S::SIZE did not panic before without overflow checks, such as in the release profile.

Also note that this PR does not add a checked version for subtracting two addresses, two pages, or two frames yet, but these would require a different function name. I don't require them personally at the moment. Would you like me to add them anyway? They could be called checked_offset_from, similar to the corresponding pointer types functions in std. If you prefer, we can also defer this. Adding such methods should not be breaking.

This PR is needed for #617 for #611. The approach was discussed in #611 (comment).

This PR is best reviewed commit by commit.

Fixes #293.

@mkroening
mkroening force-pushed the checked-ops branch 2 times, most recently from 84e49d5 to 1c7127a Compare September 25, 2026 16:23
Note that this does not add a checked version for subtracting two addresses yet.
Note that this changes the panic behavior, since `rhs * S::SIZE` did not panic before without overflow checks.
Note that this does not add a checked version for subtracting two pages or frames yet.
@mkroening

Copy link
Copy Markdown
Member Author

CI just made me notice #[const_fn(cfg(not(feature = "memory_encryption")))] on PhysAddr::new().

This is really unfortunate, since any crate in the crate graph that enables this feature makes other code in other crates not compile anymore. I don't know if we have any perspective on fixing that and whether we should open an issue for that.

@mkroening

Copy link
Copy Markdown
Member Author

I just noticed #293. That issue proposes traits. This PR adds inherent methods instead, as is done for integers in the standard library. What would you prefer? I'll mark this PR as closing that issue. Please let me know if I should undo that.

This branch has not been deployed

No deployments
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.

Define CheckedAdd and CheckedSub traits

1 participant