Skip to main content

sql_values/
lib.rs

1#![no_std]
2#![doc = include_str!("../README.md")]
3
4extern crate alloc;
5
6pub mod postgres;
7
8use alloc::vec::Vec;
9
10/// Parse `t`, `f`, `1`, or `0` as a boolean.
11///
12/// ```
13/// assert_eq!(sql_values::parse_bool("0"), Some(false));
14/// ```
15pub fn parse_bool(text: &str) -> Option<bool> {
16    match text {
17        "t" | "1" => Some(true),
18        "f" | "0" => Some(false),
19        _ => None,
20    }
21}
22
23/// Parse PostgreSQL `\x`-prefixed bytea hex with no intermediate allocation.
24///
25/// ```
26/// assert_eq!(sql_values::parse_pg_bytea_hex(r"\x4869"), Some(vec![0x48, 0x69]));
27/// ```
28pub fn parse_pg_bytea_hex(text: &str) -> Option<Vec<u8>> {
29    let bytes = text.as_bytes();
30    if bytes.len() < 2 || bytes[0] != b'\\' || bytes[1] != b'x' {
31        return None;
32    }
33
34    let hex_part = &bytes[2..];
35    if !hex_part.len().is_multiple_of(2) {
36        return None;
37    }
38
39    let mut result = Vec::with_capacity(hex_part.len() / 2);
40    for i in (0..hex_part.len()).step_by(2) {
41        let high = hex_digit(hex_part[i])?;
42        let low = hex_digit(hex_part[i + 1])?;
43        result.push((high << 4) | low);
44    }
45    Some(result)
46}
47
48/// Parse integer text with an optional leading sign.
49///
50/// ```
51/// assert_eq!(sql_values::parse_i64("-42"), Some(-42));
52/// ```
53pub fn parse_i64(text: &str) -> Option<i64> {
54    text.parse::<i64>().ok()
55}
56
57/// Parse a 64-bit float, including PostgreSQL infinity and `NaN` spellings.
58///
59/// ```
60/// assert_eq!(sql_values::parse_f64("Infinity"), Some(f64::INFINITY));
61/// ```
62pub fn parse_f64(text: &str) -> Option<f64> {
63    match text {
64        "Infinity" => Some(f64::INFINITY),
65        "-Infinity" => Some(f64::NEG_INFINITY),
66        "NaN" => Some(f64::NAN),
67        _ => text.parse::<f64>().ok(),
68    }
69}
70
71/// Parse an arbitrary-precision decimal.
72///
73/// ```
74/// let d = sql_values::parse_decimal("123.450").unwrap();
75/// assert_eq!(d.to_string(), "123.450");
76/// ```
77#[cfg(feature = "decimal")]
78pub fn parse_decimal(text: &str) -> Option<bigdecimal::BigDecimal> {
79    use core::str::FromStr;
80    bigdecimal::BigDecimal::from_str(text).ok()
81}
82
83fn hex_digit(byte: u8) -> Option<u8> {
84    match byte {
85        b'0'..=b'9' => Some(byte - b'0'),
86        b'a'..=b'f' => Some(byte - b'a' + 10),
87        b'A'..=b'F' => Some(byte - b'A' + 10),
88        _ => None,
89    }
90}