Skip to main content

vstd_extra/
number.rs

1// SPDX-License-Identifier: MPL-2.0
2use vstd::{
3    endian::{Base, Endian, EndianNat},
4    prelude::*,
5};
6
7verus! {
8
9pub ghost struct Base10 {}
10
11impl Base for Base10 {
12    open spec fn base() -> nat {
13        10
14    }
15
16    proof fn base_min() {
17    }
18}
19
20/// The mathematical value of an ASCII decimal byte sequence; empty input is zero.
21pub open spec fn decimal_value(bytes: Seq<u8>) -> int {
22    EndianNat::<Base10>::new(Endian::Big, bytes.map_values(|byte: u8| byte - b'0')).to_nat() as int
23}
24
25/// Decimal input whose mathematical value fits in a `u32`, including empty input.
26pub open spec fn valid_decimal(bytes: Seq<u8>) -> bool {
27    &&& bytes.all(|byte: u8| b'0' <= byte <= b'9')
28    &&& decimal_value(bytes) <= u32::MAX
29}
30
31pub proof fn lemma_decimal_value_step(bytes: Seq<u8>)
32    requires
33        bytes.all(|byte: u8| b'0' <= byte <= b'9'),
34    ensures
35        bytes.len() == 0 ==> decimal_value(bytes) == 0,
36        bytes.len() > 0 ==> decimal_value(bytes) == decimal_value(bytes[..bytes.len() - 1]) * 10 + (
37        bytes.last() - b'0'),
38{
39    reveal(EndianNat::to_nat);
40    if bytes.len() > 0 {
41        let digits = bytes.map_values(|byte: u8| byte - b'0');
42        assert(digits.drop_last() == bytes[..bytes.len() - 1].map_values(|byte: u8| byte - b'0'));
43    }
44}
45
46pub proof fn lemma_decimal_prefix(bytes: Seq<u8>, end: int)
47    requires
48        bytes.all(|byte: u8| b'0' <= byte <= b'9'),
49        0 <= end <= bytes.len(),
50    ensures
51        0 <= decimal_value(bytes[..end]) <= decimal_value(bytes),
52    decreases bytes.len(),
53{
54    lemma_decimal_value_step(bytes);
55    assert(bytes[..bytes.len()] == bytes);
56    if bytes.len() > 0 {
57        let prefix = bytes[..bytes.len() - 1];
58        lemma_decimal_prefix(
59            prefix,
60            if end < bytes.len() {
61                end
62            } else {
63                end - 1
64            },
65        );
66        if end < bytes.len() {
67            assert(prefix[..end] == bytes[..end]);
68        }
69    }
70}
71
72} // verus!