uqa_sql/expr/bit_string/
integer.rs1use super::{
10 error, finish_bits, BitStringValue, Produced, ProductionControl, ProductionVec, Result,
11 MAX_BIT_LENGTH,
12};
13
14pub 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
45pub 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
53pub 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}