leo_ast/common/
positive_number.rs

1// Copyright (C) 2019-2025 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17use serde::{Deserialize, Serialize};
18use std::{fmt, str::FromStr};
19
20/// A number string guaranteed to be non-negative.
21#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
22pub struct NonNegativeNumber {
23    /// The string representation of the non-negative number.
24    string: String,
25    /// The numeric value of the non-negative number.
26    value: usize,
27}
28
29impl NonNegativeNumber {
30    /// Returns the string representation of the non-negative number.
31    pub fn string(&self) -> &str {
32        &self.string
33    }
34
35    /// Returns the numeric value of the non-negative number.
36    pub fn value(&self) -> usize {
37        self.value
38    }
39
40    /// Returns `true` if this number is zero.
41    pub fn is_zero(&self) -> bool {
42        self.value == 0
43    }
44}
45
46impl From<String> for NonNegativeNumber {
47    fn from(string: String) -> Self {
48        let value = usize::from_str(&string).unwrap();
49        Self { string, value }
50    }
51}
52
53impl From<usize> for NonNegativeNumber {
54    fn from(value: usize) -> Self {
55        let string = value.to_string();
56        Self { string, value }
57    }
58}
59
60impl fmt::Display for NonNegativeNumber {
61    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62        write!(f, "{}", self.value)
63    }
64}