| 1 | use crate::arguments::value_size_int4_checked; |
| 2 | use crate::{ |
| 3 | decode::Decode, |
| 4 | encode::{Encode, IsNull}, |
| 5 | error::BoxDynError, |
| 6 | types::Type, |
| 7 | PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres, |
| 8 | }; |
| 9 | use bit_vec::BitVec; |
| 10 | use sqlx_core::bytes::Buf; |
| 11 | use std::{io, mem}; |
| 12 | |
| 13 | impl Type<Postgres> for BitVec { |
| 14 | fn type_info() -> PgTypeInfo { |
| 15 | PgTypeInfo::VARBIT |
| 16 | } |
| 17 | |
| 18 | fn compatible(ty: &PgTypeInfo) -> bool { |
| 19 | *ty == PgTypeInfo::BIT || *ty == PgTypeInfo::VARBIT |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | impl PgHasArrayType for BitVec { |
| 24 | fn array_type_info() -> PgTypeInfo { |
| 25 | PgTypeInfo::VARBIT_ARRAY |
| 26 | } |
| 27 | |
| 28 | fn array_compatible(ty: &PgTypeInfo) -> bool { |
| 29 | *ty == PgTypeInfo::BIT_ARRAY || *ty == PgTypeInfo::VARBIT_ARRAY |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl Encode<'_, Postgres> for BitVec { |
| 34 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> { |
| 35 | let len = value_size_int4_checked(self.len())?; |
| 36 | |
| 37 | buf.extend(len.to_be_bytes()); |
| 38 | buf.extend(self.to_bytes()); |
| 39 | |
| 40 | Ok(IsNull::No) |
| 41 | } |
| 42 | |
| 43 | fn size_hint(&self) -> usize { |
| 44 | mem::size_of::<i32>() + self.len() |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | impl Decode<'_, Postgres> for BitVec { |
| 49 | fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> { |
| 50 | match value.format() { |
| 51 | PgValueFormat::Binary => { |
| 52 | let mut bytes = value.as_bytes()?; |
| 53 | let len = bytes.get_i32(); |
| 54 | |
| 55 | let len = usize::try_from(len).map_err(|_| format!("invalid VARBIT len: {len}"))?; |
| 56 | |
| 57 | // The smallest amount of data we can read is one byte |
| 58 | let bytes_len = (len + 7) / 8; |
| 59 | |
| 60 | if bytes.remaining() != bytes_len { |
| 61 | Err(io::Error::new( |
| 62 | io::ErrorKind::InvalidData, |
| 63 | "VARBIT length mismatch.", |
| 64 | ))?; |
| 65 | } |
| 66 | |
| 67 | let mut bitvec = BitVec::from_bytes(bytes); |
| 68 | |
| 69 | // Chop off zeroes from the back. We get bits in bytes, so if |
| 70 | // our bitvec is not in full bytes, extra zeroes are added to |
| 71 | // the end. |
| 72 | while bitvec.len() > len { |
| 73 | bitvec.pop(); |
| 74 | } |
| 75 | |
| 76 | Ok(bitvec) |
| 77 | } |
| 78 | PgValueFormat::Text => { |
| 79 | let s = value.as_str()?; |
| 80 | let mut bit_vec = BitVec::with_capacity(s.len()); |
| 81 | |
| 82 | for c in s.chars() { |
| 83 | match c { |
| 84 | '0' => bit_vec.push(false), |
| 85 | '1' => bit_vec.push(true), |
| 86 | _ => { |
| 87 | Err(io::Error::new( |
| 88 | io::ErrorKind::InvalidData, |
| 89 | "VARBIT data contains other characters than 1 or 0.", |
| 90 | ))?; |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | Ok(bit_vec) |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | } |