Skip to main content

uqa_sql/expr/
bit_string.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL bit-string input, length constraints and output over Core's packed values.
8
9use crate::error::{Result, SQLError};
10use uqa_core::{
11    memory::{Produced, ProductionControl, ProductionString, ProductionVec},
12    BitStringValue,
13};
14
15mod integer;
16pub use integer::{from_integer_with_control, to_bigint, to_integer};
17
18/// `PostgreSQL`'s largest admitted bit-string payload length, independent of a declared column modifier.
19const MAX_BIT_LENGTH: u32 = i32::MAX as u32 - 7;
20const MAX_DECLARED_LENGTH: u32 = 83_886_080;
21
22/// Fixed and varying declarations share a value representation, but have different input and assignment constraints.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum BitStringKind {
25    Fixed,
26    Varying,
27}
28
29impl BitStringKind {
30    /// Validate the one integer length supplied by the declaration owner. The caller owns modifier arity and array-shape validation.
31    pub fn validate_length(self, length: i64) -> Result<u32> {
32        let name = match self {
33            Self::Fixed => "bit",
34            Self::Varying => "varbit",
35        };
36        if length < 1 {
37            return Err(error(
38                "22023",
39                format!("length for type {name} must be at least 1"),
40            ));
41        }
42        if length > i64::from(MAX_DECLARED_LENGTH) {
43            return Err(error(
44                "22023",
45                format!("length for type {name} cannot exceed {MAX_DECLARED_LENGTH}"),
46            ));
47        }
48        Ok(length as u32)
49    }
50
51    pub(crate) fn check_length(self, length: u32, modifier: i32) -> Result<()> {
52        if modifier <= 0 {
53            return Ok(());
54        }
55        match self {
56            Self::Fixed if length != modifier as u32 => Err(error(
57                "22026",
58                format!("bit string length {length} does not match type bit({modifier})"),
59            )),
60            Self::Varying if length > modifier as u32 => Err(error(
61                "22001",
62                format!("bit string too long for type bit varying({modifier})"),
63            )),
64            _ => Ok(()),
65        }
66    }
67}
68
69/// Interpret binary or hexadecimal input. An input function checks the declared length before inspecting digits; explicit casts apply their modifier after unconstrained input instead.
70pub fn input_with_control(
71    text: &str,
72    kind: BitStringKind,
73    modifier: i32,
74    control: &ProductionControl<'_>,
75) -> Result<Produced<BitStringValue>> {
76    control.check()?;
77    let (digits, bits_per_digit) = match text.as_bytes().first() {
78        Some(b'b' | b'B') => (&text[1..], 1),
79        Some(b'x' | b'X') => (&text[1..], 4),
80        _ => (text, 1),
81    };
82    let length = digits
83        .len()
84        .checked_mul(bits_per_digit)
85        .and_then(|length| u32::try_from(length).ok())
86        .filter(|length| *length <= MAX_BIT_LENGTH)
87        .ok_or_else(|| {
88            error(
89                "54000",
90                format!("bit string length exceeds the maximum allowed ({MAX_BIT_LENGTH})"),
91            )
92        })?;
93    kind.check_length(length, modifier)?;
94    let mut bytes = ProductionVec::new(*control);
95    bytes.reserve(length.div_ceil(8) as usize)?;
96    let digits_per_byte = 8 / bits_per_digit;
97    for (index, chunk) in digits.as_bytes().chunks(digits_per_byte).enumerate() {
98        control.check()?;
99        let mut packed = 0_u8;
100        for (position, digit) in chunk.iter().copied().enumerate() {
101            let value = match digit {
102                b'0'..=b'1' => digit - b'0',
103                b'2'..=b'9' if bits_per_digit == 4 => digit - b'0',
104                b'a'..=b'f' if bits_per_digit == 4 => digit - b'a' + 10,
105                b'A'..=b'F' if bits_per_digit == 4 => digit - b'A' + 10,
106                _ => {
107                    let invalid = digits[index * digits_per_byte + position..]
108                        .chars()
109                        .next()
110                        .expect("a digit byte exists");
111                    let name = if bits_per_digit == 4 {
112                        "hexadecimal"
113                    } else {
114                        "binary"
115                    };
116                    return Err(error(
117                        "22P02",
118                        format!("\"{invalid}\" is not a valid {name} digit"),
119                    ));
120                }
121            };
122            packed |= value << (8 - bits_per_digit * (position + 1));
123        }
124        bytes.push_copy(packed)?;
125    }
126    finish_bits(bytes, length, control)
127}
128
129/// Apply assignment or explicit-cast length semantics without changing the borrowed source or allocating an unpacked temporary.
130pub fn coerce_with_control(
131    value: &BitStringValue,
132    kind: BitStringKind,
133    modifier: i32,
134    explicit: bool,
135    control: &ProductionControl<'_>,
136) -> Result<Produced<BitStringValue>> {
137    control.check()?;
138    if modifier <= 0 || (kind == BitStringKind::Fixed && modifier as u32 > MAX_BIT_LENGTH) {
139        return Ok(value.clone_with_control(control)?);
140    }
141    if !explicit {
142        kind.check_length(value.bit_len(), modifier)?;
143    }
144    let length = match kind {
145        BitStringKind::Fixed => modifier as u32,
146        BitStringKind::Varying => value.bit_len().min(modifier as u32),
147    };
148    if length == value.bit_len() {
149        return Ok(value.clone_with_control(control)?);
150    }
151    let byte_length = length.div_ceil(8) as usize;
152    let mut bytes = ProductionVec::new(*control);
153    bytes.reserve(byte_length)?;
154    for position in 0..byte_length {
155        let mut byte = value.as_bytes().get(position).copied().unwrap_or(0);
156        if position + 1 == byte_length && !length.is_multiple_of(8) {
157            byte &= u8::MAX << (8 - length % 8);
158        }
159        bytes.push_copy(byte)?;
160    }
161    finish_bits(bytes, length, control)
162}
163
164/// Emit exactly the logical bits, preserving leading zeroes and partial final bytes under the invoking output allowance.
165pub fn output_with_control(
166    value: &BitStringValue,
167    control: &ProductionControl<'_>,
168) -> Result<Produced<String>> {
169    control.check()?;
170    let mut output = ProductionString::new(*control);
171    output.reserve(value.bit_len() as usize)?;
172    for (position, byte) in value.as_bytes().iter().copied().enumerate() {
173        control.check()?;
174        let count = (value.bit_len() as usize - position * 8).min(8);
175        for bit in 0..count {
176            output.push(if byte & (0x80 >> bit) == 0 { '0' } else { '1' })?;
177        }
178    }
179    Ok(output.finish()?)
180}
181
182fn finish_bits(
183    bytes: ProductionVec<'_, u8>,
184    length: u32,
185    control: &ProductionControl<'_>,
186) -> Result<Produced<BitStringValue>> {
187    BitStringValue::try_from_packed_with_control(bytes.finish()?, length, control)?
188        .ok_or_else(|| SQLError::Internal("invalid constructed bit-string padding".into()))
189}
190
191fn error(sqlstate: &str, message: String) -> SQLError {
192    SQLError::Routine {
193        sqlstate: sqlstate.into(),
194        message,
195    }
196}
197
198#[cfg(test)]
199mod tests;