| 1 | use crate::decode::Decode; |
| 2 | use crate::encode::{Encode, IsNull}; |
| 3 | use crate::error::BoxDynError; |
| 4 | use crate::types::Type; |
| 5 | use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres}; |
| 6 | |
| 7 | impl Type<Postgres> for bool { |
| 8 | fn type_info() -> PgTypeInfo { |
| 9 | PgTypeInfo::BOOL |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | impl PgHasArrayType for bool { |
| 14 | fn array_type_info() -> PgTypeInfo { |
| 15 | PgTypeInfo::BOOL_ARRAY |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | impl Encode<'_, Postgres> for bool { |
| 20 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> { |
| 21 | buf.push(*self as u8); |
| 22 | |
| 23 | Ok(IsNull::No) |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | impl Decode<'_, Postgres> for bool { |
| 28 | fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> { |
| 29 | Ok(match value.format() { |
| 30 | PgValueFormat::Binary => value.as_bytes()?[0] != 0, |
| 31 | |
| 32 | PgValueFormat::Text => match value.as_str()? { |
| 33 | "t" => true, |
| 34 | "f" => false, |
| 35 | |
| 36 | s => { |
| 37 | return Err(format!("unexpected value {s:?} for boolean").into()); |
| 38 | } |
| 39 | }, |
| 40 | }) |
| 41 | } |
| 42 | } |