| 1 | use byteorder::{BigEndian, ByteOrder}; |
| 2 | |
| 3 | use crate::decode::Decode; |
| 4 | use crate::encode::{Encode, IsNull}; |
| 5 | use crate::error::BoxDynError; |
| 6 | use crate::types::Type; |
| 7 | use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres}; |
| 8 | |
| 9 | impl Type<Postgres> for f32 { |
| 10 | fn type_info() -> PgTypeInfo { |
| 11 | PgTypeInfo::FLOAT4 |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | impl PgHasArrayType for f32 { |
| 16 | fn array_type_info() -> PgTypeInfo { |
| 17 | PgTypeInfo::FLOAT4_ARRAY |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | impl Encode<'_, Postgres> for f32 { |
| 22 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> { |
| 23 | buf.extend(&self.to_be_bytes()); |
| 24 | |
| 25 | Ok(IsNull::No) |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | impl Decode<'_, Postgres> for f32 { |
| 30 | fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> { |
| 31 | Ok(match value.format() { |
| 32 | PgValueFormat::Binary => BigEndian::read_f32(value.as_bytes()?), |
| 33 | PgValueFormat::Text => value.as_str()?.parse()?, |
| 34 | }) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | impl Type<Postgres> for f64 { |
| 39 | fn type_info() -> PgTypeInfo { |
| 40 | PgTypeInfo::FLOAT8 |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | impl PgHasArrayType for f64 { |
| 45 | fn array_type_info() -> PgTypeInfo { |
| 46 | PgTypeInfo::FLOAT8_ARRAY |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl Encode<'_, Postgres> for f64 { |
| 51 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> { |
| 52 | buf.extend(&self.to_be_bytes()); |
| 53 | |
| 54 | Ok(IsNull::No) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | impl Decode<'_, Postgres> for f64 { |
| 59 | fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> { |
| 60 | Ok(match value.format() { |
| 61 | PgValueFormat::Binary => BigEndian::read_f64(value.as_bytes()?), |
| 62 | PgValueFormat::Text => value.as_str()?.parse()?, |
| 63 | }) |
| 64 | } |
| 65 | } |