dafny-lang / dafny

Dafny is a verification-aware programming language
https://dafny.org
Other
2.94k stars 261 forks source link

Optimization to use slice_usize in Rust #5857

Open ajewellamz opened 1 month ago

ajewellamz commented 1 month ago

Summary

Sequence slices should avoid conversions to and from DafnyInt when possible

Background and Motivation

Given the code

  function FindLength(s : seq<uint8>) : (ret : Result<uint64, Error>)

  method CheckSeq(bytes : seq<uint8>)
  {
    var result := FindLength(bytes);
    if result.Success? {
      var new_bytes := bytes[0..result.value];
     ...
  }

The slice operation is generated as

let mut new_bytes: Sequence<u8> = bytes.slice(&int!(0), &Into::<DafnyInt>::into(result.value().clone()));

which unnecessarily converts the two numbers into DafnyInts, only to be converted back to native numbers in Sequence::slice.

Proposed Feature

Instead generate

let mut new_bytes: Sequence<u8> = bytes.slice_usize(0, result.value().clone() as usize);

where Sequence::slice_usize is the obvious extension of Sequence::slice

    pub fn slice_usize(&self, start_index: usize, end_index: usize) -> Sequence<T> {
        let new_data = Sequence::from_array_owned(self.to_array()[start_index..end_index].to_vec());
        new_data
    }

Alternatives

No response

robin-aws commented 1 month ago

@ajewellamz I edited your description just to add code blocks because I was having trouble parsing it, hope you don't mind. :)