Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

len() implementation without overflow errors #1516

Open
fpoli opened this issue May 28, 2024 · 1 comment
Open

len() implementation without overflow errors #1516

fpoli opened this issue May 28, 2024 · 1 comment
Labels
enhancement New feature or request

Comments

@fpoli
Copy link
Member

fpoli commented May 28, 2024

Viktor Kuncak (@vkuncak) suggested the following trick to implement a len() method that verifies with overflow checks enabled. They used it in Stainless:

impl Link {
    #[pure]
    #[ensures(result <= usize::MAX - 1)]
    fn len(&self) -> usize {
        match self {
            Link::Empty => 0,
            Link::More(node) => {
              let len1 = node.next.len();
              if len1 == usize::MAX - 1 {
                len1
              } else {
                len1 + 1
              }
            }
        }
    }
}
@fpoli fpoli added the enhancement New feature or request label May 28, 2024
@CleveGreen
Copy link

Using saturating arithmetic works for implementing len with overflow checks, but it complicates other specifications that depend on it.

One way to avoid enabling overflow checks for the entire project is to write an increment function and mark it as trusted, even though it might feel a bit unsatisfactory.

Perhaps dynamically sized number types would help with this? I was planning on taking a swing on implementing and verifying these tomorrow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants