Skip to main content

relate_core/
memory_limit.rs

1//! Human-readable memory-limit sizes (ADR-0042).
2
3use crate::{Error, Result};
4
5/// Parse `--logical-graph-size-limit` / `RELATE_LOGICAL_GRAPH_SIZE_LIMIT` sizes.
6///
7/// Integer bytes, or an integer plus `b`/`bytes`/`mb`/`mib`/`gb`/`gib`
8/// (case-insensitive, optional space). `mb`/`gb` are SI; `mib`/`gib` are IEC.
9/// `0` is unlimited at the call site.
10///
11/// ```
12/// use relate_core::parse_memory_limit;
13/// assert_eq!(parse_memory_limit("1gib").unwrap(), 1 << 30);
14/// assert_eq!(parse_memory_limit("2 mb").unwrap(), 2_000_000);
15/// ```
16pub fn parse_memory_limit(s: &str) -> Result<u64> {
17    let s = s.trim();
18    if s.is_empty() {
19        return Err(Error::semantic("empty memory limit"));
20    }
21    let split = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
22    let (num, rest) = s.split_at(split);
23    if num.is_empty() {
24        return Err(Error::semantic(format!("invalid memory limit '{s}'")));
25    }
26    let n: u64 = num
27        .parse()
28        .map_err(|_| Error::semantic(format!("invalid memory limit '{s}'")))?;
29    let unit = rest.trim().to_ascii_lowercase();
30    let mul: u64 = match unit.as_str() {
31        "" | "b" | "byte" | "bytes" => 1,
32        "mb" => 1_000_000,
33        "mib" => 1 << 20,
34        "gb" => 1_000_000_000,
35        "gib" => 1 << 30,
36        _ => {
37            return Err(Error::semantic(format!(
38                "invalid memory limit unit '{rest}'; use bytes, mb, mib, gb, or gib"
39            )))
40        }
41    };
42    n.checked_mul(mul)
43        .ok_or_else(|| Error::semantic(format!("memory limit '{s}' overflows u64")))
44}
45
46/// Parse the expression-memory-limit grammar: [`parse_memory_limit`] plus
47/// the explicit opt-out spelling `none` (case-insensitive), which maps to
48/// `0` = no cap. `0` is already unlimited in [`parse_memory_limit`].
49pub fn parse_expression_memory_limit(s: &str) -> Result<u64> {
50    let s = s.trim();
51    if s.eq_ignore_ascii_case("none") {
52        Ok(0)
53    } else {
54        parse_memory_limit(s)
55    }
56}
57
58/// Reject `0` for a size that turns a feature on.
59///
60/// `0` is `invalid {name}: must be positive`. A positive `n` is returned
61/// unchanged. [`parse_memory_limit`] still accepts `0` (unlimited) for the
62/// live-graph cap.
63pub fn require_positive_memory_limit(name: &str, n: u64) -> Result<u64> {
64    if n == 0 {
65        Err(Error::semantic(format!("invalid {name}: must be positive")))
66    } else {
67        Ok(n)
68    }
69}
70
71/// [`parse_memory_limit`] for a size that must be greater than zero.
72///
73/// `name` is the flag or variable in the error. A bad SIZE is
74/// `invalid {name}: …` around that parse error. `0` is
75/// [`require_positive_memory_limit`]. A blank string is a bad SIZE, not
76/// an unset value; callers that treat blank as off fold it first.
77pub fn parse_positive_memory_limit(name: &str, s: &str) -> Result<u64> {
78    let n = match parse_memory_limit(s) {
79        Ok(n) => n,
80        Err(Error::Semantic(msg)) => {
81            return Err(Error::semantic(format!("invalid {name}: {msg}")));
82        }
83        Err(other) => return Err(other),
84    };
85    require_positive_memory_limit(name, n)
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    #[test]
93    fn parses_units() {
94        assert_eq!(parse_memory_limit("0").unwrap(), 0);
95        assert_eq!(parse_memory_limit("512").unwrap(), 512);
96        assert_eq!(parse_memory_limit("512b").unwrap(), 512);
97        assert_eq!(parse_memory_limit("1 bytes").unwrap(), 1);
98        assert_eq!(parse_memory_limit("2mb").unwrap(), 2_000_000);
99        assert_eq!(parse_memory_limit("2 MiB").unwrap(), 2 << 20);
100        assert_eq!(parse_memory_limit("1GB").unwrap(), 1_000_000_000);
101        assert_eq!(parse_memory_limit("1gib").unwrap(), 1 << 30);
102    }
103
104    #[test]
105    fn rejects_unknown_unit() {
106        assert!(parse_memory_limit("1tb").is_err());
107        assert!(parse_memory_limit("gib").is_err());
108        assert!(parse_memory_limit("").is_err());
109    }
110
111    #[test]
112    fn rejects_overflow() {
113        assert!(parse_memory_limit("18446744073709551615gib").is_err());
114    }
115
116    #[test]
117    fn positive_limit_rejects_zero_and_names_the_knob() {
118        let zero =
119            require_positive_memory_limit("concurrent_logical_workspace_limit", 0).unwrap_err();
120        assert_eq!(
121            zero.to_string(),
122            "semantic error: invalid concurrent_logical_workspace_limit: must be positive"
123        );
124        assert_eq!(
125            require_positive_memory_limit("--concurrent-logical-workspace-limit", 8).unwrap(),
126            8
127        );
128        let bad = parse_positive_memory_limit("RELATE_CONCURRENT_LOGICAL_WORKSPACE_LIMIT", "1tb")
129            .unwrap_err();
130        assert!(
131            bad.to_string()
132                .contains("invalid RELATE_CONCURRENT_LOGICAL_WORKSPACE_LIMIT:"),
133            "{bad}"
134        );
135        assert_eq!(
136            parse_positive_memory_limit("--concurrent-logical-workspace-limit", "2mib").unwrap(),
137            2 * 1024 * 1024
138        );
139    }
140}