|
1 | 1 | // Take a look at the license at the top of the repository in the LICENSE file. |
2 | 2 |
|
3 | | -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; |
| 3 | +use std::net::IpAddr; |
4 | 4 |
|
5 | 5 | use glib::{prelude::*, translate::*}; |
6 | 6 |
|
@@ -80,16 +80,33 @@ impl From<IpAddr> for InetAddress { |
80 | 80 |
|
81 | 81 | impl From<InetAddress> for IpAddr { |
82 | 82 | fn from(addr: InetAddress) -> Self { |
83 | | - let size = addr.native_size(); |
84 | | - unsafe { |
85 | | - let bytes = ffi::g_inet_address_to_bytes(addr.to_glib_none().0); |
86 | | - if size == 4 { |
87 | | - Self::V4(Ipv4Addr::from(*(bytes as *const [u8; 4]))) |
88 | | - } else if size == 16 { |
89 | | - Self::V6(Ipv6Addr::from(*(bytes as *const [u16; 8]))) |
90 | | - } else { |
91 | | - panic!("Unknown IP kind"); |
92 | | - } |
| 83 | + match addr.to_bytes() { |
| 84 | + Some(InetAddressBytes::V4(bytes)) => IpAddr::from(*bytes), |
| 85 | + Some(InetAddressBytes::V6(bytes)) => IpAddr::from(*bytes), |
| 86 | + None => panic!("Unknown IP kind"), |
93 | 87 | } |
94 | 88 | } |
95 | 89 | } |
| 90 | + |
| 91 | +#[cfg(test)] |
| 92 | +mod tests { |
| 93 | + use std::net::IpAddr; |
| 94 | + |
| 95 | + use crate::InetAddress; |
| 96 | + |
| 97 | + #[test] |
| 98 | + fn test_ipv6_to_rust() { |
| 99 | + let rust_addr = "2606:50c0:8000::153".parse::<IpAddr>().unwrap(); |
| 100 | + assert!(rust_addr.is_ipv6()); |
| 101 | + let gio_addr = InetAddress::from(rust_addr); |
| 102 | + assert_eq!(rust_addr, IpAddr::from(gio_addr)); |
| 103 | + } |
| 104 | + |
| 105 | + #[test] |
| 106 | + fn test_ipv4_to_rust() { |
| 107 | + let rust_addr = "185.199.108.153".parse::<IpAddr>().unwrap(); |
| 108 | + assert!(rust_addr.is_ipv4()); |
| 109 | + let gio_addr = InetAddress::from(rust_addr); |
| 110 | + assert_eq!(rust_addr, IpAddr::from(gio_addr)); |
| 111 | + } |
| 112 | +} |
0 commit comments