Skip to main content

sql_values/
lib.rs

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