Skip to main content

FiniteNumber

Struct FiniteNumber 

Source
pub struct FiniteNumber(/* private fields */);
Expand description

A finite IEEE-754 number accepted at the workbook boundary.

Implementations§

Source§

impl FiniteNumber

Source

pub fn new(value: f64) -> Result<Self, ValidationError>

Rejects NaN and positive or negative infinity.

§Errors

Returns ValidationError::NonFiniteNumber when value is not finite.

Examples found in repository?
examples/create_and_write.rs (line 17)
8fn main() -> Result<(), Box<dyn Error>> {
9    let destination = std::env::args()
10        .nth(1)
11        .unwrap_or_else(|| "cellrune-output.xlsx".to_owned());
12    let mut draft = WorkbookDraft::new();
13    let sheet_id = draft.workbook().sheets()[0].id();
14    draft.set_cell_value(
15        sheet_id,
16        CellAddress::from_a1("A1")?,
17        CellValue::Number(FiniteNumber::new(2.0)?),
18    )?;
19    draft.set_cell_formula(
20        sheet_id,
21        CellAddress::from_a1("B1")?,
22        FormulaText::from_user_input("=A1+3")?,
23    )?;
24
25    let calculation = calculate_workbook(draft.workbook(), CalculationOptions::default());
26    let report = write_xlsx_draft_path(
27        &draft,
28        &calculation,
29        destination,
30        RecalculationWriteOptions::default(),
31    )?;
32    println!(
33        "wrote {} calculated cells (complete: {})",
34        report.materialized_count(),
35        report.is_complete()
36    );
37    Ok(())
38}
More examples
Hide additional examples
examples/read_and_calculate.rs (line 109)
18fn main() -> Result<(), Box<dyn Error>> {
19    let Some(path) = std::env::args_os().nth(1) else {
20        eprintln!("{USAGE}");
21        return Ok(());
22    };
23
24    let workbook = read_xlsx_path(path, ReadOptions::default())?;
25    println!(
26        "read {} sheets and {} compatibility diagnostics",
27        workbook.sheets().len(),
28        workbook.diagnostics().len()
29    );
30    for diagnostic in workbook.diagnostics() {
31        eprintln!(
32            "[{:?}] {}: {}",
33            diagnostic.severity(),
34            diagnostic.code().as_str(),
35            diagnostic.message()
36        );
37    }
38
39    let second_argument = std::env::args_os().nth(2);
40    if second_argument.as_deref() == Some(std::ffi::OsStr::new(READ_ONLY)) {
41        return Ok(());
42    }
43
44    let limits = match std::env::var(MAX_DEPENDENCY_EDGES_ENV) {
45        Ok(value) => {
46            CalculationLimits::default().with_max_dependency_edges(value.parse::<u64>()?)?
47        }
48        Err(std::env::VarError::NotPresent) => CalculationLimits::default(),
49        Err(error) => return Err(error.into()),
50    };
51    let options = CalculationOptions::default().with_limits(limits);
52    if second_argument.as_deref() == Some(std::ffi::OsStr::new(SCAN_ONLY)) {
53        let capabilities = scan_formula_capabilities_with_options(&workbook, options);
54        println!(
55            "formula capability inventory: {} supported, {} unsupported",
56            capabilities.supported_count(),
57            capabilities.unsupported_count()
58        );
59        let mut issue_counts =
60            BTreeMap::<(cellrune::CalculationIssueCode, Option<String>), usize>::new();
61        let mut issue_samples =
62            BTreeMap::<(cellrune::CalculationIssueCode, Option<String>), Vec<String>>::new();
63        for entry in capabilities.entries() {
64            let FormulaCapability::Unsupported(issues) = entry.capability() else {
65                continue;
66            };
67            let sheet_name = workbook
68                .sheet_by_id(entry.cell().sheet_id())
69                .map_or("<unknown>", |sheet| sheet.name().as_str());
70            for issue in issues {
71                let key = (issue.code(), issue.detail().map(str::to_owned));
72                *issue_counts.entry(key.clone()).or_default() += 1;
73                let samples = issue_samples.entry(key).or_default();
74                if samples.len() < MAX_SAMPLES_PER_ISSUE {
75                    let formula = workbook
76                        .sheet_by_id(entry.cell().sheet_id())
77                        .and_then(|sheet| sheet.cell(entry.cell().address()))
78                        .and_then(|cell| match cell.content() {
79                            CellContent::Formula(formula) => formula.text(),
80                            CellContent::Literal(_) => None,
81                        })
82                        .map_or("<missing formula text>".to_owned(), |formula| {
83                            truncate_formula(formula.as_str())
84                        });
85                    samples.push(format!(
86                        "{sheet_name}!{}: ={formula}",
87                        entry.cell().address()
88                    ));
89                }
90            }
91        }
92        for (key @ (code, detail), count) in &issue_counts {
93            let rendered_detail = detail
94                .as_deref()
95                .map_or(String::new(), |detail| format!(" ({detail})"));
96            eprintln!("{count:>8} {}{rendered_detail}", code.as_str());
97            if let Some(samples) = issue_samples.get(key) {
98                for sample in samples {
99                    eprintln!("           {sample}");
100                }
101            }
102        }
103        return Ok(());
104    }
105
106    let options = match second_argument {
107        Some(serial) => {
108            let serial = serial.to_string_lossy().parse::<f64>()?;
109            options.with_today_serial(FiniteNumber::new(serial)?)
110        }
111        None => options,
112    };
113    let calculation = calculate_workbook(&workbook, options);
114    let mut issue_counts = BTreeMap::<cellrune::CalculationIssueCode, usize>::new();
115    for (_, result) in calculation.cells() {
116        if let CalculationCellResult::Unavailable(issue) = result {
117            *issue_counts.entry(issue.code()).or_default() += 1;
118        }
119    }
120    let unavailable = issue_counts.values().sum::<usize>();
121    println!(
122        "calculated {} formula cells; {} unavailable",
123        calculation.len(),
124        unavailable
125    );
126    for (code, count) in issue_counts {
127        eprintln!("{count:>8} {}", code.as_str());
128    }
129
130    Ok(())
131}
Source

pub const fn get(self) -> f64

Returns the underlying finite number.

Examples found in repository?
examples/select_calculation_modes.rs (line 76)
73fn render(calculation: &CalculationSnapshot, cell: CalculationCellId) -> String {
74    match calculation.cell(cell) {
75        Some(CalculationCellResult::Value(CellValue::Number(number))) => {
76            render_number(number.get())
77        }
78        Some(CalculationCellResult::Value(CellValue::Logical(logical))) => logical.to_string(),
79        Some(CalculationCellResult::Value(CellValue::Error(error))) => error.as_str().to_owned(),
80        Some(CalculationCellResult::Unavailable(issue)) => {
81            format!("unavailable: {}", issue.code().as_str())
82        }
83        // `CellValue` and `CalculationCellResult` are `#[non_exhaustive]`, so a wildcard arm is
84        // required even when every variant this example can produce is handled above.
85        Some(_) => "<other value>".to_owned(),
86        None => "<not calculated>".to_owned(),
87    }
88}

Trait Implementations§

Source§

impl Clone for FiniteNumber

Source§

fn clone(&self) -> FiniteNumber

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for FiniteNumber

Source§

impl Debug for FiniteNumber

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for FiniteNumber

Source§

fn eq(&self, other: &FiniteNumber) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for FiniteNumber

Source§

fn partial_cmp(&self, other: &FiniteNumber) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl StructuralPartialEq for FiniteNumber

Source§

impl TryFrom<f64> for FiniteNumber

Source§

type Error = ValidationError

The type returned in the event of a conversion error.
Source§

fn try_from(value: f64) -> Result<Self, Self::Error>

Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.