diesel/type_impls/
integers.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::SmallInt, DB> for i16 {
11 fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
12 let mut bytes = not_none!(bytes);
13 debug_assert!(
14 bytes.len() <= 2,
15 "Received more than 2 bytes decoding i16. \
16 Was an Integer expression accidentally identified as SmallInt?"
17 );
18 debug_assert!(
19 bytes.len() >= 2,
20 "Received fewer than 2 bytes decoding i16. \
21 Was an expression of a different type accidentally identified \
22 as SmallInt?"
23 );
24 bytes
25 .read_i16::<DB::ByteOrder>()
26 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
27 }
28}
29
30impl<DB: Backend> ToSql<sql_types::SmallInt, DB> for i16 {
31 fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
32 out.write_i16::<DB::ByteOrder>(*self)
33 .map(|_| IsNull::No)
34 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
35 }
36}
37
38impl<DB: Backend<RawValue = [u8]>> FromSql<sql_types::Integer, DB> for i32 {
39 fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
40 let mut bytes = not_none!(bytes);
41 debug_assert!(
42 bytes.len() <= 4,
43 "Received more than 4 bytes decoding i32. \
44 Was a BigInteger expression accidentally identified as Integer?"
45 );
46 debug_assert!(
47 bytes.len() >= 4,
48 "Received fewer than 4 bytes decoding i32. \
49 Was a SmallInteger expression accidentally identified as Integer?"
50 );
51 bytes
52 .read_i32::<DB::ByteOrder>()
53 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
54 }
55}
56
57impl<DB: Backend> ToSql<sql_types::Integer, DB> for i32 {
58 fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
59 out.write_i32::<DB::ByteOrder>(*self)
60 .map(|_| IsNull::No)
61 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
62 }
63}
64
65impl<DB: Backend<RawValue = [u8]>> FromSql<sql_types::BigInt, DB> for i64 {
66 fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
67 let mut bytes = not_none!(bytes);
68 debug_assert!(
69 bytes.len() <= 8,
70 "Received more than 8 bytes decoding i64. \
71 Was an expression of a different type misidentified as BigInteger?"
72 );
73 debug_assert!(
74 bytes.len() >= 8,
75 "Received fewer than 8 bytes decoding i64. \
76 Was an Integer expression misidentified as BigInteger?"
77 );
78 bytes
79 .read_i64::<DB::ByteOrder>()
80 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
81 }
82}
83
84impl<DB: Backend> ToSql<sql_types::BigInt, DB> for i64 {
85 fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
86 out.write_i64::<DB::ByteOrder>(*self)
87 .map(|_| IsNull::No)
88 .map_err(|e| Box::new(e) as Box<dyn Error + Send + Sync>)
89 }
90}