Skip to main content

uqa_sql/semantics/parameters/
units.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Integer parameter values and their units, read and shown as `PostgreSQL`'s `parse_int`, `convert_to_base_unit` and `convert_int_from_base_unit` do: C `strtol` and `strtod` number syntax, a unit of up to three characters, rounding to the nearest multiple of the next smaller unit, and display in the greatest unit that divides the value.
8
9/// The base unit of an integer parameter (`GUC_UNIT_*`).
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum ParameterUnit {
12    Bytes,
13    Kilobytes,
14    Megabytes,
15    Milliseconds,
16    Seconds,
17    Minutes,
18}
19
20const MEMORY_UNITS_HINT: &str =
21    "Valid units for this parameter are \"B\", \"kB\", \"MB\", \"GB\", and \"TB\".";
22const TIME_UNITS_HINT: &str =
23    "Valid units for this parameter are \"us\", \"ms\", \"s\", \"min\", \"h\", and \"d\".";
24const INTEGER_RANGE_HINT: &str = "Value exceeds integer range.";
25const MAX_UNIT_LENGTH: usize = 3;
26const KIB: f64 = 1024.0;
27
28impl ParameterUnit {
29    /// The name that `pg_settings.unit` and range errors report.
30    pub const fn name(self) -> &'static str {
31        match self {
32            Self::Bytes => "B",
33            Self::Kilobytes => "kB",
34            Self::Megabytes => "MB",
35            Self::Milliseconds => "ms",
36            Self::Seconds => "s",
37            Self::Minutes => "min",
38        }
39    }
40
41    const fn hint(self) -> &'static str {
42        match self {
43            Self::Bytes | Self::Kilobytes | Self::Megabytes => MEMORY_UNITS_HINT,
44            Self::Milliseconds | Self::Seconds | Self::Minutes => TIME_UNITS_HINT,
45        }
46    }
47
48    /// The units a value may name and how many base units each holds, from the greatest to the smallest, as `memory_unit_conversion_table` and `time_unit_conversion_table` list them.
49    fn conversions(self) -> [(&'static str, f64); 6] {
50        match self {
51            Self::Bytes => [
52                ("TB", KIB * KIB * KIB * KIB),
53                ("GB", KIB * KIB * KIB),
54                ("MB", KIB * KIB),
55                ("kB", KIB),
56                ("B", 1.0),
57                ("", 0.0),
58            ],
59            Self::Kilobytes => [
60                ("TB", KIB * KIB * KIB),
61                ("GB", KIB * KIB),
62                ("MB", KIB),
63                ("kB", 1.0),
64                ("B", 1.0 / KIB),
65                ("", 0.0),
66            ],
67            Self::Megabytes => [
68                ("TB", KIB * KIB),
69                ("GB", KIB),
70                ("MB", 1.0),
71                ("kB", 1.0 / KIB),
72                ("B", 1.0 / (KIB * KIB)),
73                ("", 0.0),
74            ],
75            Self::Milliseconds => [
76                ("d", 86_400_000.0),
77                ("h", 3_600_000.0),
78                ("min", 60_000.0),
79                ("s", 1000.0),
80                ("ms", 1.0),
81                ("us", 1.0 / 1000.0),
82            ],
83            Self::Seconds => [
84                ("d", 86_400.0),
85                ("h", 3600.0),
86                ("min", 60.0),
87                ("s", 1.0),
88                ("ms", 1.0 / 1000.0),
89                ("us", 1.0 / (1000.0 * 1000.0)),
90            ],
91            Self::Minutes => [
92                ("d", 1440.0),
93                ("h", 60.0),
94                ("min", 1.0),
95                ("s", 1.0 / 60.0),
96                ("ms", 1.0 / (1000.0 * 60.0)),
97                ("us", 1.0 / (1000.0 * 1000.0 * 60.0)),
98            ],
99        }
100    }
101}
102
103/// Read an integer value in base units. The error carries the hint `PostgreSQL` adds to `invalid value for parameter`, if any.
104pub(super) fn parse_integer(
105    raw: &str,
106    unit: Option<ParameterUnit>,
107) -> Result<i32, Option<&'static str>> {
108    let bytes = raw.as_bytes();
109    let (integer, integer_end, overflow) = c_strtol(bytes);
110    let (mut value, mut end) = (integer as f64, integer_end);
111    if overflow || matches!(bytes.get(integer_end), Some(b'.' | b'e' | b'E')) {
112        let (double, double_end, out_of_range) = c_strtod(bytes);
113        if double_end == 0 || out_of_range {
114            return Err(None);
115        }
116        (value, end) = (double, double_end);
117    } else if integer_end == 0 {
118        return Err(None);
119    }
120    if value.is_nan() {
121        return Err(None);
122    }
123    end = skip_c_space(bytes, end);
124    if end < bytes.len() {
125        let unit = unit.ok_or(None)?;
126        value = convert_to_base_unit(value, &bytes[end..], unit).ok_or(Some(unit.hint()))?;
127    }
128    let value = value.round_ties_even();
129    if value > f64::from(i32::MAX) || value < f64::from(i32::MIN) {
130        return Err(Some(INTEGER_RANGE_HINT));
131    }
132    Ok(value as i32)
133}
134
135/// Show an integer value in the greatest unit that divides it.
136#[cfg(test)]
137fn show_integer(value: i64, unit: Option<ParameterUnit>) -> String {
138    show_integer_with_control(
139        value,
140        unit,
141        &uqa_core::memory::ProductionControl::uncontrolled(),
142    )
143    .expect("ordinary setting formatting")
144    .into_uncontrolled()
145    .expect("ordinary setting")
146}
147
148pub(super) fn show_integer_with_control(
149    value: i64,
150    unit: Option<ParameterUnit>,
151    control: &uqa_core::memory::ProductionControl<'_>,
152) -> Result<uqa_core::memory::Produced<String>, crate::SQLError> {
153    let Some(unit) = unit.filter(|_| value > 0) else {
154        return Ok(control.format(format_args!("{value}"))?);
155    };
156    for (name, multiplier) in unit.conversions() {
157        if name.is_empty() {
158            break;
159        }
160        if multiplier <= 1.0 || value % (multiplier as i64) == 0 {
161            let converted = (value as f64 / multiplier).round_ties_even() as i64;
162            return Ok(control.format(format_args!("{converted}{name}"))?);
163        }
164    }
165    unreachable!("every unit lists its base unit")
166}
167
168/// Convert `value` given in the unit that `text` names to base units, rounding a fraction to the nearest multiple of the next smaller unit; `None` for an unknown unit or text after it.
169fn convert_to_base_unit(value: f64, text: &[u8], unit: ParameterUnit) -> Option<f64> {
170    let length = text
171        .iter()
172        .take(MAX_UNIT_LENGTH)
173        .take_while(|byte| !is_c_space(**byte))
174        .count();
175    if skip_c_space(text, length) != text.len() {
176        return None;
177    }
178    let conversions = unit.conversions();
179    let index = conversions
180        .iter()
181        .position(|(name, _)| !name.is_empty() && name.as_bytes() == &text[..length])?;
182    let mut converted = value * conversions[index].1;
183    if let Some((next, multiplier)) = conversions.get(index + 1) {
184        if !next.is_empty() {
185            converted = (converted / multiplier).round_ties_even() * multiplier;
186        }
187    }
188    Some(converted)
189}
190
191/// The white space of the C locale's `isspace`.
192pub(super) fn is_c_space(byte: u8) -> bool {
193    matches!(byte, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
194}
195
196fn skip_c_space(bytes: &[u8], mut index: usize) -> usize {
197    while bytes.get(index).copied().is_some_and(is_c_space) {
198        index += 1;
199    }
200    index
201}
202
203/// C `strtol(text, &end, 0)` on a 64-bit `long`: the value, the offset where the conversion stopped (0 when nothing was converted) and whether the value overflowed. A leading `0x` selects hexadecimal and a leading `0` octal.
204fn c_strtol(bytes: &[u8]) -> (i64, usize, bool) {
205    let mut index = skip_c_space(bytes, 0);
206    let negative = match bytes.get(index) {
207        Some(b'-') => {
208            index += 1;
209            true
210        }
211        Some(b'+') => {
212            index += 1;
213            false
214        }
215        _ => false,
216    };
217    let hexadecimal = matches!(bytes.get(index..index + 2), Some(b"0x" | b"0X"))
218        && bytes.get(index + 2).is_some_and(u8::is_ascii_hexdigit);
219    let radix = if hexadecimal {
220        index += 2;
221        16
222    } else if bytes.get(index) == Some(&b'0') {
223        8
224    } else {
225        10
226    };
227    let start = index;
228    let mut magnitude: u128 = 0;
229    let mut overflow = false;
230    while let Some(digit) = bytes
231        .get(index)
232        .and_then(|byte| char::from(*byte).to_digit(radix))
233    {
234        magnitude = magnitude * u128::from(radix) + u128::from(digit);
235        if magnitude > u128::from(i64::MAX.unsigned_abs()) + 1 {
236            magnitude = u128::from(i64::MAX.unsigned_abs()) + 1;
237            overflow = true;
238        }
239        index += 1;
240    }
241    if index == start {
242        return (0, 0, false);
243    }
244    let value = if negative {
245        i64::try_from(-(magnitude as i128)).unwrap_or_else(|_| {
246            overflow = true;
247            i64::MIN
248        })
249    } else {
250        i64::try_from(magnitude).unwrap_or_else(|_| {
251            overflow = true;
252            i64::MAX
253        })
254    };
255    (value, index, overflow)
256}
257
258/// C `strtod`: the value, the offset where the conversion stopped (0 when nothing was converted) and whether the value overflowed or underflowed (`ERANGE`). Reads decimal and hexadecimal numbers, `inf`, `infinity` and `nan`.
259pub(super) fn c_strtod(bytes: &[u8]) -> (f64, usize, bool) {
260    let mut index = skip_c_space(bytes, 0);
261    let sign_start = index;
262    let negative = match bytes.get(index) {
263        Some(b'-') => {
264            index += 1;
265            true
266        }
267        Some(b'+') => {
268            index += 1;
269            false
270        }
271        _ => false,
272    };
273    let signed = |value: f64| if negative { -value } else { value };
274    let rest = &bytes[index..];
275    let starts_with =
276        |word: &[u8]| rest.len() >= word.len() && rest[..word.len()].eq_ignore_ascii_case(word);
277    if starts_with(b"infinity") {
278        return (signed(f64::INFINITY), index + 8, false);
279    }
280    if starts_with(b"inf") {
281        return (signed(f64::INFINITY), index + 3, false);
282    }
283    if starts_with(b"nan") {
284        let mut end = index + 3;
285        if bytes.get(end) == Some(&b'(') {
286            let close = bytes[end + 1..]
287                .iter()
288                .position(|byte| !(byte.is_ascii_alphanumeric() || *byte == b'_'));
289            if let Some(offset) = close {
290                if bytes[end + 1 + offset] == b')' {
291                    end += offset + 2;
292                }
293            }
294        }
295        return (f64::NAN, end, false);
296    }
297    if matches!(rest.get(..2), Some(b"0x" | b"0X")) {
298        if let Some((value, end, nonzero)) = hexadecimal_float(bytes, index + 2) {
299            return finish_strtod(signed(value), end, nonzero);
300        }
301    }
302    let mut end = index;
303    let mut nonzero = false;
304    let mut digits = 0;
305    while let Some(byte) = bytes.get(end).filter(|byte| byte.is_ascii_digit()) {
306        nonzero |= *byte != b'0';
307        digits += 1;
308        end += 1;
309    }
310    if bytes.get(end) == Some(&b'.') {
311        end += 1;
312        while let Some(byte) = bytes.get(end).filter(|byte| byte.is_ascii_digit()) {
313            nonzero |= *byte != b'0';
314            digits += 1;
315            end += 1;
316        }
317    }
318    if digits == 0 {
319        return (0.0, 0, false);
320    }
321    if matches!(bytes.get(end), Some(b'e' | b'E')) {
322        let mut exponent = end + 1;
323        if matches!(bytes.get(exponent), Some(b'+' | b'-')) {
324            exponent += 1;
325        }
326        if bytes.get(exponent).is_some_and(u8::is_ascii_digit) {
327            end = exponent;
328            while bytes.get(end).is_some_and(u8::is_ascii_digit) {
329                end += 1;
330            }
331        }
332    }
333    let text = std::str::from_utf8(&bytes[sign_start..end]).expect("ASCII number");
334    let value = text.parse::<f64>().expect("C decimal number syntax");
335    finish_strtod(value, end, nonzero)
336}
337
338fn finish_strtod(value: f64, end: usize, nonzero: bool) -> (f64, usize, bool) {
339    let out_of_range = value.is_infinite() || (nonzero && value.abs() < f64::MIN_POSITIVE);
340    (value, end, out_of_range)
341}
342
343/// The hexadecimal mantissa and optional binary exponent after `0x`: the magnitude, the offset after it and whether any digit was nonzero; `None` when no hexadecimal digit follows, which leaves `strtod` to read the `0` alone.
344fn hexadecimal_float(bytes: &[u8], start: usize) -> Option<(f64, usize, bool)> {
345    let mut index = start;
346    let mut mantissa: u64 = 0;
347    let mut exponent: i64 = 0;
348    let mut digits = 0;
349    let mut nonzero = false;
350    let mut accumulate = |digit: u32, fraction: bool, exponent: &mut i64| {
351        nonzero |= digit != 0;
352        if mantissa >> 60 == 0 {
353            mantissa = mantissa << 4 | u64::from(digit);
354            if fraction {
355                *exponent -= 4;
356            }
357        } else if !fraction {
358            *exponent += 4;
359        }
360    };
361    while let Some(digit) = bytes
362        .get(index)
363        .and_then(|byte| char::from(*byte).to_digit(16))
364    {
365        accumulate(digit, false, &mut exponent);
366        digits += 1;
367        index += 1;
368    }
369    if bytes.get(index) == Some(&b'.') {
370        let mut fraction = index + 1;
371        let mut fraction_digits = 0;
372        while let Some(digit) = bytes
373            .get(fraction)
374            .and_then(|byte| char::from(*byte).to_digit(16))
375        {
376            accumulate(digit, true, &mut exponent);
377            fraction_digits += 1;
378            fraction += 1;
379        }
380        if digits + fraction_digits > 0 {
381            index = fraction;
382            digits += fraction_digits;
383        }
384    }
385    if digits == 0 {
386        return None;
387    }
388    if matches!(bytes.get(index), Some(b'p' | b'P')) {
389        let mut cursor = index + 1;
390        let negative = match bytes.get(cursor) {
391            Some(b'-') => {
392                cursor += 1;
393                true
394            }
395            Some(b'+') => {
396                cursor += 1;
397                false
398            }
399            _ => false,
400        };
401        if bytes.get(cursor).is_some_and(u8::is_ascii_digit) {
402            let mut binary: i64 = 0;
403            while let Some(byte) = bytes.get(cursor).filter(|byte| byte.is_ascii_digit()) {
404                binary = binary
405                    .saturating_mul(10)
406                    .saturating_add(i64::from(byte - b'0'));
407                cursor += 1;
408            }
409            exponent = exponent.saturating_add(if negative { -binary } else { binary });
410            index = cursor;
411        }
412    }
413    // Scale in steps that stay within the normal range, so that a large mantissa with a very negative exponent does not vanish before the multiplication.
414    let mut remaining = exponent.clamp(-2200, 2200);
415    let mut value = mantissa as f64;
416    while remaining > 1000 {
417        value *= 2f64.powi(1000);
418        remaining -= 1000;
419    }
420    while remaining < -1000 {
421        value *= 2f64.powi(-1000);
422        remaining += 1000;
423    }
424    let remaining = i32::try_from(remaining).expect("exponent within one step");
425    Some((value * 2f64.powi(remaining), index, nonzero))
426}
427
428#[cfg(test)]
429mod tests;