Skip to main content

uqa_sql/expr/bit_string/
integer.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Integer conversion preserves low bits, sign extension and exact-width signed output.
8
9use super::{
10    error, finish_bits, BitStringValue, Produced, ProductionControl, ProductionVec, Result,
11    MAX_BIT_LENGTH,
12};
13
14/// Convert an int4 or int8 value already checked by the caller's integer-type owner. A widened int4 has the same sign-extension and low-bit behavior as int8.
15pub fn from_integer_with_control(
16    value: i64,
17    modifier: i32,
18    control: &ProductionControl<'_>,
19) -> Result<Produced<BitStringValue>> {
20    control.check()?;
21    let length = if modifier <= 0 || modifier as u32 > MAX_BIT_LENGTH {
22        1
23    } else {
24        modifier as u32
25    };
26    let mut bytes = ProductionVec::new(*control);
27    bytes.reserve(length.div_ceil(8) as usize)?;
28    for position in 0..length.div_ceil(8) {
29        let width = (length - position * 8).min(8);
30        let shift = length - position * 8 - width;
31        let chunk = if shift >= 64 {
32            if value < 0 {
33                u8::MAX
34            } else {
35                0
36            }
37        } else {
38            (value >> shift) as u8
39        };
40        bytes.push_copy(chunk << (8 - width))?;
41    }
42    finish_bits(bytes, length, control)
43}
44
45/// Interpret at most 32 bits as int4. Shorter inputs are unsigned; the full width preserves its sign bit.
46pub fn to_integer(value: &BitStringValue) -> Result<i32> {
47    if value.bit_len() > 32 {
48        return Err(error("22003", "integer out of range".into()));
49    }
50    Ok(to_unsigned(value) as i32)
51}
52
53/// Interpret at most 64 bits as int8. The fixed upper bound requires no traversal scratch or retained allocation.
54pub fn to_bigint(value: &BitStringValue) -> Result<i64> {
55    if value.bit_len() > 64 {
56        return Err(error("22003", "bigint out of range".into()));
57    }
58    Ok(to_unsigned(value) as i64)
59}
60
61fn to_unsigned(value: &BitStringValue) -> u64 {
62    let mut output = 0_u64;
63    for byte in value.as_bytes() {
64        output = (output << 8) | u64::from(*byte);
65    }
66    output >> ((8 - value.bit_len() % 8) % 8)
67}