]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/test.rs
std: Add more entries to stdtest base_port
[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 prelude::v1::*;
12
13 use env;
14 use net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
15 use sync::atomic::{AtomicUsize, Ordering};
16
17 static PORT: AtomicUsize = AtomicUsize::new(0);
18
19 pub fn next_test_ip4() -> SocketAddr {
20     let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port();
21     SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))
22 }
23
24 pub fn next_test_ip6() -> SocketAddr {
25     let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port();
26     SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1),
27                                      port, 0, 0))
28 }
29
30 pub fn sa4(a: Ipv4Addr, p: u16) -> SocketAddr {
31     SocketAddr::V4(SocketAddrV4::new(a, p))
32 }
33
34 pub fn sa6(a: Ipv6Addr, p: u16) -> SocketAddr {
35     SocketAddr::V6(SocketAddrV6::new(a, p, 0, 0))
36 }
37
38 pub fn tsa<A: ToSocketAddrs>(a: A) -> Result<Vec<SocketAddr>, String> {
39     match a.to_socket_addrs() {
40         Ok(a) => Ok(a.collect()),
41         Err(e) => Err(e.to_string()),
42     }
43 }
44
45 // The bots run multiple builds at the same time, and these builds
46 // all want to use ports. This function figures out which workspace
47 // it is running in and assigns a port range based on it.
48 fn base_port() -> u16 {
49     let cwd = env::current_dir().unwrap();
50     let dirs = ["32-opt", "32-nopt",
51                 "musl-64-opt", "cross-opt",
52                 "64-opt", "64-nopt", "64-opt-vg", "64-debug-opt",
53                 "all-opt", "snap3", "dist"];
54     dirs.iter().enumerate().find(|&(_, dir)| {
55         cwd.to_str().unwrap().contains(dir)
56     }).map(|p| p.0).unwrap_or(0) as u16 * 1000 + 19600
57 }