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/// Copy network-order packed input, discarding unused low padding bits as `PostgreSQL`'s binary input does. The span contains exactly the bytes needed for the logical length.
130pub fn from_packed_with_control(
131    input: &[u8],
132    length: u32,
133    control: &ProductionControl<'_>,
134) -> Result<Produced<BitStringValue>> {
135    control.check()?;
136    if length > MAX_BIT_LENGTH || input.len() != length.div_ceil(8) as usize {
137        return Err(error(
138            "22P03",
139            "invalid length in external bit string".into(),
140        ));
141    }
142    let mut bytes = ProductionVec::new(*control);
143    bytes.reserve(input.len())?;
144    bytes.extend_from_slice(input)?;
145    if let Some(last) = bytes
146        .as_mut_slice()
147        .last_mut()
148        .filter(|_| !length.is_multiple_of(8))
149    {
150        *last &= u8::MAX << (8 - length % 8);
151    }
152    finish_bits(bytes, length, control)
153}
154
155/// Apply assignment or explicit-cast length semantics without changing the borrowed source or allocating an unpacked temporary.
156pub fn coerce_with_control(
157    value: &BitStringValue,
158    kind: BitStringKind,
159    modifier: i32,
160    explicit: bool,
161    control: &ProductionControl<'_>,
162) -> Result<Produced<BitStringValue>> {
163    control.check()?;
164    if modifier <= 0 || (kind == BitStringKind::Fixed && modifier as u32 > MAX_BIT_LENGTH) {
165        return Ok(value.clone_with_control(control)?);
166    }
167    if !explicit {
168        kind.check_length(value.bit_len(), modifier)?;
169    }
170    let length = match kind {
171        BitStringKind::Fixed => modifier as u32,
172        BitStringKind::Varying => value.bit_len().min(modifier as u32),
173    };
174    if length == value.bit_len() {
175        return Ok(value.clone_with_control(control)?);
176    }
177    let byte_length = length.div_ceil(8) as usize;
178    let mut bytes = ProductionVec::new(*control);
179    bytes.reserve(byte_length)?;
180    for position in 0..byte_length {
181        let mut byte = value.as_bytes().get(position).copied().unwrap_or(0);
182        if position + 1 == byte_length && !length.is_multiple_of(8) {
183            byte &= u8::MAX << (8 - length % 8);
184        }
185        bytes.push_copy(byte)?;
186    }
187    finish_bits(bytes, length, control)
188}
189
190/// Emit exactly the logical bits, preserving leading zeroes and partial final bytes under the invoking output allowance.
191pub fn output_with_control(
192    value: &BitStringValue,
193    control: &ProductionControl<'_>,
194) -> Result<Produced<String>> {
195    control.check()?;
196    let mut output = ProductionString::new(*control);
197    output.reserve(value.bit_len() as usize)?;
198    for (position, byte) in value.as_bytes().iter().copied().enumerate() {
199        control.check()?;
200        let count = (value.bit_len() as usize - position * 8).min(8);
201        for bit in 0..count {
202            output.push(if byte & (0x80 >> bit) == 0 { '0' } else { '1' })?;
203        }
204    }
205    Ok(output.finish()?)
206}
207
208fn finish_bits(
209    bytes: ProductionVec<'_, u8>,
210    length: u32,
211    control: &ProductionControl<'_>,
212) -> Result<Produced<BitStringValue>> {
213    BitStringValue::try_from_packed_with_control(bytes.finish()?, length, control)?
214        .ok_or_else(|| SQLError::Internal("invalid constructed bit-string padding".into()))
215}
216
217fn error(sqlstate: &str, message: String) -> SQLError {
218    SQLError::Routine {
219        sqlstate: sqlstate.into(),
220        message,
221    }
222}
223
224#[cfg(test)]
225mod tests;