sqlx_postgres/types/
float.rs

1use byteorder::{BigEndian, ByteOrder};
2
3use crate::decode::Decode;
4use crate::encode::{Encode, IsNull};
5use crate::error::BoxDynError;
6use crate::types::Type;
7use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres};
8
9impl Type<Postgres> for f32 {
10    fn type_info() -> PgTypeInfo {
11        PgTypeInfo::FLOAT4
12    }
13}
14
15impl PgHasArrayType for f32 {
16    fn array_type_info() -> PgTypeInfo {
17        PgTypeInfo::FLOAT4_ARRAY
18    }
19}
20
21impl 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
29impl 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
38impl Type<Postgres> for f64 {
39    fn type_info() -> PgTypeInfo {
40        PgTypeInfo::FLOAT8
41    }
42}
43
44impl PgHasArrayType for f64 {
45    fn array_type_info() -> PgTypeInfo {
46        PgTypeInfo::FLOAT8_ARRAY
47    }
48}
49
50impl 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
58impl 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}