diesel/type_impls/
floats.rs1use byteorder::{ReadBytesExt, WriteBytesExt};
2use std::error::Error;
3use std::io::prelude::*;
4
5use backend::Backend;
6use deserialize::{self, FromSql};
7use serialize::{self, IsNull, Output, ToSql};
8use sql_types;
9
10impl<DB: Backend<RawValue = [u8]>> FromSql<sql_types::Float, DB> for f32 {
11 fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
12 let mut bytes = not_none!(bytes);
13 debug_assert!(
14 bytes.len() <= 4,
15 "Received more than 4 bytes while decoding \
16 an f32. Was a double accidentally marked as float?"
17 );
18 bytes
19 .read_f32::<DB::ByteOrder>()
20 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
21 }
22}
23
24impl<DB: Backend> ToSql<sql_types::Float, DB> for f32 {
25 fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
26 out.write_f32::<DB::ByteOrder>(*self)
27 .map(|_| IsNull::No)
28 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
29 }
30}
31
32impl<DB: Backend<RawValue = [u8]>> FromSql<sql_types::Double, DB> for f64 {
33 fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
34 let mut bytes = not_none!(bytes);
35 debug_assert!(
36 bytes.len() <= 8,
37 "Received more than 8 bytes while decoding \
38 an f64. Was a numeric accidentally marked as double?"
39 );
40 bytes
41 .read_f64::<DB::ByteOrder>()
42 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
43 }
44}
45
46impl<DB: Backend> ToSql<sql_types::Double, DB> for f64 {
47 fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
48 out.write_f64::<DB::ByteOrder>(*self)
49 .map(|_| IsNull::No)
50 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
51 }
52}