diff options
| author | Luqman Aden <me@luqman.ca> | 2013-07-25 18:18:43 -0400 |
|---|---|---|
| committer | Luqman Aden <me@luqman.ca> | 2013-07-25 18:27:18 -0400 |
| commit | 005ea3b17375584f823c51d141248e3bcbc04115 (patch) | |
| tree | 92b4fb55bc62123601e2ba9dc4f48e95660a5dd6 /src/libstd | |
| parent | d6e1a6b237d4c3b04a7dff6609c3427eb99bbc60 (diff) | |
| download | rust-005ea3b17375584f823c51d141248e3bcbc04115.tar.gz rust-005ea3b17375584f823c51d141248e3bcbc04115.zip | |
libstd: Add ToStr impl for IpAddr.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/rt/io/net/ip.rs | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/libstd/rt/io/net/ip.rs b/src/libstd/rt/io/net/ip.rs index 3a93fd70543..2b572574b60 100644 --- a/src/libstd/rt/io/net/ip.rs +++ b/src/libstd/rt/io/net/ip.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use num::FromStrRadix; +use to_str::ToStr; + type Port = u16; #[deriving(Eq, TotalEq)] @@ -15,3 +18,42 @@ pub enum IpAddr { Ipv4(u8, u8, u8, u8, Port), Ipv6(u16, u16, u16, u16, u16, u16, u16, u16, Port) } + +impl ToStr for IpAddr { + fn to_str(&self) -> ~str { + match *self { + Ipv4(a, b, c, d, p) => + fmt!("%u.%u.%u.%u:%u", + a as uint, b as uint, c as uint, d as uint, p as uint), + + // Ipv4 Compatible address + Ipv6(0, 0, 0, 0, 0, 0, g, h, p) => { + let a = fmt!("%04x", g as uint); + let b = FromStrRadix::from_str_radix(a.slice(2, 4), 16).unwrap(); + let a = FromStrRadix::from_str_radix(a.slice(0, 2), 16).unwrap(); + let c = fmt!("%04x", h as uint); + let d = FromStrRadix::from_str_radix(c.slice(2, 4), 16).unwrap(); + let c = FromStrRadix::from_str_radix(c.slice(0, 2), 16).unwrap(); + + fmt!("[::%u.%u.%u.%u]:%u", a, b, c, d, p as uint) + } + + // Ipv4-Mapped address + Ipv6(0, 0, 0, 0, 0, 1, g, h, p) => { + let a = fmt!("%04x", g as uint); + let b = FromStrRadix::from_str_radix(a.slice(2, 4), 16).unwrap(); + let a = FromStrRadix::from_str_radix(a.slice(0, 2), 16).unwrap(); + let c = fmt!("%04x", h as uint); + let d = FromStrRadix::from_str_radix(c.slice(2, 4), 16).unwrap(); + let c = FromStrRadix::from_str_radix(c.slice(0, 2), 16).unwrap(); + + fmt!("[::FFFF:%u.%u.%u.%u]:%u", a, b, c, d, p as uint) + } + + Ipv6(a, b, c, d, e, f, g, h, p) => + fmt!("[%x:%x:%x:%x:%x:%x:%x:%x]:%u", + a as uint, b as uint, c as uint, d as uint, + e as uint, f as uint, g as uint, h as uint, p as uint) + } + } +} |
