Skip to main content

sqlx_mysql/types/
int.rs

1use byteorder::{ByteOrder, LittleEndian};
2
3use crate::decode::Decode;
4use crate::encode::{Encode, IsNull};
5use crate::error::BoxDynError;
6use crate::protocol::text::{ColumnFlags, ColumnType};
7use crate::types::Type;
8use crate::{MySql, MySqlTypeInfo, MySqlValueFormat, MySqlValueRef};
9
10fn int_compatible(ty: &MySqlTypeInfo) -> bool {
11    matches!(
12        ty.r#type,
13        ColumnType::Tiny
14            | ColumnType::Short
15            | ColumnType::Long
16            | ColumnType::Int24
17            | ColumnType::LongLong
18    ) && !ty.flags.contains(ColumnFlags::UNSIGNED)
19}
20
21impl Type<MySql> for i8 {
22    fn type_info() -> MySqlTypeInfo {
23        MySqlTypeInfo::binary(ColumnType::Tiny)
24    }
25
26    fn compatible(ty: &MySqlTypeInfo) -> bool {
27        int_compatible(ty)
28    }
29}
30
31impl Type<MySql> for i16 {
32    fn type_info() -> MySqlTypeInfo {
33        MySqlTypeInfo::binary(ColumnType::Short)
34    }
35
36    fn compatible(ty: &MySqlTypeInfo) -> bool {
37        int_compatible(ty)
38    }
39}
40
41impl Type<MySql> for i32 {
42    fn type_info() -> MySqlTypeInfo {
43        MySqlTypeInfo::binary(ColumnType::Long)
44    }
45
46    fn compatible(ty: &MySqlTypeInfo) -> bool {
47        int_compatible(ty)
48    }
49}
50
51impl Type<MySql> for i64 {
52    fn type_info() -> MySqlTypeInfo {
53        MySqlTypeInfo::binary(ColumnType::LongLong)
54    }
55
56    fn compatible(ty: &MySqlTypeInfo) -> bool {
57        int_compatible(ty)
58    }
59}
60
61impl Encode<'_, MySql> for i8 {
62    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
63        buf.extend(&self.to_le_bytes());
64
65        Ok(IsNull::No)
66    }
67}
68
69impl Encode<'_, MySql> for i16 {
70    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
71        buf.extend(&self.to_le_bytes());
72
73        Ok(IsNull::No)
74    }
75}
76
77impl Encode<'_, MySql> for i32 {
78    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
79        buf.extend(&self.to_le_bytes());
80
81        Ok(IsNull::No)
82    }
83}
84
85impl Encode<'_, MySql> for i64 {
86    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
87        buf.extend(&self.to_le_bytes());
88
89        Ok(IsNull::No)
90    }
91}
92
93/// Integer part of a textual `DECIMAL`, erroring if it has a nonzero fraction.
94pub(super) fn integral_decimal_str(s: &str) -> Result<&str, BoxDynError> {
95    let (int_part, frac_part) = s.split_once('.').unwrap_or((s, ""));
96
97    if frac_part.bytes().any(|b| b != b'0') {
98        return Err(format!("DECIMAL value `{s}` has a fractional part").into());
99    }
100
101    Ok(int_part)
102}
103
104fn int_decode(value: MySqlValueRef<'_>) -> Result<i64, BoxDynError> {
105    // DECIMAL is ASCII text even over the binary protocol, so parse the digits
106    // instead of reading the bytes as a little-endian integer.
107    if matches!(
108        value.type_info.r#type,
109        ColumnType::Decimal | ColumnType::NewDecimal
110    ) {
111        return integral_decimal_str(value.as_str()?)?
112            .parse()
113            .map_err(Into::into);
114    }
115
116    Ok(match value.format() {
117        MySqlValueFormat::Text => value.as_str()?.parse()?,
118        MySqlValueFormat::Binary => {
119            let buf = value.as_bytes()?;
120
121            // Check conditions that could cause `read_int()` to panic.
122            if buf.is_empty() {
123                return Err("empty buffer".into());
124            }
125
126            if buf.len() > 8 {
127                return Err(format!(
128                    "expected no more than 8 bytes for integer value, got {}",
129                    buf.len()
130                )
131                .into());
132            }
133
134            LittleEndian::read_int(buf, buf.len())
135        }
136    })
137}
138
139impl Decode<'_, MySql> for i8 {
140    fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
141        int_decode(value)?.try_into().map_err(Into::into)
142    }
143}
144
145impl Decode<'_, MySql> for i16 {
146    fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
147        int_decode(value)?.try_into().map_err(Into::into)
148    }
149}
150
151impl Decode<'_, MySql> for i32 {
152    fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
153        int_decode(value)?.try_into().map_err(Into::into)
154    }
155}
156
157impl Decode<'_, MySql> for i64 {
158    fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
159        int_decode(value)
160    }
161}