sqlx_mysql/types/
inet.rs

1use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
2
3use crate::decode::Decode;
4use crate::encode::{Encode, IsNull};
5use crate::error::BoxDynError;
6use crate::io::MySqlBufMutExt;
7use crate::types::Type;
8use crate::{MySql, MySqlTypeInfo, MySqlValueRef};
9
10impl Type<MySql> for Ipv4Addr {
11    fn type_info() -> MySqlTypeInfo {
12        <&str as Type<MySql>>::type_info()
13    }
14
15    fn compatible(ty: &MySqlTypeInfo) -> bool {
16        <&str as Type<MySql>>::compatible(ty)
17    }
18}
19
20impl Encode<'_, MySql> for Ipv4Addr {
21    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
22        buf.put_str_lenenc(&self.to_string());
23
24        Ok(IsNull::No)
25    }
26}
27
28impl Decode<'_, MySql> for Ipv4Addr {
29    fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
30        // delegate to the &str type to decode from MySQL
31        let text = <&str as Decode<MySql>>::decode(value)?;
32
33        // parse a Ipv4Addr from the text
34        text.parse().map_err(Into::into)
35    }
36}
37
38impl Type<MySql> for Ipv6Addr {
39    fn type_info() -> MySqlTypeInfo {
40        <&str as Type<MySql>>::type_info()
41    }
42
43    fn compatible(ty: &MySqlTypeInfo) -> bool {
44        <&str as Type<MySql>>::compatible(ty)
45    }
46}
47
48impl Encode<'_, MySql> for Ipv6Addr {
49    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
50        buf.put_str_lenenc(&self.to_string());
51
52        Ok(IsNull::No)
53    }
54}
55
56impl Decode<'_, MySql> for Ipv6Addr {
57    fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
58        // delegate to the &str type to decode from MySQL
59        let text = <&str as Decode<MySql>>::decode(value)?;
60
61        // parse a Ipv6Addr from the text
62        text.parse().map_err(Into::into)
63    }
64}
65
66impl Type<MySql> for IpAddr {
67    fn type_info() -> MySqlTypeInfo {
68        <&str as Type<MySql>>::type_info()
69    }
70
71    fn compatible(ty: &MySqlTypeInfo) -> bool {
72        <&str as Type<MySql>>::compatible(ty)
73    }
74}
75
76impl Encode<'_, MySql> for IpAddr {
77    fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
78        buf.put_str_lenenc(&self.to_string());
79
80        Ok(IsNull::No)
81    }
82}
83
84impl Decode<'_, MySql> for IpAddr {
85    fn decode(value: MySqlValueRef<'_>) -> Result<Self, BoxDynError> {
86        // delegate to the &str type to decode from MySQL
87        let text = <&str as Decode<MySql>>::decode(value)?;
88
89        // parse a IpAddr from the text
90        text.parse().map_err(Into::into)
91    }
92}