]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/test.rs
Auto merge of #35856 - phimuemue:master, r=brson
[rust.git] / src / libstd / net / test.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use env;
12 use net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
13 use sync::atomic::{AtomicUsize, Ordering};
14
15 static PORT: AtomicUsize = AtomicUsize::new(0);
16
17 pub fn next_test_ip4() -> SocketAddr {
18     let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port();
19     SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))
20 }
21
22 pub fn next_test_ip6() -> SocketAddr {
23     let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port();
24     SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1),
25                                      port, 0, 0))
26 }
27
28 pub fn sa4(a: Ipv4Addr, p: u16) -> SocketAddr {
29     SocketAddr::V4(SocketAddrV4::new(a, p))
30 }
31
32 pub fn sa6(a: Ipv6Addr, p: u16) -> SocketAddr {
33     SocketAddr::V6(SocketAddrV6::new(a, p, 0, 0))
34 }
35
36 pub fn tsa<A: ToSocketAddrs>(a: A) -> Result<Vec<SocketAddr>, String> {
37     match a.to_socket_addrs() {
38         Ok(a) => Ok(a.collect()),
39         Err(e) => Err(e.to_string()),
40     }
41 }
42
43 // The bots run multiple builds at the same time, and these builds
44 // all want to use ports. This function figures out which workspace
45 // it is running in and assigns a port range based on it.
46 fn base_port() -> u16 {
47     let cwd = env::current_dir().unwrap();
48     let dirs = ["32-opt", "32-nopt",
49                 "musl-64-opt", "cross-opt",
50                 "64-opt", "64-nopt", "64-opt-vg", "64-debug-opt",
51                 "all-opt", "snap3", "dist"];
52     dirs.iter().enumerate().find(|&(_, dir)| {
53         cwd.to_str().unwrap().contains(dir)
54     }).map(|p| p.0).unwrap_or(0) as u16 * 1000 + 19600
55 }