Skip to main content

rustledger_plugin/native/plugins/
utils.rs

1//! Shared utility functions for native plugins.
2
3#[cfg(test)]
4use crate::types::{DirectiveWrapper, PluginOp, PluginOutput};
5
6/// Materialize a plugin's ops back into a flat list of `DirectiveWrapper`s.
7///
8/// Test-only helper used by the inline plugin tests that previously
9/// inspected `output.directives` directly. The mapping is:
10/// - `Keep(i)` → `input[i].clone()`
11/// - `Modify(i, w)` → `w` (carries `input[i]`'s identity in production,
12///   but for test inspection the wrapper's content is what we care about)
13/// - `Insert(w)` → `w`
14/// - `Delete(_)` → omitted
15#[cfg(test)]
16#[must_use]
17pub fn materialize_ops(input: &[DirectiveWrapper], output: &PluginOutput) -> Vec<DirectiveWrapper> {
18    let mut out = Vec::with_capacity(output.ops.len());
19    for op in &output.ops {
20        match op {
21            PluginOp::Keep(i) => out.push(input[*i].clone()),
22            PluginOp::Modify(_, w) | PluginOp::Insert(w) => out.push(w.clone()),
23            PluginOp::Delete(_) => {}
24        }
25    }
26    out
27}
28
29/// Increment a date string by one day.
30/// Returns None if the date format is invalid.
31pub fn increment_date(date: &str) -> Option<String> {
32    let parts: Vec<&str> = date.split('-').collect();
33    if parts.len() != 3 {
34        return None;
35    }
36
37    let year: i32 = parts[0].parse().ok()?;
38    let month: u32 = parts[1].parse().ok()?;
39    let day: u32 = parts[2].parse().ok()?;
40
41    // Simple date increment (handles month/year rollovers)
42    let days_in_month = match month {
43        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
44        4 | 6 | 9 | 11 => 30,
45        2 => {
46            if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
47                29
48            } else {
49                28
50            }
51        }
52        _ => return None,
53    };
54
55    let (new_year, new_month, new_day) = if day < days_in_month {
56        (year, month, day + 1)
57    } else if month < 12 {
58        (year, month + 1, 1)
59    } else {
60        (year + 1, 1, 1)
61    };
62
63    Some(format!("{new_year:04}-{new_month:02}-{new_day:02}"))
64}